Skip to main content

kaspa_bip32/
private_key.rs

1use crate::PublicKey;
2use crate::Result;
3use crate::types::*;
4pub use secp256k1::SecretKey;
5use secp256k1::{Secp256k1, SignOnly, scalar::Scalar};
6
7/// Trait for private key types which can be derived using BIP32.
8pub trait PrivateKey: Sized {
9    /// Public key type which corresponds to this private key.
10    type PublicKey: PublicKey;
11
12    /// Initialize this key from bytes.
13    fn from_bytes(bytes: &PrivateKeyBytes) -> Result<Self>;
14
15    /// Serialize this key as bytes.
16    fn to_bytes(&self) -> PrivateKeyBytes;
17
18    /// Derive a child key from a parent key and the a provided tweak value,
19    /// i.e. where `other` is referred to as "I sub L" in BIP32 and sourced
20    /// from the left half of the HMAC-SHA-512 output.
21    fn derive_child(&self, other: PrivateKeyBytes) -> Result<Self>;
22
23    /// Get the [`Self::PublicKey`] that corresponds to this private key.
24    fn public_key(&self) -> Self::PublicKey;
25}
26
27impl PrivateKey for SecretKey {
28    type PublicKey = secp256k1::PublicKey;
29
30    fn from_bytes(bytes: &PrivateKeyBytes) -> Result<Self> {
31        Ok(SecretKey::from_slice(bytes)?)
32    }
33
34    fn to_bytes(&self) -> PrivateKeyBytes {
35        *self.as_ref()
36    }
37
38    fn derive_child(&self, other: PrivateKeyBytes) -> Result<Self> {
39        Ok((*self).add_tweak(&Scalar::from_be_bytes(other)?)?)
40    }
41
42    fn public_key(&self) -> Self::PublicKey {
43        let engine = Secp256k1::<SignOnly>::signing_only();
44        secp256k1::PublicKey::from_secret_key(&engine, self)
45    }
46}