1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use super::unused_port;
use std::{
io::{BufRead, BufReader},
path::PathBuf,
process::{Child, Command},
time::{Duration, Instant},
};
const GETH_STARTUP_TIMEOUT_MILLIS: u64 = 10_000;
const API: &str = "eth,net,web3,txpool";
const GETH: &str = "geth";
pub struct GethInstance {
pid: Child,
port: u16,
ipc: Option<PathBuf>,
}
impl GethInstance {
pub fn port(&self) -> u16 {
self.port
}
pub fn endpoint(&self) -> String {
format!("http://localhost:{}", self.port)
}
pub fn ws_endpoint(&self) -> String {
format!("ws://localhost:{}", self.port)
}
pub fn ipc_path(&self) -> &Option<PathBuf> {
&self.ipc
}
}
impl Drop for GethInstance {
fn drop(&mut self) {
self.pid.kill().expect("could not kill geth");
}
}
#[derive(Clone, Default)]
pub struct Geth {
port: Option<u16>,
block_time: Option<u64>,
ipc_path: Option<PathBuf>,
}
impl Geth {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn port<T: Into<u16>>(mut self, port: T) -> Self {
self.port = Some(port.into());
self
}
#[must_use]
pub fn block_time<T: Into<u64>>(mut self, block_time: T) -> Self {
self.block_time = Some(block_time.into());
self
}
#[must_use]
pub fn ipc_path<T: Into<PathBuf>>(mut self, path: T) -> Self {
self.ipc_path = Some(path.into());
self
}
pub fn spawn(self) -> GethInstance {
let mut cmd = Command::new(GETH);
cmd.stderr(std::process::Stdio::piped());
let port = if let Some(port) = self.port { port } else { unused_port() };
cmd.arg("--http");
cmd.arg("--http.port").arg(port.to_string());
cmd.arg("--http.api").arg(API);
cmd.arg("--ws");
cmd.arg("--ws.port").arg(port.to_string());
cmd.arg("--ws.api").arg(API);
cmd.arg("--dev");
if let Some(block_time) = self.block_time {
cmd.arg("--dev.period").arg(block_time.to_string());
}
if let Some(ref ipc) = self.ipc_path {
cmd.arg("--ipcpath").arg(ipc);
}
let mut child = cmd.spawn().expect("couldnt start geth");
let stdout = child.stderr.expect("Unable to get stderr for geth child process");
let start = Instant::now();
let mut reader = BufReader::new(stdout);
loop {
if start + Duration::from_millis(GETH_STARTUP_TIMEOUT_MILLIS) <= Instant::now() {
panic!("Timed out waiting for geth to start. Is geth installed?")
}
let mut line = String::new();
reader.read_line(&mut line).expect("Failed to read line from geth process");
if line.contains("HTTP endpoint opened") || line.contains("HTTP server started") {
break
}
}
child.stderr = Some(reader.into_inner());
GethInstance { pid: child, port, ipc: self.ipc_path }
}
}