Skip to main content

wagyu_model/
public_key.rs

1use crate::address::{Address, AddressError};
2use crate::format::Format;
3use crate::private_key::PrivateKey;
4
5use std::{
6    fmt::{Debug, Display},
7    str::FromStr,
8};
9
10/// The interface for a generic public key.
11pub trait PublicKey: Clone + Debug + Display + FromStr + Send + Sync + 'static + Eq + Sized {
12    type Address: Address;
13    type Format: Format;
14    type PrivateKey: PrivateKey;
15
16    /// Returns the address corresponding to the given public key.
17    fn from_private_key(private_key: &Self::PrivateKey) -> Self;
18
19    /// Returns the address of the corresponding private key.
20    fn to_address(&self, format: &Self::Format) -> Result<Self::Address, AddressError>;
21}
22
23#[derive(Debug, Fail)]
24pub enum PublicKeyError {
25    #[fail(display = "{}: {}", _0, _1)]
26    Crate(&'static str, String),
27
28    #[fail(display = "invalid byte length: {}", _0)]
29    InvalidByteLength(usize),
30
31    #[fail(display = "invalid character length: {}", _0)]
32    InvalidCharacterLength(usize),
33
34    #[fail(display = "invalid public key prefix: {:?}", _0)]
35    InvalidPrefix(String),
36
37    #[fail(display = "no public spending key found")]
38    NoSpendingKey,
39
40    #[fail(display = "no public viewing key found")]
41    NoViewingKey,
42}
43
44impl From<base58::FromBase58Error> for PublicKeyError {
45    fn from(error: base58::FromBase58Error) -> Self {
46        PublicKeyError::Crate("base58", format!("{:?}", error))
47    }
48}
49
50impl From<bech32::Error> for PublicKeyError {
51    fn from(error: bech32::Error) -> Self {
52        PublicKeyError::Crate("bech32", format!("{:?}", error))
53    }
54}
55
56impl From<hex::FromHexError> for PublicKeyError {
57    fn from(error: hex::FromHexError) -> Self {
58        PublicKeyError::Crate("hex", format!("{:?}", error))
59    }
60}
61
62impl From<secp256k1::Error> for PublicKeyError {
63    fn from(error: secp256k1::Error) -> Self {
64        PublicKeyError::Crate("secp256k1", format!("{:?}", error))
65    }
66}
67
68impl From<std::io::Error> for PublicKeyError {
69    fn from(error: std::io::Error) -> Self {
70        PublicKeyError::Crate("std::io", format!("{:?}", error))
71    }
72}