Merge rust-bitcoin/rust-bitcoin#1428: Adds Network::from_core_arg and links it to Network::from_str

d7006ef80d Adds roundtrip tests for Network::from_core_arg (Sergi Delgado Segura)
bd1eb29f61 Adds Network::to_core_arg (Sergi Delgado Segura)

Pull request description:

  Comming from https://github.com/rust-bitcoin/rust-bitcoincore-rpc/pull/247

  `Network::from_str` only considers `rust-bitcoin` string as possible inputs to create a `Network` instance. This PR adds a new method to `Network`, `from_core_arg`, which is complementary to the existing `Network::to_core_arg`. This method allows the conversion between `bitcoind -network` string and `Network` variants.

  This also links `Network::from_str` to `Network::from_core_arg` so the default case on the former calls the latter, and an error is only returned if none of the cases match.

ACKs for top commit:
  Kixunil:
    ACK d7006ef80d
  apoelstra:
    ACK d7006ef80d

Tree-SHA512: 97a66f858a7d4a3642bdef9016457833cfc1181e276f7ead7c6b87f6fcdcb7c5d1cfdb4b621225b806bc5949c3c5cc6a32b7df934157542d7c79aa00a9e20f41
This commit is contained in:
Andrew Poelstra 2022-12-08 14:41:28 +00:00
commit c93e83e94b
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 37 additions and 0 deletions

View File

@ -119,6 +119,28 @@ impl Network {
Network::Regtest => "regtest", 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>'
/// Chain selection options:
///
/// -chain=<chain>
/// Use the chain <chain> (default: main). Allowed values: main, test, signet, regtest
/// ```
pub fn from_core_arg(core_arg: &str) -> Result<Self, ParseNetworkError> {
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. /// An error in parsing network string.
@ -577,4 +599,19 @@ mod tests {
assert_eq!(&magic.to_string(), magic_str); 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);
}
}
} }