1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
mod ed25519;
use alloc::{str::FromStr, string::String};
use bech32::{self, FromBase32, ToBase32, Variant};
use bee_common::packable::{Packable, Read, Write};
pub use self::ed25519::{Ed25519Address, ED25519_ADDRESS_LENGTH};
use crate::{signature::SignatureUnlock, Error};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(tag = "type", content = "data")
)]
pub enum Address {
Ed25519(Ed25519Address),
}
impl Address {
pub fn kind(&self) -> u8 {
match self {
Self::Ed25519(_) => Ed25519Address::KIND,
}
}
pub fn try_from_bech32(addr: &str) -> Result<Self, Error> {
match bech32::decode(addr) {
Ok((_hrp, data, _)) => {
let bytes = Vec::<u8>::from_base32(&data).map_err(|_| Error::InvalidAddress)?;
Self::unpack(&mut bytes.as_slice()).map_err(|_| Error::InvalidAddress)
}
Err(_) => Err(Error::InvalidAddress),
}
}
#[allow(clippy::wrong_self_convention)]
pub fn to_bech32(&self, hrp: &str) -> String {
bech32::encode(hrp, self.pack_new().to_base32(), Variant::Bech32).expect("Invalid address.")
}
pub fn verify(&self, msg: &[u8], signature: &SignatureUnlock) -> Result<(), Error> {
match self {
Address::Ed25519(address) => {
let SignatureUnlock::Ed25519(signature) = signature;
address.verify(msg, signature)
}
}
}
}
impl From<Ed25519Address> for Address {
fn from(address: Ed25519Address) -> Self {
Self::Ed25519(address)
}
}
impl FromStr for Address {
type Err = Error;
fn from_str(address: &str) -> Result<Self, Self::Err> {
Address::try_from_bech32(address)
}
}
impl TryFrom<String> for Address {
type Error = Error;
fn try_from(address: String) -> Result<Self, Self::Error> {
Address::from_str(&address)
}
}
impl Packable for Address {
type Error = Error;
fn packed_len(&self) -> usize {
match self {
Self::Ed25519(address) => Ed25519Address::KIND.packed_len() + address.packed_len(),
}
}
fn pack<W: Write>(&self, writer: &mut W) -> Result<(), Self::Error> {
match self {
Self::Ed25519(address) => {
Ed25519Address::KIND.pack(writer)?;
address.pack(writer)?;
}
}
Ok(())
}
fn unpack_inner<R: Read + ?Sized, const CHECK: bool>(reader: &mut R) -> Result<Self, Self::Error> {
Ok(match u8::unpack_inner::<R, CHECK>(reader)? {
Ed25519Address::KIND => Ed25519Address::unpack_inner::<R, CHECK>(reader)?.into(),
k => return Err(Self::Error::InvalidAddressKind(k)),
})
}
}