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