Skip to content

Commit 4e71a37

Browse files
committed
Introduce anyhow
1 parent 658d20c commit 4e71a37

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ bitcoincore-rpc = "0.16.0"
1414
tempfile = "3.1"
1515
log = "0.4"
1616
which = "4.2.5"
17+
anyhow = "1.0.66"
1718

1819
[dev-dependencies]
1920
env_logger = "0.9"

src/lib.rs

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub extern crate bitcoincore_rpc;
2828
pub extern crate tempfile;
2929
pub extern crate which;
3030

31+
#[derive(Debug)]
3132
/// Struct representing the bitcoind process with related information
3233
pub struct BitcoinD {
3334
/// Process child handle, used to terminate the process when this struct is dropped
@@ -41,6 +42,7 @@ pub struct BitcoinD {
4142
pub params: ConnectParams,
4243
}
4344

45+
#[derive(Debug)]
4446
/// The DataDir struct defining the kind of data directory the node
4547
/// will contain. Data directory can be either persistent, or temporary.
4648
pub enum DataDir {
@@ -225,18 +227,18 @@ impl BitcoinD {
225227
/// Launch the bitcoind process from the given `exe` executable with default args.
226228
///
227229
/// Waits for the node to be ready to accept connections before returning
228-
pub fn new<S: AsRef<OsStr>>(exe: S) -> Result<BitcoinD, Error> {
230+
pub fn new<S: AsRef<OsStr>>(exe: S) -> anyhow::Result<BitcoinD> {
229231
BitcoinD::with_conf(exe, &Conf::default())
230232
}
231233

232234
/// Launch the bitcoind process from the given `exe` executable with given [Conf] param
233-
pub fn with_conf<S: AsRef<OsStr>>(exe: S, conf: &Conf) -> Result<BitcoinD, Error> {
235+
pub fn with_conf<S: AsRef<OsStr>>(exe: S, conf: &Conf) -> anyhow::Result<BitcoinD> {
234236
let tmpdir = conf
235237
.tmpdir
236238
.clone()
237239
.or_else(|| env::var("TEMPDIR_ROOT").map(PathBuf::from).ok());
238240
let work_dir = match (&tmpdir, &conf.staticdir) {
239-
(Some(_), Some(_)) => return Err(Error::BothDirsSpecified),
241+
(Some(_), Some(_)) => return Err(Error::BothDirsSpecified.into()),
240242
(Some(tmpdir), None) => DataDir::Temporary(TempDir::new_in(tmpdir)?),
241243
(None, Some(workdir)) => {
242244
fs::create_dir_all(workdir)?;
@@ -309,7 +311,7 @@ impl BitcoinD {
309311
return Self::with_conf(exe, &conf);
310312
} else {
311313
error!("early exit with: {:?}", status);
312-
return Err(Error::EarlyExit(status));
314+
return Err(Error::EarlyExit(status).into());
313315
}
314316
}
315317
thread::sleep(Duration::from_millis(100));
@@ -381,15 +383,15 @@ impl BitcoinD {
381383
}
382384

383385
/// Stop the node, waiting correct process termination
384-
pub fn stop(&mut self) -> Result<ExitStatus, Error> {
386+
pub fn stop(&mut self) -> anyhow::Result<ExitStatus> {
385387
self.client.stop()?;
386388
Ok(self.process.wait()?)
387389
}
388390

389391
#[cfg(not(any(feature = "0_17_1", feature = "0_18_0", feature = "0_18_1")))]
390392
/// Create a new wallet in the running node, and return an RPC client connected to the just
391393
/// created wallet
392-
pub fn create_wallet<T: AsRef<str>>(&self, wallet: T) -> Result<Client, Error> {
394+
pub fn create_wallet<T: AsRef<str>>(&self, wallet: T) -> anyhow::Result<Client> {
393395
let _ = self
394396
.client
395397
.create_wallet(wallet.as_ref(), None, None, None, None)?;
@@ -412,7 +414,7 @@ impl Drop for BitcoinD {
412414
/// Returns a non-used local port if available.
413415
///
414416
/// Note there is a race condition during the time the method check availability and the caller
415-
pub fn get_available_port() -> Result<u16, Error> {
417+
pub fn get_available_port() -> anyhow::Result<u16> {
416418
// using 0 as port let the system assign a port available
417419
let t = TcpListener::bind(("127.0.0.1", 0))?; // 0 means the OS choose a free port
418420
Ok(t.local_addr().map(|s| s.port())?)
@@ -431,7 +433,7 @@ impl From<bitcoincore_rpc::Error> for Error {
431433
}
432434

433435
/// Provide the bitcoind executable path if a version feature has been specified
434-
pub fn downloaded_exe_path() -> Result<String, Error> {
436+
pub fn downloaded_exe_path() -> anyhow::Result<String> {
435437
if versions::HAS_FEATURE {
436438
let mut path: PathBuf = env!("OUT_DIR").into();
437439
path.push("bitcoin");
@@ -446,25 +448,25 @@ pub fn downloaded_exe_path() -> Result<String, Error> {
446448

447449
Ok(format!("{}", path.display()))
448450
} else {
449-
Err(Error::NoFeature)
451+
Err(Error::NoFeature.into())
450452
}
451453
}
452454

453455
/// Returns the daemon executable path if it's provided as a feature or as `BITCOIND_EXE` env var.
454456
/// Returns error if none or both are set
455-
pub fn exe_path() -> Result<String, Error> {
457+
pub fn exe_path() -> anyhow::Result<String> {
456458
match (downloaded_exe_path(), std::env::var("BITCOIND_EXE")) {
457-
(Ok(_), Ok(_)) => Err(Error::BothFeatureAndEnvVar),
459+
(Ok(_), Ok(_)) => Err(Error::BothFeatureAndEnvVar.into()),
458460
(Ok(path), Err(_)) => Ok(path),
459461
(Err(_), Ok(path)) => Ok(path),
460462
(Err(_), Err(_)) => which::which("bitcoind")
461-
.map_err(|_| Error::NoBitcoindExecutableFound)
463+
.map_err(|_| Error::NoBitcoindExecutableFound.into())
462464
.map(|p| p.display().to_string()),
463465
}
464466
}
465467

466468
/// Validate the specified arg if there is any unavailable or deprecated one
467-
pub fn validate_args(args: Vec<&str>) -> Result<Vec<&str>, Error> {
469+
pub fn validate_args(args: Vec<&str>) -> anyhow::Result<Vec<&str>> {
468470
args.iter().try_for_each(|arg| {
469471
// other kind of invalid arguments can be added into the list if needed
470472
if INVALID_ARGS.iter().any(|x| arg.starts_with(x)) {
@@ -676,7 +678,10 @@ mod test {
676678
let bitcoind = BitcoinD::with_conf(exe, &conf);
677679

678680
assert!(bitcoind.is_err());
679-
assert!(matches!(bitcoind, Err(Error::RpcUserAndPasswordUsed)));
681+
assert!(matches!(
682+
bitcoind.unwrap_err().downcast_ref().unwrap(),
683+
Error::RpcUserAndPasswordUsed
684+
));
680685
}
681686

682687
#[test]

0 commit comments

Comments
 (0)