1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![cfg_attr(docsrs, cfg_attr(all(), doc = include_str!("../README.md")))]
3
4pub extern crate corepc_client as client;
5
6#[rustfmt::skip]
7mod client_versions;
8mod versions;
9
10use std::ffi::OsStr;
11use std::net::{Ipv4Addr, SocketAddrV4, TcpListener};
12use std::path::PathBuf;
13use std::process::{Child, Command, ExitStatus, Stdio};
14use std::time::Duration;
15use std::{env, fmt, fs, thread};
16
17use anyhow::Context;
18use corepc_client::client_sync::{self, Auth};
19use log::{debug, error, warn};
20use tempfile::TempDir;
21pub use {anyhow, serde_json, tempfile, which};
22
23#[rustfmt::skip] #[doc(inline)]
25pub use self::{
26 client_versions::{types, Client, AddressType},
27 versions::VERSION,
28};
29
30#[derive(Debug)]
31pub struct Node {
33 process: Child,
35 pub client: Client,
37 work_dir: DataDir,
39
40 pub params: ConnectParams,
42}
43
44#[derive(Debug)]
45pub enum DataDir {
48 Persistent(PathBuf),
50 Temporary(TempDir),
52}
53
54impl DataDir {
55 fn path(&self) -> PathBuf {
57 match self {
58 Self::Persistent(path) => path.to_owned(),
59 Self::Temporary(tmp_dir) => tmp_dir.path().to_path_buf(),
60 }
61 }
62}
63
64#[derive(Debug, Clone)]
65pub struct ConnectParams {
67 pub cookie_file: PathBuf,
69 pub rpc_socket: SocketAddrV4,
71 pub p2p_socket: Option<SocketAddrV4>,
73 pub zmq_pub_raw_block_socket: Option<SocketAddrV4>,
75 pub zmq_pub_raw_tx_socket: Option<SocketAddrV4>,
77}
78
79pub struct CookieValues {
80 pub user: String,
81 pub password: String,
82}
83
84impl ConnectParams {
85 fn parse_cookie(content: String) -> Option<CookieValues> {
87 let values: Vec<_> = content.splitn(2, ':').collect();
88 let user = values.first()?.to_string();
89 let password = values.get(1)?.to_string();
90 Some(CookieValues { user, password })
91 }
92
93 pub fn get_cookie_values(&self) -> Result<Option<CookieValues>, std::io::Error> {
95 let cookie = std::fs::read_to_string(&self.cookie_file)?;
96 Ok(self::ConnectParams::parse_cookie(cookie))
97 }
98}
99
100#[derive(Debug, PartialEq, Eq, Clone)]
102pub enum P2P {
103 No,
105 Yes,
107 Connect(SocketAddrV4, bool),
111}
112
113pub enum Error {
115 Io(std::io::Error),
117 Rpc(client_sync::Error),
119 NoFeature,
121 NoEnvVar,
123 NoBitcoindExecutableFound,
126 EarlyExit(ExitStatus),
128 BothDirsSpecified,
130 RpcUserAndPasswordUsed,
133 SkipDownload,
135 NoBitcoindInstance,
137}
138
139impl fmt::Debug for Error {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 use Error::*;
142
143 match self {
144 Io(_) => write!(f, "io::Error"), Rpc(_) => write!(f, "bitcoin_rpc::Error"),
146 NoFeature => write!(f, "Called a method requiring a feature to be set, but it's not"),
147 NoEnvVar => write!(f, "Called a method requiring env var `BITCOIND_EXE` to be set, but it's not"),
148 NoBitcoindExecutableFound => write!(f, "`bitcoind` executable is required, provide it with one of the following: set env var `BITCOIND_EXE` or use a feature like \"22_1\" or have `bitcoind` executable in the `PATH`"),
149 EarlyExit(e) => write!(f, "The bitcoind process terminated early with exit code {}", e),
150 BothDirsSpecified => write!(f, "tempdir and staticdir cannot be enabled at same time in configuration options"),
151 RpcUserAndPasswordUsed => write!(f, "`-rpcuser` and `-rpcpassword` cannot be used, it will be deprecated soon and it's recommended to use `-rpcauth` instead which works alongside with the default cookie authentication"),
152 SkipDownload => write!(f, "expecting an auto-downloaded executable but `BITCOIND_SKIP_DOWNLOAD` env var is set"),
153 NoBitcoindInstance => write!(f, "it appears that bitcoind is not reachable"),
154 }
155 }
156}
157
158impl std::fmt::Display for Error {
159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) }
160}
161
162impl std::error::Error for Error {
163 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
164 use Error::*;
165
166 match *self {
167 Error::Io(ref e) => Some(e),
168 Error::Rpc(ref e) => Some(e),
169 NoFeature
170 | NoEnvVar
171 | NoBitcoindExecutableFound
172 | EarlyExit(_)
173 | BothDirsSpecified
174 | RpcUserAndPasswordUsed
175 | SkipDownload
176 | NoBitcoindInstance => None,
177 }
178 }
179}
180
181const LOCAL_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
182
183const INVALID_ARGS: [&str; 2] = ["-rpcuser", "-rpcpassword"];
184
185#[non_exhaustive]
206#[derive(Debug, PartialEq, Eq, Clone)]
207pub struct Conf<'a> {
208 pub args: Vec<&'a str>,
212
213 pub view_stdout: bool,
215
216 pub p2p: P2P,
218
219 pub network: &'a str,
222
223 pub tmpdir: Option<PathBuf>,
237
238 pub staticdir: Option<PathBuf>,
240
241 pub attempts: u8,
247
248 pub enable_zmq: bool,
250
251 pub wallet: Option<String>,
253}
254
255impl Default for Conf<'_> {
256 fn default() -> Self {
257 Conf {
258 args: vec!["-regtest", "-fallbackfee=0.0001"],
259 view_stdout: false,
260 p2p: P2P::No,
261 network: "regtest",
262 tmpdir: None,
263 staticdir: None,
264 attempts: 3,
265 enable_zmq: false,
266 wallet: Some("default".to_string()),
267 }
268 }
269}
270
271impl Node {
272 pub fn new<S: AsRef<OsStr>>(exe: S) -> anyhow::Result<Node> {
276 Node::with_conf(exe, &Conf::default())
277 }
278
279 pub fn with_conf<S: AsRef<OsStr>>(exe: S, conf: &Conf) -> anyhow::Result<Node> {
281 let tmpdir =
282 conf.tmpdir.clone().or_else(|| env::var("TEMPDIR_ROOT").map(PathBuf::from).ok());
283 let work_dir = match (&tmpdir, &conf.staticdir) {
284 (Some(_), Some(_)) => return Err(Error::BothDirsSpecified.into()),
285 (Some(tmpdir), None) => DataDir::Temporary(TempDir::new_in(tmpdir)?),
286 (None, Some(workdir)) => {
287 fs::create_dir_all(workdir)?;
288 DataDir::Persistent(workdir.to_owned())
289 }
290 (None, None) => DataDir::Temporary(TempDir::new()?),
291 };
292
293 let work_dir_path = work_dir.path();
294 if !work_dir_path.exists() {
295 panic!("work dir does not exist");
296 }
297 debug!("work_dir: {:?}", work_dir_path);
298
299 let cookie_file = work_dir_path.join(conf.network).join(".cookie");
300 let rpc_port = get_available_port()?;
301 let rpc_socket = SocketAddrV4::new(LOCAL_IP, rpc_port);
302 let rpc_url = format!("http://{}", rpc_socket);
303 debug!("rpc_url: {}", rpc_url);
304
305 let (p2p_args, p2p_socket) = match conf.p2p {
306 P2P::No => (vec!["-listen=0".to_string()], None),
307 P2P::Yes => {
308 let p2p_port = get_available_port()?;
309 let p2p_socket = SocketAddrV4::new(LOCAL_IP, p2p_port);
310 let bind_arg = format!("-bind={}", p2p_socket);
311 let args = vec![bind_arg];
312 (args, Some(p2p_socket))
313 }
314 P2P::Connect(other_node_url, listen) => {
315 let p2p_port = get_available_port()?;
316 let p2p_socket = SocketAddrV4::new(LOCAL_IP, p2p_port);
317 let bind_arg = format!("-bind={}", p2p_socket);
318 let connect = format!("-connect={}", other_node_url);
319 let mut args = vec![bind_arg, connect];
320 if listen {
321 args.push("-listen=1".to_string())
322 }
323 (args, Some(p2p_socket))
324 }
325 };
326
327 let (zmq_args, zmq_pub_raw_tx_socket, zmq_pub_raw_block_socket) = match conf.enable_zmq {
328 true => {
329 let zmq_pub_raw_tx_port = get_available_port()?;
330 let zmq_pub_raw_tx_socket = SocketAddrV4::new(LOCAL_IP, zmq_pub_raw_tx_port);
331 let zmq_pub_raw_block_port = get_available_port()?;
332 let zmq_pub_raw_block_socket = SocketAddrV4::new(LOCAL_IP, zmq_pub_raw_block_port);
333 let zmqpubrawblock_arg =
334 format!("-zmqpubrawblock=tcp://0.0.0.0:{}", zmq_pub_raw_block_port);
335 let zmqpubrawtx_arg = format!("-zmqpubrawtx=tcp://0.0.0.0:{}", zmq_pub_raw_tx_port);
336 (
337 vec![zmqpubrawtx_arg, zmqpubrawblock_arg],
338 Some(zmq_pub_raw_tx_socket),
339 Some(zmq_pub_raw_block_socket),
340 )
341 }
342 false => (vec![], None, None),
343 };
344
345 let stdout = if conf.view_stdout { Stdio::inherit() } else { Stdio::null() };
346
347 let datadir_arg = format!("-datadir={}", work_dir_path.display());
348 let rpc_arg = format!("-rpcport={}", rpc_port);
349 let default_args = [&datadir_arg, &rpc_arg];
350 let conf_args = validate_args(conf.args.clone())?;
351
352 debug!(
353 "launching {:?} with args: {:?} {:?} AND custom args: {:?}",
354 exe.as_ref(),
355 default_args,
356 p2p_args,
357 conf_args
358 );
359
360 let mut process = Command::new(exe.as_ref())
361 .args(default_args)
362 .args(&p2p_args)
363 .args(&conf_args)
364 .args(&zmq_args)
365 .stdout(stdout)
366 .spawn()
367 .with_context(|| format!("Error while executing {:?}", exe.as_ref()))?;
368
369 debug!("cookie file: {}", cookie_file.display());
370
371 if let Some(status) = process.try_wait()? {
372 if conf.attempts > 0 {
373 warn!("early exit with: {:?}. Trying to launch again ({} attempts remaining), maybe some other process used our available port", status, conf.attempts);
374 let mut conf = conf.clone();
375 conf.attempts -= 1;
376 return Self::with_conf(exe, &conf)
377 .with_context(|| format!("Remaining attempts {}", conf.attempts));
378 } else {
379 error!("early exit with: {:?}", status);
380 return Err(Error::EarlyExit(status).into());
381 }
382 }
383 thread::sleep(Duration::from_millis(1000));
384 assert!(process.stderr.is_none());
385
386 let mut tries = 0;
387 let auth = Auth::CookieFile(cookie_file.clone());
388
389 let client = loop {
390 tries += 1;
391
392 if tries > 10 {
393 error!("failed to get a response from bitcoind");
394 return Err(Error::NoBitcoindInstance.into());
395 }
396
397 let client_base = match Client::new_with_auth(&rpc_url, auth.clone()) {
398 Ok(client) => client,
399 Err(e) => {
400 error!("failed to create client: {}. Retrying!", e);
401 thread::sleep(Duration::from_millis(1000));
402 continue;
403 }
404 };
405
406 let client_result: Result<serde_json::Value, _> =
408 client_base.call("getblockchaininfo", &[]);
409
410 match client_result {
411 Ok(_) => {
412 let url = match &conf.wallet {
413 Some(wallet) => {
414 debug!("trying to create/load wallet: {}", wallet);
415 match client_base.create_wallet(wallet) {
417 Ok(json) => {
418 debug!("created wallet: {}", json.name());
419 }
420 Err(e) => {
421 debug!(
422 "initial create_wallet failed, try load instead: {:?}",
423 e
424 );
425 let wallet = client_base.load_wallet(wallet)?.name();
426 debug!("loaded wallet: {}", wallet);
427 }
428 }
429 format!("{}/wallet/{}", rpc_url, wallet)
430 }
431 None => rpc_url,
432 };
433 debug!("creating client with url: {}", url);
434 break Client::new_with_auth(&url, auth)?;
435 }
436 Err(e) => {
437 error!("failed to get a response from bitcoind: {}. Retrying!", e);
438 thread::sleep(Duration::from_millis(1000));
439 continue;
440 }
441 }
442 };
443
444 Ok(Node {
445 process,
446 client,
447 work_dir,
448 params: ConnectParams {
449 cookie_file,
450 rpc_socket,
451 p2p_socket,
452 zmq_pub_raw_block_socket,
453 zmq_pub_raw_tx_socket,
454 },
455 })
456 }
457
458 pub fn rpc_url(&self) -> String { format!("http://{}", self.params.rpc_socket) }
460
461 #[cfg(any(feature = "0_19_1", not(feature = "download")))]
462 pub fn rpc_url_with_wallet<T: AsRef<str>>(&self, wallet_name: T) -> String {
465 format!("http://{}/wallet/{}", self.params.rpc_socket, wallet_name.as_ref())
466 }
467
468 pub fn workdir(&self) -> PathBuf { self.work_dir.path() }
470
471 pub fn p2p_connect(&self, listen: bool) -> Option<P2P> {
473 self.params.p2p_socket.map(|s| P2P::Connect(s, listen))
474 }
475
476 pub fn stop(&mut self) -> anyhow::Result<ExitStatus> {
478 self.client.stop()?;
479 Ok(self.process.wait()?)
480 }
481
482 #[cfg(any(feature = "0_19_1", not(feature = "download")))]
483 pub fn create_wallet<T: AsRef<str>>(&self, wallet: T) -> anyhow::Result<Client> {
486 let _ = self.client.create_wallet(wallet.as_ref())?;
487 Ok(Client::new_with_auth(
488 &self.rpc_url_with_wallet(wallet),
489 Auth::CookieFile(self.params.cookie_file.clone()),
490 )?)
491 }
492}
493
494#[cfg(feature = "download")]
495impl Node {
496 pub fn from_downloaded() -> anyhow::Result<Node> { Node::new(downloaded_exe_path()?) }
498
499 pub fn from_downloaded_with_conf(conf: &Conf) -> anyhow::Result<Node> {
501 Node::with_conf(downloaded_exe_path()?, conf)
502 }
503}
504
505impl Drop for Node {
506 fn drop(&mut self) {
507 if let DataDir::Persistent(_) = self.work_dir {
508 let _ = self.stop();
509 }
510 let _ = self.process.kill();
511 }
512}
513
514pub fn get_available_port() -> anyhow::Result<u16> {
518 let t = TcpListener::bind(("127.0.0.1", 0))?; Ok(t.local_addr().map(|s| s.port())?)
521}
522
523impl From<std::io::Error> for Error {
524 fn from(e: std::io::Error) -> Self { Error::Io(e) }
525}
526
527impl From<client_sync::Error> for Error {
528 fn from(e: client_sync::Error) -> Self { Error::Rpc(e) }
529}
530
531#[cfg(not(feature = "download"))]
533pub fn downloaded_exe_path() -> anyhow::Result<String> { Err(Error::NoFeature.into()) }
534
535#[cfg(feature = "download")]
537pub fn downloaded_exe_path() -> anyhow::Result<String> {
538 if std::env::var_os("BITCOIND_SKIP_DOWNLOAD").is_some() {
539 return Err(Error::SkipDownload.into());
540 }
541
542 let mut path: PathBuf = env!("OUT_DIR").into();
543 path.push("bitcoin");
544 path.push(format!("bitcoin-{}", VERSION));
545 path.push("bin");
546
547 if cfg!(target_os = "windows") {
548 path.push("bitcoind.exe");
549 } else {
550 path.push("bitcoind");
551 }
552
553 let path = format!("{}", path.display());
554 debug!("path: {}", path);
555 Ok(path)
556}
557
558pub fn exe_path() -> anyhow::Result<String> {
565 if let Ok(path) = std::env::var("BITCOIND_EXE") {
566 return Ok(path);
567 }
568 if let Ok(path) = downloaded_exe_path() {
569 return Ok(path);
570 }
571 which::which("bitcoind")
572 .map_err(|_| Error::NoBitcoindExecutableFound.into())
573 .map(|p| p.display().to_string())
574}
575
576pub fn validate_args(args: Vec<&str>) -> anyhow::Result<Vec<&str>> {
578 args.iter().try_for_each(|arg| {
579 if INVALID_ARGS.iter().any(|x| arg.starts_with(x)) {
581 return Err(Error::RpcUserAndPasswordUsed);
582 }
583 Ok(())
584 })?;
585
586 Ok(args)
587}
588
589#[cfg(test)]
590mod test {
591 use std::net::SocketAddrV4;
592
593 use tempfile::TempDir;
594
595 use super::*;
596 use crate::{exe_path, get_available_port, Conf, Node, LOCAL_IP, P2P};
597
598 #[test]
599 fn test_local_ip() {
600 assert_eq!("127.0.0.1", format!("{}", LOCAL_IP));
601 let port = get_available_port().unwrap();
602 let socket = SocketAddrV4::new(LOCAL_IP, port);
603 assert_eq!(format!("127.0.0.1:{}", port), format!("{}", socket));
604 }
605
606 #[test]
607 fn test_node_get_blockchain_info() {
608 let exe = init();
609 let node = Node::new(exe).unwrap();
610 let info = node.client.get_blockchain_info().unwrap();
611 assert_eq!(0, info.blocks);
612 }
613
614 #[test]
615 fn test_node() {
616 let exe = init();
617 let node = Node::new(exe).unwrap();
618 let info = node.client.get_blockchain_info().unwrap();
619
620 assert_eq!(0, info.blocks);
621 let address = node.client.new_address().unwrap();
622 let _ = node.client.generate_to_address(1, &address).unwrap();
623 let info = node.client.get_blockchain_info().unwrap();
624 assert_eq!(1, info.blocks);
625 }
626
627 #[test]
628 #[cfg(feature = "0_21_2")]
629 fn test_getindexinfo() {
630 let exe = init();
631 let mut conf = Conf::default();
632 conf.args.push("-txindex");
633 let node = Node::with_conf(&exe, &conf).unwrap();
634 assert!(
635 node.client.server_version().unwrap() >= 210_000,
636 "getindexinfo requires bitcoin >0.21"
637 );
638 let info: std::collections::HashMap<String, serde_json::Value> =
639 node.client.call("getindexinfo", &[]).unwrap();
640 assert!(info.contains_key("txindex"));
641 assert!(node.client.server_version().unwrap() >= 210_000);
642 }
643
644 #[test]
645 fn test_p2p() {
646 let exe = init();
647
648 let conf = Conf::<'_> { p2p: P2P::Yes, ..Default::default() };
649 let node = Node::with_conf(&exe, &conf).unwrap();
650 assert_eq!(peers_connected(&node.client), 0);
651
652 let other_conf = Conf::<'_> { p2p: node.p2p_connect(false).unwrap(), ..Default::default() };
653 let other_node = Node::with_conf(&exe, &other_conf).unwrap();
654
655 assert_eq!(peers_connected(&node.client), 1);
656 assert_eq!(peers_connected(&other_node.client), 1);
657 }
658
659 #[cfg(not(target_os = "windows"))] #[test]
661 fn test_data_persistence() {
662 let mut conf = Conf::default();
664 let datadir = TempDir::new().unwrap();
665 conf.staticdir = Some(datadir.path().to_path_buf());
666
667 let node = Node::with_conf(exe_path().unwrap(), &conf).unwrap();
671 let core_addrs = node.client.new_address().unwrap();
672 node.client.generate_to_address(101, &core_addrs).unwrap();
673 let wallet_balance_1 = node.client.get_balance().unwrap();
674 let best_block_1 = node.client.get_best_block_hash().unwrap();
675
676 drop(node);
677
678 let node = Node::with_conf(exe_path().unwrap(), &conf).unwrap();
680
681 let wallet_balance_2 = node.client.get_balance().unwrap();
682 let best_block_2 = node.client.get_best_block_hash().unwrap();
683
684 assert_eq!(best_block_1, best_block_2);
686
687 assert_eq!(wallet_balance_1, wallet_balance_2);
689 }
690
691 #[test]
692 fn test_multi_p2p() {
693 let exe = init();
694
695 let conf_node1 = Conf::<'_> { p2p: P2P::Yes, ..Default::default() };
696 let node1 = Node::with_conf(&exe, &conf_node1).unwrap();
697 assert_eq!(peers_connected(&node1.client), 0);
698
699 let conf_node2 = Conf::<'_> { p2p: node1.p2p_connect(true).unwrap(), ..Default::default() };
701 let node2 = Node::with_conf(&exe, &conf_node2).unwrap();
702
703 let conf_node3 =
705 Conf::<'_> { p2p: node2.p2p_connect(false).unwrap(), ..Default::default() };
706 let node3 = Node::with_conf(exe_path().unwrap(), &conf_node3).unwrap();
707
708 let node1_peers = peers_connected(&node1.client);
710 let node2_peers = peers_connected(&node2.client);
711 let node3_peers = peers_connected(&node3.client);
712
713 assert!(node1_peers >= 1);
715 assert!(node2_peers >= 1);
716 assert_eq!(node3_peers, 1, "listen false but more than 1 peer");
717 }
718
719 #[cfg(feature = "0_19_1")]
720 #[test]
721 fn test_multi_wallet() {
722 use corepc_client::bitcoin::Amount;
723
724 let exe = init();
725 let node = Node::new(exe).unwrap();
726 let alice = node.create_wallet("alice").unwrap();
727 let alice_address = alice.new_address().unwrap();
728 let bob = node.create_wallet("bob").unwrap();
729 let bob_address = bob.new_address().unwrap();
730 node.client.generate_to_address(1, &alice_address).unwrap();
731 node.client.generate_to_address(101, &bob_address).unwrap();
732
733 let balances = alice.get_balances().unwrap();
734 let alice_balances: types::GetBalances = balances;
735
736 let balances = bob.get_balances().unwrap();
737 let bob_balances: types::GetBalances = balances;
738
739 assert_eq!(
740 Amount::from_btc(50.0).unwrap(),
741 Amount::from_btc(alice_balances.mine.trusted).unwrap()
742 );
743 assert_eq!(
744 Amount::from_btc(50.0).unwrap(),
745 Amount::from_btc(bob_balances.mine.trusted).unwrap()
746 );
747 assert_eq!(
748 Amount::from_btc(5000.0).unwrap(),
749 Amount::from_btc(bob_balances.mine.immature).unwrap()
750 );
751 let _txid = alice.send_to_address(&bob_address, Amount::from_btc(1.0).unwrap()).unwrap();
752
753 let balances = alice.get_balances().unwrap();
754 let alice_balances: types::GetBalances = balances;
755
756 assert!(
757 Amount::from_btc(alice_balances.mine.trusted).unwrap()
758 < Amount::from_btc(49.0).unwrap()
759 && Amount::from_btc(alice_balances.mine.trusted).unwrap()
760 > Amount::from_btc(48.9).unwrap()
761 );
762
763 for _ in 0..30 {
765 let balances = bob.get_balances().unwrap();
766 let bob_balances: types::GetBalances = balances;
767
768 if Amount::from_btc(bob_balances.mine.untrusted_pending).unwrap().to_sat() > 0 {
769 break;
770 }
771 std::thread::sleep(std::time::Duration::from_millis(100));
772 }
773 let balances = bob.get_balances().unwrap();
774 let bob_balances: types::GetBalances = balances;
775
776 assert_eq!(
777 Amount::from_btc(1.0).unwrap(),
778 Amount::from_btc(bob_balances.mine.untrusted_pending).unwrap()
779 );
780 assert!(node.create_wallet("bob").is_err(), "wallet already exist");
781 }
782
783 #[test]
784 fn test_node_rpcuser_and_rpcpassword() {
785 let exe = init();
786
787 let mut conf = Conf::default();
788 conf.args.push("-rpcuser=bitcoind");
789 conf.args.push("-rpcpassword=bitcoind");
790
791 let node = Node::with_conf(exe, &conf);
792
793 assert!(node.is_err());
794 }
795
796 #[test]
797 fn test_node_rpcauth() {
798 let exe = init();
799
800 let mut conf = Conf::default();
801 conf.args.push("-rpcauth=bitcoind:cccd5d7fd36e55c1b8576b8077dc1b83$60b5676a09f8518dcb4574838fb86f37700cd690d99bd2fdc2ea2bf2ab80ead6");
804
805 let node = Node::with_conf(exe, &conf).unwrap();
806
807 let auth = Auth::UserPass("bitcoind".to_string(), "bitcoind".to_string());
808 let client = Client::new_with_auth(
809 format!("{}/wallet/default", node.rpc_url().as_str()).as_str(),
810 auth,
811 )
812 .unwrap();
813 let info = client.get_blockchain_info().unwrap();
814 assert_eq!(0, info.blocks);
815
816 let address = client.new_address().unwrap();
817 let _ = client.generate_to_address(1, &address).unwrap();
818 let info = node.client.get_blockchain_info().unwrap();
819 assert_eq!(1, info.blocks);
820 }
821
822 #[test]
823 fn test_get_cookie_user_and_pass() {
824 let exe = init();
825 let node = Node::new(exe).unwrap();
826
827 let user: &str = "bitcoind_user";
828 let password: &str = "bitcoind_password";
829
830 std::fs::write(&node.params.cookie_file, format!("{}:{}", user, password)).unwrap();
831
832 let result_values = node.params.get_cookie_values().unwrap().unwrap();
833
834 assert_eq!(user, result_values.user);
835 assert_eq!(password, result_values.password);
836 }
837
838 #[test]
839 fn zmq_interface_enabled() {
840 let conf = Conf::<'_> { enable_zmq: true, ..Default::default() };
841 let node = Node::with_conf(exe_path().unwrap(), &conf).unwrap();
842
843 assert!(node.params.zmq_pub_raw_tx_socket.is_some());
844 assert!(node.params.zmq_pub_raw_block_socket.is_some());
845 }
846
847 #[test]
848 fn zmq_interface_disabled() {
849 let exe = init();
850 let node = Node::new(exe).unwrap();
851
852 assert!(node.params.zmq_pub_raw_tx_socket.is_none());
853 assert!(node.params.zmq_pub_raw_block_socket.is_none());
854 }
855
856 fn peers_connected(client: &Client) -> usize {
857 let result: Vec<serde_json::Value> = client.call("getpeerinfo", &[]).unwrap();
860 result.len()
861 }
862
863 fn init() -> String {
864 let _ = env_logger::try_init();
865 exe_path().unwrap()
866 }
867}