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