wagyu_model/
private_key.rs1use crate::address::{Address, AddressError};
2use crate::format::Format;
3use crate::public_key::PublicKey;
4
5use rand::Rng;
6use std::{
7 fmt::{Debug, Display},
8 str::FromStr,
9};
10
11pub trait PrivateKey: Clone + Debug + Display + FromStr + Send + Sync + 'static + Eq + Sized {
13 type Address: Address;
14 type Format: Format;
15 type PublicKey: PublicKey;
16
17 fn new<R: Rng>(rng: &mut R) -> Result<Self, PrivateKeyError>;
19
20 fn to_public_key(&self) -> Self::PublicKey;
22
23 fn to_address(&self, format: &Self::Format) -> Result<Self::Address, AddressError>;
25}
26
27#[derive(Debug, Fail)]
28pub enum PrivateKeyError {
29 #[fail(display = "{}: {}", _0, _1)]
30 Crate(&'static str, String),
31
32 #[fail(display = "invalid byte length: {}", _0)]
33 InvalidByteLength(usize),
34
35 #[fail(display = "invalid character length: {}", _0)]
36 InvalidCharacterLength(usize),
37
38 #[fail(display = "invalid private key checksum: {{ expected: {:?}, found: {:?} }}", _0, _1)]
39 InvalidChecksum(String, String),
40
41 #[fail(display = "invalid network: {{ expected: {:?}, found: {:?} }}", _0, _1)]
42 InvalidNetwork(String, String),
43
44 #[fail(display = "invalid private key prefix: {:?}", _0)]
45 InvalidPrefix(Vec<u8>),
46
47 #[fail(display = "{}", _0)]
48 Message(String),
49
50 #[fail(display = "unsupported format")]
51 UnsupportedFormat,
52}
53
54impl From<&'static str> for PrivateKeyError {
55 fn from(msg: &'static str) -> Self {
56 PrivateKeyError::Message(msg.into())
57 }
58}
59
60impl From<base58::FromBase58Error> for PrivateKeyError {
61 fn from(error: base58::FromBase58Error) -> Self {
62 PrivateKeyError::Crate("base58", format!("{:?}", error))
63 }
64}
65
66impl From<bech32::Error> for PrivateKeyError {
67 fn from(error: bech32::Error) -> Self {
68 PrivateKeyError::Crate("bech32", format!("{:?}", error))
69 }
70}
71
72impl From<hex::FromHexError> for PrivateKeyError {
73 fn from(error: hex::FromHexError) -> Self {
74 PrivateKeyError::Crate("hex", format!("{:?}", error))
75 }
76}
77
78impl From<rand_core::Error> for PrivateKeyError {
79 fn from(error: rand_core::Error) -> Self {
80 PrivateKeyError::Crate("rand", format!("{:?}", error))
81 }
82}
83
84impl From<secp256k1::Error> for PrivateKeyError {
85 fn from(error: secp256k1::Error) -> Self {
86 PrivateKeyError::Crate("secp256k1", format!("{:?}", error))
87 }
88}
89
90impl From<std::io::Error> for PrivateKeyError {
91 fn from(error: std::io::Error) -> Self {
92 PrivateKeyError::Crate("std::io", format!("{:?}", error))
93 }
94}