bc_components/ec_key/
ec_key_base.rs

1use bc_ur::UREncodable;
2use anyhow::Result;
3
4use crate::ECPublicKey;
5
6/// A base trait for all elliptic curve keys.
7///
8/// This trait defines common functionality for all elliptic curve keys, including
9/// both private and public keys. It provides methods for key construction from
10/// binary data and hexadecimal strings, as well as conversion to hexadecimal format.
11///
12/// All EC key types have a fixed size depending on their specific type:
13/// - EC private keys: 32 bytes
14/// - EC compressed public keys: 33 bytes
15/// - EC uncompressed public keys: 65 bytes
16/// - Schnorr public keys: 32 bytes
17pub trait ECKeyBase:
18    std::fmt::Display +
19    std::fmt::Debug +
20    Clone +
21    PartialEq + Eq +
22    core::hash::Hash
23{
24    /// The size of the key in bytes.
25    const KEY_SIZE: usize;
26
27    /// Creates a key from a reference to binary data.
28    ///
29    /// Returns an error if the data is not valid for this key type.
30    fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> where Self: Sized;
31    
32    /// Returns the key's binary data.
33    fn data(&self) -> &[u8];
34
35    /// Returns the key as a hexadecimal string.
36    fn hex(&self) -> String {
37        hex::encode(self.data())
38    }
39
40    /// Creates a key from a hexadecimal string.
41    ///
42    /// Returns an error if the string is not valid hexadecimal or if the
43    /// resulting data is not valid for this key type.
44    fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
45        let data = hex::decode(hex.as_ref())?;
46        Self::from_data_ref(data)
47    }
48}
49
50/// A trait for elliptic curve keys that can derive a public key.
51///
52/// This trait extends `ECKeyBase` to provide a method for deriving
53/// the corresponding compressed public key. It is implemented by both
54/// private keys (where it generates the public key) and public keys
55/// (where it may return self or convert between formats).
56pub trait ECKey: ECKeyBase + UREncodable {
57    /// Returns the compressed public key corresponding to this key.
58    fn public_key(&self) -> ECPublicKey;
59}