-
Notifications
You must be signed in to change notification settings - Fork 114
/
base.rs
189 lines (159 loc) · 5.17 KB
/
base.rs
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! Base functionality.
use crate::{proto, Decimal, Error, ErrorReport, Result};
use eyre::WrapErr;
use serde::{de, de::Error as _, ser, Deserialize, Serialize};
use std::{fmt, str::FromStr};
use subtle_encoding::bech32;
/// Account identifiers
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
pub struct AccountId {
/// Account ID encoded as Bech32
bech32: String,
/// Length of the human-readable prefix of the address
hrp_length: usize,
}
impl AccountId {
/// Create an [`AccountId`] with the given human-readable prefix and
/// public key hash.
pub fn new(prefix: &str, bytes: [u8; tendermint::account::LENGTH]) -> Result<Self> {
let id = bech32::encode(prefix, &bytes);
// TODO(tarcieri): ensure this is the proper validation for an account prefix
if prefix.chars().all(|c| matches!(c, 'a'..='z')) {
Ok(Self {
bech32: id,
hrp_length: prefix.len(),
})
} else {
Err(Error::AccountId { id })
.wrap_err("expected prefix to be lowercase alphabetical characters only")
}
}
/// Get the human-readable prefix of this account.
pub fn prefix(&self) -> &str {
&self.bech32[..self.hrp_length]
}
/// Decode an account ID from Bech32 to an inner byte value.
pub fn to_bytes(&self) -> [u8; tendermint::account::LENGTH] {
bech32::decode(&self.bech32)
.ok()
.and_then(|result| result.1.try_into().ok())
.expect("malformed Bech32 AccountId")
}
}
impl AsRef<str> for AccountId {
fn as_ref(&self) -> &str {
&self.bech32
}
}
impl fmt::Debug for AccountId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("AccountId").field(&self.as_ref()).finish()
}
}
impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_ref())
}
}
impl FromStr for AccountId {
type Err = ErrorReport;
fn from_str(s: &str) -> Result<Self> {
let (hrp, bytes) = bech32::decode(s).wrap_err("failed to decode bech32")?;
if bytes.len() == tendermint::account::LENGTH {
Ok(Self {
bech32: s.to_owned(),
hrp_length: hrp.len(),
})
} else {
Err(Error::AccountId { id: s.to_owned() }).wrap_err_with(|| {
format!(
"account ID should be at least {} bytes long, but was {} bytes long",
tendermint::account::LENGTH,
bytes.len()
)
})
}
}
}
impl From<AccountId> for tendermint::account::Id {
fn from(id: AccountId) -> tendermint::account::Id {
tendermint::account::Id::from(&id)
}
}
impl From<&AccountId> for tendermint::account::Id {
fn from(id: &AccountId) -> tendermint::account::Id {
tendermint::account::Id::new(id.to_bytes())
}
}
impl<'de> Deserialize<'de> for AccountId {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(D::Error::custom)
}
}
impl Serialize for AccountId {
fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.bech32.serialize(serializer)
}
}
/// Coin defines a token with a denomination and an amount.
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Coin {
/// Denomination
pub denom: Denom,
/// Amount
pub amount: Decimal,
}
impl TryFrom<proto::cosmos::base::v1beta1::Coin> for Coin {
type Error = ErrorReport;
fn try_from(proto: proto::cosmos::base::v1beta1::Coin) -> Result<Coin> {
Coin::try_from(&proto)
}
}
impl TryFrom<&proto::cosmos::base::v1beta1::Coin> for Coin {
type Error = ErrorReport;
fn try_from(proto: &proto::cosmos::base::v1beta1::Coin) -> Result<Coin> {
Ok(Coin {
denom: proto.denom.parse()?,
amount: proto.amount.parse()?,
})
}
}
impl From<Coin> for proto::cosmos::base::v1beta1::Coin {
fn from(coin: Coin) -> proto::cosmos::base::v1beta1::Coin {
proto::cosmos::base::v1beta1::Coin::from(&coin)
}
}
impl From<&Coin> for proto::cosmos::base::v1beta1::Coin {
fn from(coin: &Coin) -> proto::cosmos::base::v1beta1::Coin {
proto::cosmos::base::v1beta1::Coin {
denom: coin.denom.to_string(),
amount: coin.amount.to_string(),
}
}
}
/// Denomination.
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Denom(String);
impl AsRef<str> for Denom {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl fmt::Display for Denom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_ref())
}
}
impl FromStr for Denom {
type Err = ErrorReport;
fn from_str(s: &str) -> Result<Self> {
// TODO(tarcieri): ensure this is the proper validation for a denom name
if s.chars().all(|c| matches!(c, 'a'..='z')) {
Ok(Denom(s.to_owned()))
} else {
Err(Error::Denom { name: s.to_owned() }.into())
}
}
}