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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use super::{unused_ports, CliqueConfig, Genesis};
use crate::{
types::{Bytes, H256},
utils::secret_key_to_address,
};
use k256::ecdsa::SigningKey;
use std::{
fs::{create_dir, File},
io::{BufRead, BufReader},
path::PathBuf,
process::{Child, ChildStderr, Command, Stdio},
time::{Duration, Instant},
};
use tempfile::tempdir;
const GETH_STARTUP_TIMEOUT: Duration = Duration::from_secs(10);
const GETH_DIAL_LOOP_TIMEOUT: Duration = Duration::from_secs(20);
const API: &str = "eth,net,web3,txpool,admin,personal,miner,debug";
const GETH: &str = "geth";
#[derive(Debug)]
pub enum GethInstanceError {
Timeout(String),
ReadLineError(std::io::Error),
NoStderr,
}
pub struct GethInstance {
pid: Child,
port: u16,
ipc: Option<PathBuf>,
data_dir: Option<PathBuf>,
p2p_port: Option<u16>,
genesis: Option<Genesis>,
clique_private_key: Option<SigningKey>,
}
impl GethInstance {
pub fn port(&self) -> u16 {
self.port
}
pub fn p2p_port(&self) -> Option<u16> {
self.p2p_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
}
pub fn data_dir(&self) -> &Option<PathBuf> {
&self.data_dir
}
pub fn genesis(&self) -> &Option<Genesis> {
&self.genesis
}
pub fn clique_private_key(&self) -> &Option<SigningKey> {
&self.clique_private_key
}
pub fn stderr(&mut self) -> Result<ChildStderr, GethInstanceError> {
self.pid.stderr.take().ok_or(GethInstanceError::NoStderr)
}
pub fn wait_to_add_peer(&mut self, id: H256) -> Result<(), GethInstanceError> {
let mut stderr = self.pid.stderr.as_mut().ok_or(GethInstanceError::NoStderr)?;
let mut err_reader = BufReader::new(&mut stderr);
let mut line = String::new();
let start = Instant::now();
while start.elapsed() < GETH_DIAL_LOOP_TIMEOUT {
line.clear();
err_reader.read_line(&mut line).map_err(GethInstanceError::ReadLineError)?;
let truncated_id = hex::encode(&id.0[..8]);
if line.contains("Adding p2p peer") && line.contains(&truncated_id) {
return Ok(())
}
}
Err(GethInstanceError::Timeout("Timed out waiting for geth to add a peer".into()))
}
}
impl Drop for GethInstance {
fn drop(&mut self) {
self.pid.kill().expect("could not kill geth");
}
}
#[derive(Debug, Clone)]
pub enum GethMode {
Dev(DevOptions),
NonDev(PrivateNetOptions),
}
impl Default for GethMode {
fn default() -> Self {
Self::Dev(Default::default())
}
}
#[derive(Debug, Clone, Default)]
pub struct DevOptions {
pub block_time: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct PrivateNetOptions {
pub p2p_port: Option<u16>,
pub discovery: bool,
}
impl Default for PrivateNetOptions {
fn default() -> Self {
Self { p2p_port: None, discovery: true }
}
}
#[derive(Clone, Default)]
pub struct Geth {
program: Option<PathBuf>,
port: Option<u16>,
authrpc_port: Option<u16>,
ipc_path: Option<PathBuf>,
data_dir: Option<PathBuf>,
chain_id: Option<u64>,
insecure_unlock: bool,
genesis: Option<Genesis>,
mode: GethMode,
clique_private_key: Option<SigningKey>,
}
impl Geth {
pub fn new() -> Self {
Self::default()
}
pub fn at(path: impl Into<PathBuf>) -> Self {
Self::new().path(path)
}
pub fn is_clique(&self) -> bool {
self.clique_private_key.is_some()
}
#[must_use]
pub fn path<T: Into<PathBuf>>(mut self, path: T) -> Self {
self.program = Some(path.into());
self
}
#[must_use]
pub fn set_clique_private_key<T: Into<SigningKey>>(mut self, private_key: T) -> Self {
self.clique_private_key = Some(private_key.into());
self
}
#[must_use]
pub fn port<T: Into<u16>>(mut self, port: T) -> Self {
self.port = Some(port.into());
self
}
#[must_use]
pub fn p2p_port(mut self, port: u16) -> Self {
match self.mode {
GethMode::Dev(_) => {
self.mode = GethMode::NonDev(PrivateNetOptions {
p2p_port: Some(port),
..Default::default()
})
}
GethMode::NonDev(ref mut opts) => opts.p2p_port = Some(port),
}
self
}
#[must_use]
pub fn block_time<T: Into<u64>>(mut self, block_time: T) -> Self {
self.mode = GethMode::Dev(DevOptions { block_time: Some(block_time.into()) });
self
}
#[must_use]
pub fn chain_id<T: Into<u64>>(mut self, chain_id: T) -> Self {
self.chain_id = Some(chain_id.into());
self
}
#[must_use]
pub fn insecure_unlock(mut self) -> Self {
self.insecure_unlock = true;
self
}
#[must_use]
pub fn disable_discovery(mut self) -> Self {
self.inner_disable_discovery();
self
}
fn inner_disable_discovery(&mut self) {
match self.mode {
GethMode::Dev(_) => {
self.mode =
GethMode::NonDev(PrivateNetOptions { discovery: false, ..Default::default() })
}
GethMode::NonDev(ref mut opts) => opts.discovery = false,
}
}
#[must_use]
pub fn ipc_path<T: Into<PathBuf>>(mut self, path: T) -> Self {
self.ipc_path = Some(path.into());
self
}
#[must_use]
pub fn data_dir<T: Into<PathBuf>>(mut self, path: T) -> Self {
self.data_dir = Some(path.into());
self
}
#[must_use]
pub fn genesis(mut self, genesis: Genesis) -> Self {
self.genesis = Some(genesis);
self
}
#[must_use]
pub fn authrpc_port(mut self, port: u16) -> Self {
self.authrpc_port = Some(port);
self
}
#[must_use]
#[track_caller]
pub fn spawn(mut self) -> GethInstance {
let bin_path = match self.program.as_ref() {
Some(bin) => bin.as_os_str(),
None => GETH.as_ref(),
}
.to_os_string();
let mut cmd = Command::new(&bin_path);
cmd.stderr(Stdio::piped());
let mut unused_ports = unused_ports::<3>().into_iter();
let mut unused_port = || unused_ports.next().unwrap();
let port = if let Some(port) = self.port { port } else { unused_port() };
let authrpc_port = if let Some(port) = self.authrpc_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);
let is_clique = self.is_clique();
if self.insecure_unlock || is_clique {
cmd.arg("--allow-insecure-unlock");
}
if is_clique {
self.inner_disable_discovery();
}
cmd.arg("--authrpc.port").arg(authrpc_port.to_string());
if let Some(ref mut genesis) = self.genesis {
if is_clique {
let clique_config = CliqueConfig { period: Some(0), epoch: Some(8) };
genesis.config.clique = Some(clique_config);
let clique_addr = secret_key_to_address(
self.clique_private_key.as_ref().expect("is_clique == true"),
);
let extra_data_bytes =
[&[0u8; 32][..], clique_addr.as_ref(), &[0u8; 65][..]].concat();
let extra_data = Bytes::from(extra_data_bytes);
genesis.extra_data = extra_data;
cmd.arg("--miner.etherbase").arg(format!("{clique_addr:?}"));
}
} else if is_clique {
let clique_addr =
secret_key_to_address(self.clique_private_key.as_ref().expect("is_clique == true"));
self.genesis = Some(Genesis::new(
self.chain_id.expect("chain id must be set in clique mode"),
clique_addr,
));
cmd.arg("--miner.etherbase").arg(format!("{clique_addr:?}"));
}
if let Some(ref genesis) = self.genesis {
let temp_genesis_dir_path =
tempdir().expect("should be able to create temp dir for genesis init").into_path();
let temp_genesis_path = temp_genesis_dir_path.join("genesis.json");
let mut file = File::create(&temp_genesis_path).expect("could not create genesis file");
serde_json::to_writer_pretty(&mut file, &genesis)
.expect("could not write genesis to file");
let mut init_cmd = Command::new(bin_path);
if let Some(ref data_dir) = self.data_dir {
init_cmd.arg("--datadir").arg(data_dir);
}
init_cmd.stderr(Stdio::null());
init_cmd.arg("init").arg(temp_genesis_path);
init_cmd
.spawn()
.expect("failed to spawn geth init")
.wait()
.expect("failed to wait for geth init to exit");
std::fs::remove_dir_all(temp_genesis_dir_path)
.expect("could not remove genesis temp dir");
}
if let Some(ref data_dir) = self.data_dir {
cmd.arg("--datadir").arg(data_dir);
if !data_dir.exists() {
create_dir(data_dir).expect("could not create data dir");
}
}
let p2p_port = match self.mode {
GethMode::Dev(DevOptions { block_time }) => {
cmd.arg("--dev");
if let Some(block_time) = block_time {
cmd.arg("--dev.period").arg(block_time.to_string());
}
None
}
GethMode::NonDev(PrivateNetOptions { p2p_port, discovery }) => {
let port = if let Some(port) = p2p_port { port } else { unused_port() };
cmd.arg("--port").arg(port.to_string());
if !discovery {
cmd.arg("--nodiscover");
}
Some(port)
}
};
if let Some(chain_id) = self.chain_id {
cmd.arg("--networkid").arg(chain_id.to_string());
}
cmd.arg("--verbosity").arg("4");
if let Some(ref ipc) = self.ipc_path {
cmd.arg("--ipcpath").arg(ipc);
}
let mut child = cmd.spawn().expect("couldnt start geth");
let stderr = child.stderr.expect("Unable to get stderr for geth child process");
let start = Instant::now();
let mut reader = BufReader::new(stderr);
let mut p2p_started = matches!(self.mode, GethMode::Dev(_));
let mut http_started = false;
loop {
if start + GETH_STARTUP_TIMEOUT <= Instant::now() {
panic!("Timed out waiting for geth to start. Is geth installed?")
}
let mut line = String::with_capacity(120);
reader.read_line(&mut line).expect("Failed to read line from geth process");
if matches!(self.mode, GethMode::NonDev(_)) && line.contains("Started P2P networking") {
p2p_started = true;
}
if line.contains("HTTP endpoint opened") ||
(line.contains("HTTP server started") && !line.contains("auth=true"))
{
http_started = true;
}
if p2p_started && http_started {
break
}
}
child.stderr = Some(reader.into_inner());
GethInstance {
pid: child,
port,
ipc: self.ipc_path,
data_dir: self.data_dir,
p2p_port,
genesis: self.genesis,
clique_private_key: self.clique_private_key,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn p2p_port() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let geth = Geth::new().disable_discovery().data_dir(temp_dir_path).spawn();
let p2p_port = geth.p2p_port();
assert!(p2p_port.is_some());
}
#[test]
fn explicit_p2p_port() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let geth = Geth::new().p2p_port(1234).data_dir(temp_dir_path).spawn();
let p2p_port = geth.p2p_port();
assert_eq!(p2p_port, Some(1234));
}
#[test]
fn dev_mode() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let geth = Geth::new().data_dir(temp_dir_path).spawn();
let p2p_port = geth.p2p_port();
assert!(p2p_port.is_none());
}
#[test]
fn clique_private_key_configured() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let private_key = SigningKey::random(&mut rand::thread_rng());
let geth = Geth::new()
.set_clique_private_key(private_key)
.chain_id(1337u64)
.data_dir(temp_dir_path)
.spawn();
let clique_private_key = geth.clique_private_key().clone();
assert!(clique_private_key.is_some());
}
#[test]
fn clique_genesis_configured() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let private_key = SigningKey::random(&mut rand::thread_rng());
let geth = Geth::new()
.set_clique_private_key(private_key)
.chain_id(1337u64)
.data_dir(temp_dir_path)
.spawn();
let genesis = geth.genesis().clone();
assert!(genesis.is_some());
}
#[test]
fn clique_p2p_configured() {
let temp_dir = tempfile::tempdir().unwrap();
let temp_dir_path = temp_dir.path().to_path_buf();
let private_key = SigningKey::random(&mut rand::thread_rng());
let geth = Geth::new()
.set_clique_private_key(private_key)
.chain_id(1337u64)
.data_dir(temp_dir_path)
.spawn();
let p2p_port = geth.p2p_port();
assert!(p2p_port.is_some());
}
}