alloy_node_bindings/nodes/
geth.rs1use crate::{
4 utils::{extract_endpoint, extract_value, unused_port},
5 NodeError, NODE_DIAL_LOOP_TIMEOUT, NODE_STARTUP_TIMEOUT,
6};
7use alloy_genesis::{CliqueConfig, Genesis};
8use alloy_primitives::Address;
9use k256::ecdsa::SigningKey;
10use std::{
11 ffi::OsString,
12 fs::{create_dir, File},
13 io::{BufRead, BufReader},
14 path::PathBuf,
15 process::{Child, ChildStderr, Command, Stdio},
16 time::Instant,
17};
18use tempfile::tempdir;
19use url::Url;
20
21const API: &str = "eth,net,web3,txpool,admin,personal,miner,debug";
23
24const GETH: &str = "geth";
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum NodeMode {
30 Dev(DevOptions),
32 NonDev(PrivateNetOptions),
34}
35
36impl Default for NodeMode {
37 fn default() -> Self {
38 Self::Dev(Default::default())
39 }
40}
41
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct DevOptions {
45 pub block_time: Option<u64>,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub struct PrivateNetOptions {
52 pub p2p_port: Option<u16>,
54
55 pub discovery: bool,
57}
58
59impl Default for PrivateNetOptions {
60 fn default() -> Self {
61 Self { p2p_port: None, discovery: true }
62 }
63}
64
65#[derive(Debug)]
69pub struct GethInstance {
70 pid: Child,
71 port: u16,
72 p2p_port: Option<u16>,
73 auth_port: Option<u16>,
74 ipc: Option<PathBuf>,
75 data_dir: Option<PathBuf>,
76 genesis: Option<Genesis>,
77 clique_private_key: Option<SigningKey>,
78}
79
80impl GethInstance {
81 pub const fn port(&self) -> u16 {
83 self.port
84 }
85
86 pub const fn p2p_port(&self) -> Option<u16> {
88 self.p2p_port
89 }
90
91 pub const fn auth_port(&self) -> Option<u16> {
93 self.auth_port
94 }
95
96 #[doc(alias = "http_endpoint")]
98 pub fn endpoint(&self) -> String {
99 format!("http://localhost:{}", self.port)
100 }
101
102 pub fn ws_endpoint(&self) -> String {
104 format!("ws://localhost:{}", self.port)
105 }
106
107 pub fn ipc_endpoint(&self) -> String {
109 self.ipc.clone().map_or_else(|| "geth.ipc".to_string(), |ipc| ipc.display().to_string())
110 }
111
112 #[doc(alias = "http_endpoint_url")]
114 pub fn endpoint_url(&self) -> Url {
115 Url::parse(&self.endpoint()).unwrap()
116 }
117
118 pub fn ws_endpoint_url(&self) -> Url {
120 Url::parse(&self.ws_endpoint()).unwrap()
121 }
122
123 pub const fn data_dir(&self) -> Option<&PathBuf> {
125 self.data_dir.as_ref()
126 }
127
128 pub const fn genesis(&self) -> Option<&Genesis> {
130 self.genesis.as_ref()
131 }
132
133 #[deprecated = "clique support was removed in geth >=1.14"]
135 pub const fn clique_private_key(&self) -> Option<&SigningKey> {
136 self.clique_private_key.as_ref()
137 }
138
139 pub fn stderr(&mut self) -> Result<ChildStderr, NodeError> {
144 self.pid.stderr.take().ok_or(NodeError::NoStderr)
145 }
146
147 pub fn wait_to_add_peer(&mut self, id: &str) -> Result<(), NodeError> {
151 let mut stderr = self.pid.stderr.as_mut().ok_or(NodeError::NoStderr)?;
152 let mut err_reader = BufReader::new(&mut stderr);
153 let mut line = String::new();
154 let start = Instant::now();
155
156 while start.elapsed() < NODE_DIAL_LOOP_TIMEOUT {
157 line.clear();
158 err_reader.read_line(&mut line).map_err(NodeError::ReadLineError)?;
159
160 let truncated_id = if id.len() > 16 { &id[..16] } else { id };
162 if line.contains("Adding p2p peer") && line.contains(truncated_id) {
163 return Ok(());
164 }
165 }
166 Err(NodeError::Timeout)
167 }
168}
169
170impl Drop for GethInstance {
171 fn drop(&mut self) {
172 self.pid.kill().expect("could not kill geth");
173 }
174}
175
176#[derive(Clone, Debug, Default)]
195#[must_use = "This Builder struct does nothing unless it is `spawn`ed"]
196pub struct Geth {
197 program: Option<PathBuf>,
198 port: Option<u16>,
199 authrpc_port: Option<u16>,
200 ipc_path: Option<PathBuf>,
201 ipc_enabled: bool,
202 data_dir: Option<PathBuf>,
203 chain_id: Option<u64>,
204 insecure_unlock: bool,
205 keep_err: bool,
206 genesis: Option<Genesis>,
207 mode: NodeMode,
208 clique_private_key: Option<SigningKey>,
209 args: Vec<OsString>,
210}
211
212impl Geth {
213 pub fn new() -> Self {
215 Self::default()
216 }
217
218 pub fn at(path: impl Into<PathBuf>) -> Self {
231 Self::new().path(path)
232 }
233
234 pub fn path<T: Into<PathBuf>>(mut self, path: T) -> Self {
239 self.program = Some(path.into());
240 self
241 }
242
243 pub fn dev(mut self) -> Self {
245 self.mode = NodeMode::Dev(Default::default());
246 self
247 }
248
249 pub const fn is_clique(&self) -> bool {
251 self.clique_private_key.is_some()
252 }
253
254 pub fn clique_address(&self) -> Option<Address> {
256 self.clique_private_key.as_ref().map(|pk| Address::from_public_key(pk.verifying_key()))
257 }
258
259 #[deprecated = "clique support was removed in geth >=1.14"]
265 pub fn set_clique_private_key<T: Into<SigningKey>>(mut self, private_key: T) -> Self {
266 self.clique_private_key = Some(private_key.into());
267 self
268 }
269
270 pub fn port<T: Into<u16>>(mut self, port: T) -> Self {
275 self.port = Some(port.into());
276 self
277 }
278
279 pub fn p2p_port(mut self, port: u16) -> Self {
284 match &mut self.mode {
285 NodeMode::Dev(_) => {
286 self.mode = NodeMode::NonDev(PrivateNetOptions {
287 p2p_port: Some(port),
288 ..Default::default()
289 })
290 }
291 NodeMode::NonDev(opts) => opts.p2p_port = Some(port),
292 }
293 self
294 }
295
296 pub const fn block_time(mut self, block_time: u64) -> Self {
301 self.mode = NodeMode::Dev(DevOptions { block_time: Some(block_time) });
302 self
303 }
304
305 pub const fn chain_id(mut self, chain_id: u64) -> Self {
307 self.chain_id = Some(chain_id);
308 self
309 }
310
311 pub const fn insecure_unlock(mut self) -> Self {
313 self.insecure_unlock = true;
314 self
315 }
316
317 pub const fn enable_ipc(mut self) -> Self {
319 self.ipc_enabled = true;
320 self
321 }
322
323 pub fn disable_discovery(mut self) -> Self {
328 self.inner_disable_discovery();
329 self
330 }
331
332 fn inner_disable_discovery(&mut self) {
333 match &mut self.mode {
334 NodeMode::Dev(_) => {
335 self.mode =
336 NodeMode::NonDev(PrivateNetOptions { discovery: false, ..Default::default() })
337 }
338 NodeMode::NonDev(opts) => opts.discovery = false,
339 }
340 }
341
342 pub fn ipc_path<T: Into<PathBuf>>(mut self, path: T) -> Self {
344 self.ipc_path = Some(path.into());
345 self
346 }
347
348 pub fn data_dir<T: Into<PathBuf>>(mut self, path: T) -> Self {
350 self.data_dir = Some(path.into());
351 self
352 }
353
354 pub fn genesis(mut self, genesis: Genesis) -> Self {
361 self.genesis = Some(genesis);
362 self
363 }
364
365 pub const fn authrpc_port(mut self, port: u16) -> Self {
367 self.authrpc_port = Some(port);
368 self
369 }
370
371 pub const fn keep_stderr(mut self) -> Self {
375 self.keep_err = true;
376 self
377 }
378
379 pub fn push_arg<T: Into<OsString>>(&mut self, arg: T) {
381 self.args.push(arg.into());
382 }
383
384 pub fn extend_args<I, S>(&mut self, args: I)
386 where
387 I: IntoIterator<Item = S>,
388 S: Into<OsString>,
389 {
390 for arg in args {
391 self.push_arg(arg);
392 }
393 }
394
395 pub fn arg<T: Into<OsString>>(mut self, arg: T) -> Self {
399 self.args.push(arg.into());
400 self
401 }
402
403 pub fn args<I, S>(mut self, args: I) -> Self
407 where
408 I: IntoIterator<Item = S>,
409 S: Into<OsString>,
410 {
411 for arg in args {
412 self = self.arg(arg);
413 }
414 self
415 }
416
417 #[track_caller]
423 pub fn spawn(self) -> GethInstance {
424 self.try_spawn().unwrap()
425 }
426
427 pub fn try_spawn(mut self) -> Result<GethInstance, NodeError> {
429 let bin_path = self
430 .program
431 .as_ref()
432 .map_or_else(|| GETH.as_ref(), |bin| bin.as_os_str())
433 .to_os_string();
434 let mut cmd = Command::new(&bin_path);
435 cmd.stderr(Stdio::piped());
437
438 let mut port = self.port.unwrap_or(0);
440 let port_s = port.to_string();
441
442 if !self.ipc_enabled {
444 cmd.arg("--ipcdisable");
445 }
446
447 cmd.arg("--http");
449 cmd.arg("--http.port").arg(&port_s);
450 cmd.arg("--http.api").arg(API);
451
452 cmd.arg("--ws");
454 cmd.arg("--ws.port").arg(port_s);
455 cmd.arg("--ws.api").arg(API);
456
457 let is_clique = self.is_clique();
459 if self.insecure_unlock || is_clique {
460 cmd.arg("--allow-insecure-unlock");
461 }
462
463 if is_clique {
464 self.inner_disable_discovery();
465 }
466
467 let authrpc_port = self.authrpc_port.unwrap_or_else(&mut unused_port);
469 cmd.arg("--authrpc.port").arg(authrpc_port.to_string());
470
471 if is_clique {
473 let clique_addr = self.clique_address();
474 if let Some(genesis) = &mut self.genesis {
475 let clique_config = CliqueConfig { period: Some(0), epoch: Some(8) };
477 genesis.config.clique = Some(clique_config);
478
479 let clique_addr = clique_addr.ok_or_else(|| {
480 NodeError::CliqueAddressError(
481 "could not calculates the address of the Clique consensus address."
482 .to_string(),
483 )
484 })?;
485
486 let extra_data_bytes =
488 [&[0u8; 32][..], clique_addr.as_ref(), &[0u8; 65][..]].concat();
489 genesis.extra_data = extra_data_bytes.into();
490 }
491
492 let clique_addr = self.clique_address().ok_or_else(|| {
493 NodeError::CliqueAddressError(
494 "could not calculates the address of the Clique consensus address.".to_string(),
495 )
496 })?;
497
498 self.genesis = Some(Genesis::clique_genesis(
499 self.chain_id.ok_or(NodeError::ChainIdNotSet)?,
500 clique_addr,
501 ));
502
503 cmd.arg("--miner.etherbase").arg(format!("{clique_addr:?}"));
507 }
508
509 if let Some(genesis) = &self.genesis {
510 let temp_genesis_dir_path = tempdir().map_err(NodeError::CreateDirError)?.keep();
512
513 let temp_genesis_path = temp_genesis_dir_path.join("genesis.json");
515
516 let mut file = File::create(&temp_genesis_path).map_err(|_| {
518 NodeError::GenesisError("could not create genesis file".to_string())
519 })?;
520
521 serde_json::to_writer_pretty(&mut file, &genesis).map_err(|_| {
523 NodeError::GenesisError("could not write genesis to file".to_string())
524 })?;
525
526 let mut init_cmd = Command::new(bin_path);
527 if let Some(data_dir) = &self.data_dir {
528 init_cmd.arg("--datadir").arg(data_dir);
529 }
530
531 init_cmd.stderr(Stdio::null());
533
534 init_cmd.arg("init").arg(temp_genesis_path);
535 let res = init_cmd
536 .spawn()
537 .map_err(NodeError::SpawnError)?
538 .wait()
539 .map_err(NodeError::WaitError)?;
540 if !res.success() {
542 return Err(NodeError::InitError);
543 }
544
545 std::fs::remove_dir_all(temp_genesis_dir_path).map_err(|_| {
547 NodeError::GenesisError("could not remove genesis temp dir".to_string())
548 })?;
549 }
550
551 if let Some(data_dir) = &self.data_dir {
552 cmd.arg("--datadir").arg(data_dir);
553
554 if !data_dir.exists() {
556 create_dir(data_dir).map_err(NodeError::CreateDirError)?;
557 }
558 }
559
560 let mut p2p_port = match self.mode {
562 NodeMode::Dev(DevOptions { block_time }) => {
563 cmd.arg("--dev");
564 if let Some(block_time) = block_time {
565 cmd.arg("--dev.period").arg(block_time.to_string());
566 }
567 None
568 }
569 NodeMode::NonDev(PrivateNetOptions { p2p_port, discovery }) => {
570 let port = p2p_port.unwrap_or(0);
572 cmd.arg("--port").arg(port.to_string());
573
574 if !discovery {
576 cmd.arg("--nodiscover");
577 }
578 Some(port)
579 }
580 };
581
582 if let Some(chain_id) = self.chain_id {
583 cmd.arg("--networkid").arg(chain_id.to_string());
584 }
585
586 cmd.arg("--verbosity").arg("4");
588
589 if let Some(ipc) = &self.ipc_path {
590 cmd.arg("--ipcpath").arg(ipc);
591 }
592
593 cmd.args(self.args);
594
595 let mut child = cmd.spawn().map_err(NodeError::SpawnError)?;
596
597 let stderr = child.stderr.take().ok_or(NodeError::NoStderr)?;
598
599 let start = Instant::now();
600 let mut reader = BufReader::new(stderr);
601
602 let mut p2p_started = matches!(self.mode, NodeMode::Dev(_));
605 let mut ports_started = false;
606
607 loop {
608 if start + NODE_STARTUP_TIMEOUT <= Instant::now() {
609 let _ = child.kill();
610 return Err(NodeError::Timeout);
611 }
612
613 let mut line = String::with_capacity(120);
614 reader.read_line(&mut line).map_err(NodeError::ReadLineError)?;
615
616 if matches!(self.mode, NodeMode::NonDev(_)) && line.contains("Started P2P networking") {
617 p2p_started = true;
618 }
619
620 if !matches!(self.mode, NodeMode::Dev(_)) {
621 if line.contains("New local node record") {
623 if let Some(port) = extract_value("tcp=", &line) {
624 p2p_port = port.parse::<u16>().ok();
625 }
626 }
627 }
628
629 if line.contains("HTTP endpoint opened")
632 || (line.contains("HTTP server started") && !line.contains("auth=true"))
633 {
634 if let Some(addr) = extract_endpoint("endpoint=", &line) {
636 port = addr.port();
638 }
639
640 ports_started = true;
641 }
642
643 if line.contains("Fatal:") {
646 let _ = child.kill();
647 return Err(NodeError::Fatal(line));
648 }
649
650 if ports_started && p2p_started {
652 break;
653 }
654 }
655
656 if self.keep_err {
657 child.stderr = Some(reader.into_inner());
659 } else {
660 std::thread::spawn(move || {
664 let mut buf = String::new();
665 loop {
666 let _ = reader.read_line(&mut buf);
667 }
668 });
669 }
670
671 Ok(GethInstance {
672 pid: child,
673 port,
674 ipc: self.ipc_path,
675 data_dir: self.data_dir,
676 p2p_port,
677 auth_port: self.authrpc_port,
678 genesis: self.genesis,
679 clique_private_key: self.clique_private_key,
680 })
681 }
682}