Skip to content

Commit a725e4d

Browse files
feat: add methods to convert ExtendedPrivKey and ExtendedPubKey to PrivateKey and PublicKey (#101)
1 parent 0901ab1 commit a725e4d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

key-wallet/src/bip32.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1706,6 +1706,15 @@ impl ExtendedPrivKey {
17061706
pub fn fingerprint<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Fingerprint {
17071707
self.identifier(secp)[0..4].try_into().expect("4 is the fingerprint length")
17081708
}
1709+
1710+
/// Convert to a PrivateKey for signing operations
1711+
pub fn to_priv(&self) -> dashcore::PrivateKey {
1712+
dashcore::PrivateKey {
1713+
compressed: true,
1714+
network: self.network.into(),
1715+
inner: self.private_key,
1716+
}
1717+
}
17091718
}
17101719

17111720
impl ExtendedPubKey {
@@ -1991,6 +2000,14 @@ impl ExtendedPubKey {
19912000
pub fn fingerprint(&self) -> Fingerprint {
19922001
self.identifier()[0..4].try_into().expect("4 is the fingerprint length")
19932002
}
2003+
2004+
/// Convert to a PublicKey for use in address generation
2005+
pub fn to_pub(&self) -> dashcore::PublicKey {
2006+
dashcore::PublicKey {
2007+
compressed: true,
2008+
inner: self.public_key,
2009+
}
2010+
}
19942011
}
19952012

19962013
impl fmt::Display for ExtendedPrivKey {
@@ -2677,4 +2694,29 @@ mod tests {
26772694
"0251b09b90295c4c793e9452af0e14142c3406b67e864541149de708eb2d41d104"
26782695
); // Add correct expected value
26792696
}
2697+
2698+
#[test]
2699+
fn test_to_priv_and_to_pub() {
2700+
let seed = [0x42u8; 32];
2701+
let network = Network::Testnet;
2702+
2703+
let ext_priv = ExtendedPrivKey::new_master(network, &seed).unwrap();
2704+
let secp = Secp256k1::new();
2705+
2706+
// Test to_priv() method
2707+
let priv_key = ext_priv.to_priv();
2708+
assert_eq!(priv_key.compressed, true);
2709+
assert_eq!(priv_key.network, dashcore::Network::Testnet);
2710+
assert_eq!(priv_key.inner, ext_priv.private_key);
2711+
2712+
// Test to_pub() method
2713+
let ext_pub = ExtendedPubKey::from_priv(&secp, &ext_priv);
2714+
let pub_key = ext_pub.to_pub();
2715+
assert_eq!(pub_key.compressed, true);
2716+
assert_eq!(pub_key.inner, ext_pub.public_key);
2717+
2718+
// Verify the keys match
2719+
let pub_from_priv = dashcore::PublicKey::from_private_key(&secp, &priv_key);
2720+
assert_eq!(pub_key.inner, pub_from_priv.inner);
2721+
}
26802722
}

0 commit comments

Comments
 (0)