Derive Debug for PrivateKey for no-std builds

Currently we derive `impl Debug for PrivateKey` for "std" builds and
manually implement an obfuscated version for "no-std" builds. Since
we enable the `hashes` feature of `rust-secp` this is unnecessary
because secp takes care of obfuscating the secret for us.
This commit is contained in:
Tobin C. Harding 2023-11-21 14:34:53 +11:00
parent 8aa5501827
commit 3d17031725
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 22 additions and 7 deletions

View File

@ -263,8 +263,7 @@ impl From<&PublicKey> for PubkeyHash {
} }
/// A Bitcoin ECDSA private key /// A Bitcoin ECDSA private key
#[derive(Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct PrivateKey { pub struct PrivateKey {
/// Whether this private key should be serialized as compressed /// Whether this private key should be serialized as compressed
pub compressed: bool, pub compressed: bool,
@ -367,11 +366,6 @@ impl fmt::Display for PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.fmt_wif(f) } fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.fmt_wif(f) }
} }
#[cfg(not(feature = "std"))]
impl fmt::Debug for PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[private key data]") }
}
impl FromStr for PrivateKey { impl FromStr for PrivateKey {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<PrivateKey, Error> { PrivateKey::from_wif(s) } fn from_str(s: &str) -> Result<PrivateKey, Error> { PrivateKey::from_wif(s) }
@ -1091,4 +1085,25 @@ mod tests {
assert!(res.is_err()); assert!(res.is_err());
assert_eq!(res.unwrap_err(), Error::InvalidHexLength(8)); assert_eq!(res.unwrap_err(), Error::InvalidHexLength(8));
} }
#[test]
#[cfg(feature = "std")]
fn private_key_debug_is_obfuscated() {
let sk =
PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
let want = "PrivateKey { compressed: true, network: Testnet, inner: SecretKey(#32014e414fdce702) }";
let got = format!("{:?}", sk);
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(feature = "std"), feature = "no-std"))]
fn private_key_debug_is_obfuscated() {
let sk =
PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
// Why is this not shortened? In rust-secp256k1/src/secret it is printed with "#{:016x}"?
let want = "PrivateKey { compressed: true, network: Testnet, inner: SecretKey(#7217ac58fbad8880a91032107b82cb6c5422544b426c350ee005cf509f3dbf7b) }";
let got = format!("{:?}", sk);
assert_eq!(got, want)
}
} }