Skip to content

Commit ad7b448

Browse files
authored
Improve some docs for the public facing types (#76)
1 parent dd9ee72 commit ad7b448

File tree

3 files changed

+108
-5
lines changed

3 files changed

+108
-5
lines changed

src/keypair.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ pub trait Sign {
99
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>>;
1010
}
1111

12+
/// Represents a cryptographic keypair for any supported key type.
13+
///
14+
/// This enum acts as a type-erased wrapper for all supported keypair types (e.g., Ed25519, Secp256k1, ECC Compact, etc.),
15+
/// allowing generic handling of key generation, signing, and public key extraction.
1216
#[derive(PartialEq, Debug)]
1317
pub enum Keypair {
1418
Secp256k1(secp256k1::Keypair),
@@ -45,6 +49,17 @@ impl Sign for Keypair {
4549
}
4650

4751
impl Keypair {
52+
/// Generates a new keypair for the specified key type and network using the provided CSPRNG.
53+
///
54+
/// # Arguments
55+
/// * `key_tag` - The key tag specifying the network and key type.
56+
/// * `csprng` - A cryptographically secure random number generator.
57+
///
58+
/// # Returns
59+
/// A new `Keypair` instance for the requested type and network.
60+
///
61+
/// # Panics
62+
/// Panics if the key type is not supported or if key generation fails.
4863
pub fn generate<R>(key_tag: KeyTag, csprng: &mut R) -> Keypair
4964
where
5065
R: rand_core::CryptoRng + rand_core::RngCore,
@@ -64,6 +79,17 @@ impl Keypair {
6479
}
6580
}
6681

82+
/// Generates a new keypair from the provided entropy for the specified key type and network.
83+
///
84+
/// # Arguments
85+
/// * `key_tag` - The key tag specifying the network and key type.
86+
/// * `entropy` - A byte slice containing sufficient entropy for key generation.
87+
///
88+
/// # Returns
89+
/// A new `Keypair` instance if the entropy is valid for the requested type and network.
90+
///
91+
/// # Errors
92+
/// Returns an error if the entropy is invalid or the key type is not supported.
6793
pub fn generate_from_entropy(key_tag: KeyTag, entropy: &[u8]) -> Result<Keypair> {
6894
match key_tag.key_type {
6995
KeyType::EccCompact => Ok(Self::EccCompact(
@@ -87,6 +113,9 @@ impl Keypair {
87113
}
88114
}
89115

116+
/// Returns the key tag for this keypair, encoding the network and key type.
117+
///
118+
/// The key tag is used to identify the network and cryptographic algorithm associated with this keypair.
90119
pub fn key_tag(&self) -> KeyTag {
91120
match self {
92121
Self::Secp256k1(keypair) => keypair.key_tag(),
@@ -103,6 +132,9 @@ impl Keypair {
103132
}
104133
}
105134

135+
/// Returns a reference to the public key associated with this keypair.
136+
///
137+
/// The returned public key can be used for signature verification or key exchange.
106138
pub fn public_key(&self) -> &PublicKey {
107139
match self {
108140
Self::Secp256k1(keypair) => &keypair.public_key,
@@ -119,6 +151,16 @@ impl Keypair {
119151
}
120152
}
121153

154+
/// Performs an Elliptic Curve Diffie-Hellman (ECDH) key exchange with the given public key.
155+
///
156+
/// # Arguments
157+
/// * `public_key` - The peer's public key.
158+
///
159+
/// # Returns
160+
/// A shared secret if ECDH is supported for this key type.
161+
///
162+
/// # Errors
163+
/// Returns an error if ECDH is not supported for this key type or if the operation fails.
122164
pub fn ecdh(&self, public_key: &PublicKey) -> Result<SharedSecret> {
123165
match self {
124166
Self::EccCompact(keypair) => Ok(SharedSecret(keypair.ecdh(public_key)?)),
@@ -130,6 +172,10 @@ impl Keypair {
130172
}
131173
}
132174

175+
/// Serializes the keypair to its binary representation.
176+
///
177+
/// # Returns
178+
/// A vector of bytes containing the serialized keypair, including the key tag and secret key material.
133179
pub fn to_vec(&self) -> Vec<u8> {
134180
match self {
135181
Self::Secp256k1(keypair) => keypair.to_vec(),
@@ -146,6 +192,13 @@ impl Keypair {
146192
}
147193
}
148194

195+
/// Serializes the secret key material to its binary representation.
196+
///
197+
/// # Returns
198+
/// A vector of bytes containing the secret key material only (excluding the key tag).
199+
///
200+
/// # Security
201+
/// Handle this output with care, as it contains sensitive private key material.
149202
pub fn secret_to_vec(&self) -> Vec<u8> {
150203
match self {
151204
Self::Secp256k1(keypair) => keypair.secret_to_vec(),

src/public_key.rs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ pub trait PublicKeySize {
2222
/// A public key representing any of the supported public key types on a given
2323
/// network.
2424
///
25-
/// Public keys can convert to and from their binary and base58 representation
25+
/// This struct acts as a type-erased wrapper for all supported public key types (e.g., Ed25519, Secp256k1, ECC Compact, etc.),
26+
/// allowing generic handling of serialization, deserialization, and verification.
27+
/// Public keys can be converted to and from their binary and base58 representations.
2628
#[derive(Clone, PartialEq, Eq, Hash)]
2729
pub struct PublicKey {
2830
/// The network this public key is valid for
@@ -370,12 +372,21 @@ impl PublicKey {
370372
}
371373
}
372374

373-
/// Construct a public key from its binary form
375+
/// Constructs a public key from its binary representation.
376+
///
377+
/// # Arguments
378+
/// * `bytes` - A byte slice containing the binary representation of the public key.
379+
///
380+
/// # Errors
381+
/// Returns an error if the bytes do not represent a valid public key for the expected type.
374382
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
375383
Self::try_from(bytes.as_ref())
376384
}
377385

378-
/// Convert a public key to it's binary form.
386+
/// Serializes the public key to its binary representation.
387+
///
388+
/// # Returns
389+
/// A vector of bytes containing the serialized public key, including the key tag and key material.
379390
pub fn to_vec(&self) -> Vec<u8> {
380391
let mut result = vec![0u8; self.public_key_size()];
381392
// Unwrap ok here since we've allocated enough space for the output
@@ -384,7 +395,10 @@ impl PublicKey {
384395
result
385396
}
386397

387-
/// Get the type for this key
398+
/// Returns the type of this public key (e.g., Ed25519, Secp256k1, etc.).
399+
///
400+
/// # Returns
401+
/// The `KeyType` variant corresponding to the underlying public key.
388402
pub fn key_type(&self) -> KeyType {
389403
match self.inner {
390404
PublicKeyRepr::EccCompact(..) => KeyType::EccCompact,
@@ -397,14 +411,20 @@ impl PublicKey {
397411
}
398412
}
399413

400-
/// Get the tag for this key
414+
/// Returns the key tag for this public key, encoding the network and key type.
415+
///
416+
/// The key tag is used to identify the network and cryptographic algorithm associated with this public key.
401417
pub fn key_tag(&self) -> KeyTag {
402418
KeyTag {
403419
network: self.network,
404420
key_type: self.key_type(),
405421
}
406422
}
407423

424+
/// Returns the size in bytes of the public key, including any prefix bytes.
425+
///
426+
/// # Returns
427+
/// The length in bytes of the serialized public key for the underlying type.
408428
pub fn public_key_size(&self) -> usize {
409429
match &self.inner {
410430
PublicKeyRepr::EccCompact(..) => ecc_compact::PublicKey::PUBLIC_KEY_SIZE,

src/public_key_binary.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
use crate::{Error, KeyTag, PublicKey, Result};
22
use std::{convert::TryFrom, fmt, str::FromStr};
33

4+
/// An intermediate binary representation of a public key.
5+
///
6+
/// `PublicKeyBinary` wraps the raw bytes of a public key, including its key tag, and provides convenient
7+
/// conversions to and from [`PublicKey`], byte slices, and base58-encoded strings. This is useful for
8+
/// serialization, deserialization, and as a database-friendly format.
49
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
510
pub struct PublicKeyBinary(Vec<u8>);
611

@@ -16,6 +21,13 @@ impl fmt::Debug for PublicKeyBinary {
1621
}
1722

1823
impl From<PublicKey> for PublicKeyBinary {
24+
/// Converts a [`PublicKey`] into its binary representation.
25+
///
26+
/// # Arguments
27+
/// * `value` - The [`PublicKey`] to convert.
28+
///
29+
/// # Returns
30+
/// A `PublicKeyBinary` containing the serialized bytes of the public key.
1931
fn from(value: PublicKey) -> Self {
2032
Self(value.to_vec())
2133
}
@@ -41,6 +53,13 @@ impl From<PublicKeyBinary> for Vec<u8> {
4153

4254
impl TryFrom<PublicKeyBinary> for PublicKey {
4355
type Error = Error;
56+
/// Attempts to parse a [`PublicKey`] from its binary representation.
57+
///
58+
/// # Arguments
59+
/// * `value` - The `PublicKeyBinary` to parse.
60+
///
61+
/// # Errors
62+
/// Returns an error if the bytes do not represent a valid public key.
4463
fn try_from(value: PublicKeyBinary) -> Result<Self> {
4564
Self::try_from(value.0)
4665
}
@@ -54,13 +73,24 @@ impl AsRef<[u8]> for PublicKeyBinary {
5473

5574
impl std::str::FromStr for PublicKeyBinary {
5675
type Err = Error;
76+
/// Parses a `PublicKeyBinary` from a base58-encoded string.
77+
///
78+
/// # Arguments
79+
/// * `s` - The base58-encoded string.
80+
///
81+
/// # Errors
82+
/// Returns an error if the string is not valid base58 or does not decode to a valid public key binary.
5783
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
5884
let mut data = bs58::decode(s).with_check(Some(0)).into_vec()?;
5985
Ok(Self(data.split_off(1)))
6086
}
6187
}
6288

6389
impl std::fmt::Display for PublicKeyBinary {
90+
/// Formats the `PublicKeyBinary` as a base58-encoded string, suitable for display or storage.
91+
///
92+
/// # Returns
93+
/// A base58-encoded string representation of the public key binary.
6494
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
6595
// allocate one extra byte for the base58 version
6696
let mut data = vec![0u8; self.0.len() + 1];

0 commit comments

Comments
 (0)