1extern crate alloc;
6use crate::{pubkey::PubKeyError, seckey::SecKeyError, CurvePoint, PubKey, ScalarField, SecKey};
7use alloc::{string::String, vec::Vec};
8use core::fmt;
9use rand::{self, CryptoRng, RngCore};
10use thiserror::Error;
11
12#[derive(Error, Debug, Clone, PartialEq, Eq)]
14pub enum KeypairError {
15 #[error(transparent)]
17 SecretKey(#[from] SecKeyError),
18 #[error(transparent)]
20 PublicKey(#[from] PubKeyError),
21 #[error("point not on curve")]
23 NonCurvePoint,
24}
25pub type Result<T> = core::result::Result<T, KeypairError>;
27
28#[derive(Clone, PartialEq, Eq)]
30pub struct Keypair {
31 pub secret: SecKey,
33 pub public: PubKey,
35}
36
37impl Keypair {
38 pub fn from_parts_unsafe(secret: ScalarField, public: CurvePoint) -> Self {
41 Self {
42 secret: SecKey::new(secret),
43 public: PubKey::from_point_unsafe(public),
44 }
45 }
46
47 pub fn from_secret_key(secret_key: SecKey) -> Result<Self> {
49 let public = PubKey::from_secret_key(secret_key.clone())?;
50
51 Ok(Self::from_parts_unsafe(
53 secret_key.into_scalar(),
54 public.into_point(),
55 ))
56 }
57
58 pub fn rand(rng: &mut (impl RngCore + CryptoRng)) -> Result<Self> {
60 let sec_key: SecKey = SecKey::rand(rng);
61 Keypair::from_secret_key(sec_key)
62 }
63
64 pub fn from_bytes(secret_bytes: &[u8]) -> Result<Self> {
70 let secret = SecKey::from_bytes(secret_bytes)?;
71 Keypair::from_secret_key(secret)
72 }
73
74 pub fn from_hex(secret_hex: &str) -> Result<Self> {
80 let secret = SecKey::from_hex(secret_hex)?;
81 Keypair::from_secret_key(secret)
82 }
83
84 pub fn get_address(self) -> String {
86 self.public.into_address()
87 }
88
89 pub fn to_bytes(&self) -> Vec<u8> {
91 self.secret.to_bytes()
92 }
93
94 pub fn to_hex(&self) -> String {
96 hex::encode(self.to_bytes())
97 }
98}
99
100impl fmt::Debug for Keypair {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "{:?}", self.public)
104 }
105}
106
107impl fmt::Display for Keypair {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(f, "{}", self.public)
111 }
112}