From bd1eb29f61f451885d1f11b05f61023493584fcb Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Thu, 1 Dec 2022 12:05:40 +0100 Subject: [PATCH 1/2] Adds Network::to_core_arg This allows users to create `Network` instances from `bitcoind -chain` values --- bitcoin/src/network/constants.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/bitcoin/src/network/constants.rs b/bitcoin/src/network/constants.rs index 595f3db2..a620e5ea 100644 --- a/bitcoin/src/network/constants.rs +++ b/bitcoin/src/network/constants.rs @@ -119,6 +119,28 @@ impl Network { Network::Regtest => "regtest", } } + + /// Converts a `bitcoind -chain` argument name to its equivalent `Network`. + /// + /// ```bash + /// $ bitcoin-23.0/bin/bitcoind --help | grep -C 3 '\-chain=' + /// Chain selection options: + /// + /// -chain= + /// Use the chain (default: main). Allowed values: main, test, signet, regtest + /// ``` + pub fn from_core_arg(core_arg: &str) -> Result { + use Network::*; + + let network = match core_arg { + "main" => Bitcoin, + "test" => Testnet, + "signet" => Signet, + "regtest" => Regtest, + _ => return Err(ParseNetworkError(core_arg.to_owned())), + }; + Ok(network) + } } /// An error in parsing network string. From d7006ef80d1562da635f10cc435a7cb45f3e440a Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Thu, 8 Dec 2022 07:18:34 -0500 Subject: [PATCH 2/2] Adds roundtrip tests for Network::from_core_arg --- bitcoin/src/network/constants.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/bitcoin/src/network/constants.rs b/bitcoin/src/network/constants.rs index a620e5ea..d55ee6ad 100644 --- a/bitcoin/src/network/constants.rs +++ b/bitcoin/src/network/constants.rs @@ -599,4 +599,19 @@ mod tests { assert_eq!(&magic.to_string(), magic_str); } } + + #[test] + fn from_to_core_arg() { + let expected_pairs = [ + (Network::Bitcoin, "main"), + (Network::Testnet, "test"), + (Network::Regtest, "regtest"), + (Network::Signet, "signet"), + ]; + + for (net, core_arg) in &expected_pairs { + assert_eq!(Network::from_core_arg(core_arg), Ok(*net)); + assert_eq!(net.to_core_arg(), *core_arg); + } + } }