diff --git a/src/util/bip32.rs b/src/util/bip32.rs index 0e70c8ee..efc40a4f 100644 --- a/src/util/bip32.rs +++ b/src/util/bip32.rs @@ -497,14 +497,12 @@ impl ExtendedPrivKey { hmac_engine.input(seed); let hmac_result: Hmac = Hmac::from_engine(hmac_engine); - let sk = secp256k1::SecretKey::from_slice(&hmac_result[..32])?; - Ok(ExtendedPrivKey { network: network, depth: 0, parent_fingerprint: Default::default(), child_number: ChildNumber::from_normal_idx(0)?, - private_key: PrivateKey::new(sk, network), + private_key: PrivateKey::from_slice(&hmac_result[..32], network)?, chain_code: ChainCode::from(&hmac_result[32..]), }) } @@ -541,11 +539,8 @@ impl ExtendedPrivKey { hmac_engine.input(&endian::u32_to_array_be(u32::from(i))); let hmac_result: Hmac = Hmac::from_engine(hmac_engine); - let mut sk = PrivateKey::new( - secp256k1::SecretKey::from_slice(&hmac_result[..32])?, - self.network - ); - sk.key.add_assign(&self.private_key[..]).map_err(Error::Ecdsa)?; + let mut sk = PrivateKey::from_slice(&hmac_result[..32], self.network)?; + sk.key.add_assign(&self.private_key[..])?; Ok(ExtendedPrivKey { network: self.network, @@ -573,18 +568,13 @@ impl ExtendedPrivKey { return Err(Error::UnknownVersion(ver)); }; - let sk = PrivateKey::new( - secp256k1::SecretKey::from_slice(&data[46..78])?, - network - ); - Ok(ExtendedPrivKey { network: network, depth: data[4], parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: endian::slice_to_u32_be(&data[9..13]).into(), chain_code: ChainCode::from(&data[13..45]), - private_key: sk, + private_key: PrivateKey::from_slice(&data[46..78], network)?, }) } @@ -656,10 +646,7 @@ impl ExtendedPubKey { let hmac_result: Hmac = Hmac::from_engine(hmac_engine); - let private_key = PrivateKey::new( - secp256k1::SecretKey::from_slice(&hmac_result[..32])?, - self.network, - ); + let private_key = PrivateKey::from_slice(&hmac_result[..32], self.network)?; let chain_code = ChainCode::from(&hmac_result[32..]); Ok((private_key, chain_code)) } @@ -674,7 +661,7 @@ impl ExtendedPubKey { ) -> Result { let (sk, chain_code) = self.ckd_pub_tweak(i)?; let mut pk = self.public_key; - pk.key.add_exp_assign(secp, &sk[..]).map_err(Error::Ecdsa)?; + pk.key.add_exp_assign(secp, &sk[..])?; Ok(ExtendedPubKey { network: self.network, diff --git a/src/util/ecdsa.rs b/src/util/ecdsa.rs index c62ac585..99d7af67 100644 --- a/src/util/ecdsa.rs +++ b/src/util/ecdsa.rs @@ -201,6 +201,14 @@ impl PrivateKey { self.key[..].to_vec() } + /// Deserialize a private key from a slice + pub fn from_slice(data: &[u8], network: Network) -> Result { + Ok(PrivateKey::new( + secp256k1::SecretKey::from_slice(data)?, + network, + )) + } + /// Format the private key to WIF format. pub fn fmt_wif(&self, fmt: &mut dyn fmt::Write) -> fmt::Result { let mut ret = [0; 34];