Change from_str(s) to parse::<T>() in Examples

`s.parse` is more idiomatic and produces more helpful error messages.

This has been changed in examples.
This commit is contained in:
Jamil Lambert, PhD 2024-08-28 12:00:13 +01:00
parent c835bb9eab
commit 64e668f99e
No known key found for this signature in database
GPG Key ID: 54DC29234AB5D2C0
4 changed files with 25 additions and 25 deletions

View File

@ -184,13 +184,13 @@ fn main() {
// information to the PSBT. // information to the PSBT.
let ty = EcdsaSighashType::All.into(); let ty = EcdsaSighashType::All.into();
let derivation_paths = [ let derivation_paths = [
DerivationPath::from_str("m/84'/0'/0'/0/0").expect("valid derivation path"), "m/84'/0'/0'/0/0".parse::<DerivationPath>().expect("valid derivation path"),
DerivationPath::from_str("m/84'/0'/0'/1/0").expect("valid derivation path"), "m/84'/0'/0'/1/0".parse::<DerivationPath>().expect("valid derivation path"),
]; ];
let mut bip32_derivations = Vec::new(); let mut bip32_derivations = Vec::new();
for (idx, pk) in pk_inputs.iter().enumerate() { for (idx, pk) in pk_inputs.iter().enumerate() {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
let fingerprint = Fingerprint::from_str(MASTER_FINGERPRINT).expect("valid fingerprint"); let fingerprint = MASTER_FINGERPRINT.parse::<Fingerprint>().expect("valid fingerprint");
map.insert(pk.0, (fingerprint, derivation_paths[idx].clone())); map.insert(pk.0, (fingerprint, derivation_paths[idx].clone()));
bip32_derivations.push(map); bip32_derivations.push(map);
} }

View File

@ -112,7 +112,7 @@ impl ColdStorage {
/// ///
/// The newly created signer along with the data needed to configure a watch-only wallet. /// The newly created signer along with the data needed to configure a watch-only wallet.
fn new<C: Signing>(secp: &Secp256k1<C>, xpriv: &str) -> Result<ExportData> { fn new<C: Signing>(secp: &Secp256k1<C>, xpriv: &str) -> Result<ExportData> {
let master_xpriv = Xpriv::from_str(xpriv)?; let master_xpriv = xpriv.parse::<Xpriv>()?;
let master_xpub = Xpub::from_priv(secp, &master_xpriv); let master_xpub = Xpub::from_priv(secp, &master_xpriv);
// Hardened children require secret data to derive. // Hardened children require secret data to derive.
@ -176,10 +176,10 @@ impl WatchOnly {
/// Creates the PSBT, in BIP174 parlance this is the 'Creator'. /// Creates the PSBT, in BIP174 parlance this is the 'Creator'.
fn create_psbt<C: Verification>(&self, secp: &Secp256k1<C>) -> Result<Psbt> { fn create_psbt<C: Verification>(&self, secp: &Secp256k1<C>) -> Result<Psbt> {
let to_address = Address::from_str(RECEIVE_ADDRESS)?.require_network(Network::Regtest)?; let to_address = Address::from_str(RECEIVE_ADDRESS)?.require_network(Network::Regtest)?;
let to_amount = Amount::from_str(OUTPUT_AMOUNT_BTC)?; let to_amount = OUTPUT_AMOUNT_BTC.parse::<Amount>()?;
let (_, change_address, _) = self.change_address(secp)?; let (_, change_address, _) = self.change_address(secp)?;
let change_amount = Amount::from_str(CHANGE_AMOUNT_BTC)?; let change_amount = CHANGE_AMOUNT_BTC.parse::<Amount>()?;
let tx = Transaction { let tx = Transaction {
version: transaction::Version::TWO, version: transaction::Version::TWO,
@ -217,7 +217,7 @@ impl WatchOnly {
map.insert(pk.0, (fingerprint, path)); map.insert(pk.0, (fingerprint, path));
input.bip32_derivation = map; input.bip32_derivation = map;
let ty = PsbtSighashType::from_str("SIGHASH_ALL")?; let ty = "SIGHASH_ALL".parse::<PsbtSighashType>()?;
input.sighash_type = Some(ty); input.sighash_type = Some(ty);
psbt.inputs = vec![input]; psbt.inputs = vec![input];
@ -276,7 +276,7 @@ fn input_derivation_path() -> Result<DerivationPath> {
fn previous_output() -> TxOut { fn previous_output() -> TxOut {
let script_pubkey = ScriptBuf::from_hex(INPUT_UTXO_SCRIPT_PUBKEY) let script_pubkey = ScriptBuf::from_hex(INPUT_UTXO_SCRIPT_PUBKEY)
.expect("failed to parse input utxo scriptPubkey"); .expect("failed to parse input utxo scriptPubkey");
let amount = Amount::from_str(INPUT_UTXO_VALUE).expect("failed to parse input utxo value"); let amount = INPUT_UTXO_VALUE.parse::<Amount>().expect("failed to parse input utxo value");
TxOut { value: amount, script_pubkey } TxOut { value: amount, script_pubkey }
} }

View File

@ -151,13 +151,13 @@ fn main() {
// Map of tap root X-only keys to origin info and leaf hashes contained in it. // Map of tap root X-only keys to origin info and leaf hashes contained in it.
let origin_input_1 = get_tap_key_origin( let origin_input_1 = get_tap_key_origin(
pk_input_1, pk_input_1,
Fingerprint::from_str(MASTER_FINGERPRINT).unwrap(), MASTER_FINGERPRINT.parse::<Fingerprint>().unwrap(),
DerivationPath::from_str("m/86'/0'/0'/0/0").unwrap(), "m/86'/0'/0'/0/0".parse::<DerivationPath>().unwrap(),
); );
let origin_input_2 = get_tap_key_origin( let origin_input_2 = get_tap_key_origin(
pk_input_2, pk_input_2,
Fingerprint::from_str(MASTER_FINGERPRINT).unwrap(), MASTER_FINGERPRINT.parse::<Fingerprint>().unwrap(),
DerivationPath::from_str("m/86'/0'/0'/1/0").unwrap(), "m/86'/0'/0'/1/0".parse::<DerivationPath>().unwrap(),
); );
let origins = [origin_input_1, origin_input_2]; let origins = [origin_input_1, origin_input_2];

View File

@ -116,7 +116,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let tx_hex_string = encode::serialize_hex(&generate_bip86_key_spend_tx( let tx_hex_string = encode::serialize_hex(&generate_bip86_key_spend_tx(
&secp, &secp,
// The master extended private key from the descriptor in step 4 // The master extended private key from the descriptor in step 4
Xpriv::from_str(BENEFACTOR_XPRIV_STR)?, BENEFACTOR_XPRIV_STR.parse::<Xpriv>()?,
// Set these fields with valid data for the UTXO from step 5 above // Set these fields with valid data for the UTXO from step 5 above
UTXO_1, UTXO_1,
vec![ vec![
@ -135,10 +135,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("START EXAMPLE 2 - Script path spending of inheritance UTXO\n"); println!("START EXAMPLE 2 - Script path spending of inheritance UTXO\n");
{ {
let beneficiary = BeneficiaryWallet::new(Xpriv::from_str(BENEFICIARY_XPRIV_STR)?)?; let beneficiary = BeneficiaryWallet::new(BENEFICIARY_XPRIV_STR.parse::<Xpriv>()?)?;
let mut benefactor = BenefactorWallet::new( let mut benefactor = BenefactorWallet::new(
Xpriv::from_str(BENEFACTOR_XPRIV_STR)?, BENEFACTOR_XPRIV_STR.parse::<Xpriv>()?,
beneficiary.master_xpub(), beneficiary.master_xpub(),
)?; )?;
let (tx, psbt) = benefactor.create_inheritance_funding_tx( let (tx, psbt) = benefactor.create_inheritance_funding_tx(
@ -173,10 +173,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("START EXAMPLE 3 - Key path spending of inheritance UTXO\n"); println!("START EXAMPLE 3 - Key path spending of inheritance UTXO\n");
{ {
let beneficiary = BeneficiaryWallet::new(Xpriv::from_str(BENEFICIARY_XPRIV_STR)?)?; let beneficiary = BeneficiaryWallet::new(BENEFICIARY_XPRIV_STR.parse::<Xpriv>()?)?;
let mut benefactor = BenefactorWallet::new( let mut benefactor = BenefactorWallet::new(
Xpriv::from_str(BENEFACTOR_XPRIV_STR)?, BENEFACTOR_XPRIV_STR.parse::<Xpriv>()?,
beneficiary.master_xpub(), beneficiary.master_xpub(),
)?; )?;
let (tx, _) = benefactor.create_inheritance_funding_tx( let (tx, _) = benefactor.create_inheritance_funding_tx(
@ -227,7 +227,7 @@ fn generate_bip86_key_spend_tx(
outputs: Vec<TxOut>, outputs: Vec<TxOut>,
) -> Result<Transaction, Box<dyn std::error::Error>> { ) -> Result<Transaction, Box<dyn std::error::Error>> {
let from_amount = input_utxo.amount_in_sats; let from_amount = input_utxo.amount_in_sats;
let input_pubkey = XOnlyPublicKey::from_str(input_utxo.pubkey)?; let input_pubkey = input_utxo.pubkey.parse::<XOnlyPublicKey>()?;
// CREATOR + UPDATER // CREATOR + UPDATER
let tx1 = Transaction { let tx1 = Transaction {
@ -249,8 +249,8 @@ fn generate_bip86_key_spend_tx(
( (
vec![], vec![],
( (
Fingerprint::from_str(input_utxo.master_fingerprint)?, input_utxo.master_fingerprint.parse::<Fingerprint>()?,
DerivationPath::from_str(input_utxo.derivation_path)?, input_utxo.derivation_path.parse::<DerivationPath>()?,
), ),
), ),
); );
@ -264,7 +264,7 @@ fn generate_bip86_key_spend_tx(
tap_key_origins: origins, tap_key_origins: origins,
..Default::default() ..Default::default()
}; };
let ty = PsbtSighashType::from_str("SIGHASH_ALL")?; let ty = "SIGHASH_ALL".parse::<PsbtSighashType>()?;
input.sighash_type = Some(ty); input.sighash_type = Some(ty);
input.tap_internal_key = Some(input_pubkey); input.tap_internal_key = Some(input_pubkey);
psbt.inputs = vec![input]; psbt.inputs = vec![input];
@ -391,7 +391,7 @@ impl BenefactorWallet {
} }
// We use some other derivation path in this example for our inheritance protocol. The important thing is to ensure // We use some other derivation path in this example for our inheritance protocol. The important thing is to ensure
// that we use an unhardened path so we can make use of xpubs. // that we use an unhardened path so we can make use of xpubs.
let derivation_path = DerivationPath::from_str(&format!("101/1/0/0/{}", self.next))?; let derivation_path = format!("101/1/0/0/{}", self.next).parse::<DerivationPath>()?;
let internal_keypair = let internal_keypair =
self.master_xpriv.derive_priv(&self.secp, &derivation_path).to_keypair(&self.secp); self.master_xpriv.derive_priv(&self.secp, &derivation_path).to_keypair(&self.secp);
let beneficiary_key = let beneficiary_key =
@ -443,7 +443,7 @@ impl BenefactorWallet {
internal_keypair.x_only_public_key().0, internal_keypair.x_only_public_key().0,
(vec![], (self.master_xpriv.fingerprint(&self.secp), derivation_path)), (vec![], (self.master_xpriv.fingerprint(&self.secp), derivation_path)),
); );
let ty = PsbtSighashType::from_str("SIGHASH_ALL")?; let ty = "SIGHASH_ALL".parse::<PsbtSighashType>()?;
let mut tap_scripts = BTreeMap::new(); let mut tap_scripts = BTreeMap::new();
tap_scripts.insert( tap_scripts.insert(
taproot_spend_info.control_block(&(script.clone(), LeafVersion::TapScript)).unwrap(), taproot_spend_info.control_block(&(script.clone(), LeafVersion::TapScript)).unwrap(),
@ -480,7 +480,7 @@ impl BenefactorWallet {
// We use some other derivation path in this example for our inheritance protocol. The important thing is to ensure // We use some other derivation path in this example for our inheritance protocol. The important thing is to ensure
// that we use an unhardened path so we can make use of xpubs. // that we use an unhardened path so we can make use of xpubs.
let new_derivation_path = let new_derivation_path =
DerivationPath::from_str(&format!("101/1/0/0/{}", self.next))?; format!("101/1/0/0/{}", self.next).parse::<DerivationPath>()?;
let new_internal_keypair = self let new_internal_keypair = self
.master_xpriv .master_xpriv
.derive_priv(&self.secp, &new_derivation_path) .derive_priv(&self.secp, &new_derivation_path)
@ -582,7 +582,7 @@ impl BenefactorWallet {
beneficiary_key, beneficiary_key,
(vec![leaf_hash], (self.beneficiary_xpub.fingerprint(), new_derivation_path)), (vec![leaf_hash], (self.beneficiary_xpub.fingerprint(), new_derivation_path)),
); );
let ty = PsbtSighashType::from_str("SIGHASH_ALL")?; let ty = "SIGHASH_ALL".parse::<PsbtSighashType>()?;
let mut tap_scripts = BTreeMap::new(); let mut tap_scripts = BTreeMap::new();
tap_scripts.insert( tap_scripts.insert(
taproot_spend_info taproot_spend_info