quai_primitives/
address.rs1use core::{fmt, str::FromStr};
2use tiny_keccak::{Hasher, Keccak};
3
4use crate::{ShardError, Zone};
5
6#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
8#[repr(u8)]
9pub enum Ledger {
10 Quai = 0,
12 Qi = 1,
14}
15
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18#[non_exhaustive]
19pub enum AddressError {
20 InvalidLength,
22 InvalidHex,
24 InvalidChecksum,
26 InvalidZone(ShardError),
28 WrongLedger {
30 expected: Ledger,
32 actual: Ledger,
34 },
35}
36impl fmt::Display for AddressError {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Self::InvalidLength => f.write_str("address must contain exactly 20 bytes"),
40 Self::InvalidHex => f.write_str("address contains non-hexadecimal characters"),
41 Self::InvalidChecksum => f.write_str("invalid mixed-case address checksum"),
42 Self::InvalidZone(error) => error.fmt(f),
43 Self::WrongLedger { expected, actual } => {
44 write!(f, "expected {expected:?} address, found {actual:?}")
45 }
46 }
47 }
48}
49impl std::error::Error for AddressError {
50 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51 match self {
52 Self::InvalidZone(error) => Some(error),
53 _ => None,
54 }
55 }
56}
57
58#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
64pub struct Address([u8; 20]);
65
66impl Address {
67 pub const ZERO: Self = Self([0; 20]);
69
70 pub const fn from_bytes(bytes: [u8; 20]) -> Self {
72 Self(bytes)
73 }
74
75 pub const fn bytes(&self) -> &[u8; 20] {
77 &self.0
78 }
79
80 pub const fn ledger(self) -> Ledger {
82 if self.0[1] & 0x80 == 0 {
83 Ledger::Quai
84 } else {
85 Ledger::Qi
86 }
87 }
88
89 pub const fn zone(self) -> Result<Zone, ShardError> {
91 Zone::from_byte(self.0[0])
92 }
93
94 pub fn to_checksum(self) -> String {
96 self.to_string()
97 }
98
99 pub fn from_checksummed_str(text: &str) -> Result<Self, AddressError> {
104 let address: Self = text.parse()?;
105 if address.to_checksum() != text {
106 return Err(AddressError::InvalidChecksum);
107 }
108 Ok(address)
109 }
110
111 fn checksum_bytes(self) -> [u8; 42] {
112 const HEX: &[u8; 16] = b"0123456789abcdef";
113 let mut output = [0; 42];
114 output[0] = b'0';
115 output[1] = b'x';
116 for (i, byte) in self.0.iter().enumerate() {
117 output[2 + i * 2] = HEX[(byte >> 4) as usize];
118 output[3 + i * 2] = HEX[(byte & 0x0f) as usize];
119 }
120 let mut hash = [0; 32];
121 let mut keccak = Keccak::v256();
122 keccak.update(&output[2..]);
123 keccak.finalize(&mut hash);
124 for i in 0..40 {
125 let nibble = if i % 2 == 0 {
126 hash[i / 2] >> 4
127 } else {
128 hash[i / 2] & 0x0f
129 };
130 if nibble >= 8 {
131 output[i + 2] = output[i + 2].to_ascii_uppercase();
132 }
133 }
134 output
135 }
136}
137
138impl From<[u8; 20]> for Address {
139 fn from(value: [u8; 20]) -> Self {
140 Self::from_bytes(value)
141 }
142}
143impl From<Address> for [u8; 20] {
144 fn from(value: Address) -> Self {
145 value.0
146 }
147}
148impl AsRef<[u8]> for Address {
149 fn as_ref(&self) -> &[u8] {
150 &self.0
151 }
152}
153impl TryFrom<&[u8]> for Address {
154 type Error = AddressError;
155 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
156 let bytes = value.try_into().map_err(|_| AddressError::InvalidLength)?;
157 Ok(Self(bytes))
158 }
159}
160impl fmt::Display for Address {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 let bytes = self.checksum_bytes();
163 let address = core::str::from_utf8(&bytes).map_err(|_| fmt::Error)?;
164 f.write_str(address)
165 }
166}
167impl fmt::Debug for Address {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 fmt::Display::fmt(self, f)
170 }
171}
172impl FromStr for Address {
173 type Err = AddressError;
174 fn from_str(value: &str) -> Result<Self, Self::Err> {
175 let hex = value.strip_prefix("0x").unwrap_or(value).as_bytes();
178 if hex.len() != 40 {
179 return Err(AddressError::InvalidLength);
180 }
181 let mut bytes = [0; 20];
182 let mut has_lower = false;
183 let mut has_upper = false;
184 for (i, digit) in hex.iter().copied().enumerate() {
185 let nibble = match digit {
186 b'0'..=b'9' => digit - b'0',
187 b'a'..=b'f' => {
188 has_lower = true;
189 digit - b'a' + 10
190 }
191 b'A'..=b'F' => {
192 has_upper = true;
193 digit - b'A' + 10
194 }
195 _ => return Err(AddressError::InvalidHex),
196 };
197 bytes[i / 2] |= nibble << if i % 2 == 0 { 4 } else { 0 };
198 }
199 let address = Self(bytes);
200 if has_lower && has_upper && address.checksum_bytes()[2..] != *hex {
201 return Err(AddressError::InvalidChecksum);
202 }
203 Ok(address)
204 }
205}
206
207macro_rules! ledger_address {
208 ($name:ident, $ledger:ident, $doc:literal) => {
209 #[doc = $doc]
210 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
211 pub struct $name {
212 address: Address,
213 zone: Zone,
214 }
215
216 impl $name {
217 pub const fn address(self) -> Address {
219 self.address
220 }
221 pub const fn bytes(&self) -> &[u8; 20] {
223 self.address.bytes()
224 }
225 pub const fn zone(self) -> Zone {
227 self.zone
228 }
229 pub const fn ledger(self) -> Ledger {
231 Ledger::$ledger
232 }
233 }
234 impl TryFrom<Address> for $name {
235 type Error = AddressError;
236 fn try_from(address: Address) -> Result<Self, Self::Error> {
237 let zone = address.zone().map_err(AddressError::InvalidZone)?;
238 let actual = address.ledger();
239 if actual != Ledger::$ledger {
240 return Err(AddressError::WrongLedger {
241 expected: Ledger::$ledger,
242 actual,
243 });
244 }
245 Ok(Self { address, zone })
246 }
247 }
248 impl TryFrom<[u8; 20]> for $name {
249 type Error = AddressError;
250 fn try_from(bytes: [u8; 20]) -> Result<Self, Self::Error> {
251 Address::from_bytes(bytes).try_into()
252 }
253 }
254 impl FromStr for $name {
255 type Err = AddressError;
256 fn from_str(value: &str) -> Result<Self, Self::Err> {
257 value.parse::<Address>()?.try_into()
258 }
259 }
260 impl From<$name> for Address {
261 fn from(value: $name) -> Self {
262 value.address
263 }
264 }
265 impl AsRef<[u8]> for $name {
266 fn as_ref(&self) -> &[u8] {
267 self.address.as_ref()
268 }
269 }
270 impl fmt::Display for $name {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 self.address.fmt(f)
273 }
274 }
275 };
276}
277ledger_address!(
278 QuaiAddress,
279 Quai,
280 "An address with a published zone and the Quai ledger bit."
281);
282ledger_address!(
283 QiAddress,
284 Qi,
285 "An address with a published zone and the Qi ledger bit."
286);