Skip to main content

quai_primitives/
address.rs

1use core::{fmt, str::FromStr};
2use tiny_keccak::{Hasher, Keccak};
3
4use crate::{ShardError, Zone};
5
6/// The ledger selected by the high bit of an address's second byte.
7#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
8#[repr(u8)]
9pub enum Ledger {
10    /// Account-based Quai ledger.
11    Quai = 0,
12    /// UTXO-based Qi ledger.
13    Qi = 1,
14}
15
16/// Failure to parse an address or validate its ledger and zone.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18#[non_exhaustive]
19pub enum AddressError {
20    /// Address strings must contain exactly 40 hex digits after an optional `0x`.
21    InvalidLength,
22    /// Only ASCII hexadecimal characters are accepted.
23    InvalidHex,
24    /// A mixed-case input fails the Keccak capitalization checksum.
25    InvalidChecksum,
26    /// The address does not encode a published zone.
27    InvalidZone(ShardError),
28    /// The typed address requires a different ledger.
29    WrongLedger {
30        /// Ledger required by the requested address type.
31        expected: Ledger,
32        /// Ledger encoded in the address.
33        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/// An arbitrary 20-byte address with validated string parsing.
59///
60/// Parsing validates syntax and checksums, matching `quais.js` `getAddress`.
61/// It does not require a known zone. Use [`QuaiAddress`] or [`QiAddress`] when
62/// accepting a ledger-specific destination, or call [`Address::zone`] explicitly.
63#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
64pub struct Address([u8; 20]);
65
66impl Address {
67    /// The all-zero address. Applications must decide whether it is a valid destination.
68    pub const ZERO: Self = Self([0; 20]);
69
70    /// Construct from an exact-size byte array. No zone or ledger is implied.
71    pub const fn from_bytes(bytes: [u8; 20]) -> Self {
72        Self(bytes)
73    }
74
75    /// Borrow the underlying bytes.
76    pub const fn bytes(&self) -> &[u8; 20] {
77        &self.0
78    }
79
80    /// Return the ledger encoded by bit 7 of byte 1.
81    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    /// Decode the first byte as a published zone, rejecting unknown values.
90    pub const fn zone(self) -> Result<Zone, ShardError> {
91        Zone::from_byte(self.0[0])
92    }
93
94    /// Format as a `0x`-prefixed mixed-case Keccak checksum address.
95    pub fn to_checksum(self) -> String {
96        self.to_string()
97    }
98
99    /// Parse only the exact `0x`-prefixed checksum spelling, matching the pinned
100    /// `validateAddress` policy. Ordinary `FromStr` also accepts uniform case and
101    /// an omitted prefix; this explicit strict import rejects those spellings
102    /// whenever they differ from the canonical checksum string.
103    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        // Deliberately do not accept `0X` or trim whitespace: pinned quais.js
176        // requires an optional lowercase prefix and exactly 40 hex digits.
177        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            /// The checked ledger-independent address.
218            pub const fn address(self) -> Address {
219                self.address
220            }
221            /// Borrow the underlying bytes.
222            pub const fn bytes(&self) -> &[u8; 20] {
223                self.address.bytes()
224            }
225            /// The validated zone. This does not imply network activation.
226            pub const fn zone(self) -> Zone {
227                self.zone
228            }
229            /// The ledger enforced by this address type.
230            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);