ab_core_primitives/
address.rs1use crate::shard::ShardIndex;
4use ab_io_type::metadata::IoTypeMetadataKind;
5use ab_io_type::trivial_type::TrivialType;
6use bech32::primitives::decode::CheckedHrpstring;
7use bech32::{Bech32m, ByteIterExt, Fe32IterExt, Hrp};
8use core::cmp::Ordering;
9use core::mem::MaybeUninit;
10use core::ops::Deref;
11use core::{fmt, ptr};
12use derive_more::Deref;
13
14#[derive(Copy, Clone)]
16pub struct FormattedAddress {
17 buffer:
18 [u8; ShortHrp::MAX_HRP_LENGTH + FormattedAddress::MAX_ENCODING_WITHOUT_HRP_WITH_SEPARATOR],
19 length: usize,
20}
21
22impl fmt::Debug for FormattedAddress {
23 #[inline(always)]
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 self.as_str().fmt(f)
26 }
27}
28
29impl fmt::Display for FormattedAddress {
30 #[inline(always)]
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 self.as_str().fmt(f)
33 }
34}
35
36impl Deref for FormattedAddress {
37 type Target = str;
38
39 #[inline(always)]
40 fn deref(&self) -> &Self::Target {
41 self.as_str()
42 }
43}
44
45impl FormattedAddress {
46 const MAX_ENCODING_WITHOUT_HRP_NO_SEPARATOR: usize = 33;
47 const MAX_ENCODING_WITHOUT_HRP_WITH_SEPARATOR: usize = 39;
48
49 #[inline(always)]
51 pub const fn as_str(&self) -> &str {
52 unsafe { str::from_utf8_unchecked(self.buffer.split_at_unchecked(self.length).0) }
54 }
55}
56
57#[derive(Debug, Copy, Clone, Eq, PartialEq, Deref)]
59pub struct ShortHrp(Hrp);
60
61impl ShortHrp {
62 pub const MAX_HRP_LENGTH: usize = 5;
64 pub const MAINNET: Self = Self(Hrp::parse_unchecked("abc"));
66 pub const TESTNET: Self = Self(Hrp::parse_unchecked("xyz"));
68
69 pub fn new(hrp: Hrp) -> Option<Self> {
74 if hrp.len() > Self::MAX_HRP_LENGTH {
75 return None;
76 }
77
78 Some(Self(hrp))
79 }
80}
81
82#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
91#[repr(C)]
92pub struct Address(u64, u64);
93
94unsafe impl TrivialType for Address {
96 const METADATA: &[u8] = &[IoTypeMetadataKind::Address as u8];
97}
98
99const {
101 let (type_details, _metadata) = IoTypeMetadataKind::type_details(Address::METADATA)
102 .expect("Statically correct metadata; qed");
103 assert!(size_of::<Address>() == type_details.recommended_capacity as usize);
104 assert!(align_of::<Address>() == type_details.alignment.get() as usize);
105}
106
107impl fmt::Debug for Address {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.debug_tuple("Address").field(&u128::from(self)).finish()
110 }
111}
112
113impl PartialEq<&Address> for Address {
114 #[inline(always)]
115 fn eq(&self, other: &&Address) -> bool {
116 self.0 == other.0
117 }
118}
119
120impl PartialEq<Address> for &Address {
121 #[inline(always)]
122 fn eq(&self, other: &Address) -> bool {
123 self.0 == other.0
124 }
125}
126
127impl Ord for Address {
128 #[inline(always)]
129 fn cmp(&self, other: &Address) -> Ordering {
130 u128::from(self).cmp(&u128::from(other))
131 }
132}
133
134impl PartialOrd for Address {
135 #[inline(always)]
136 fn partial_cmp(&self, other: &Address) -> Option<Ordering> {
137 Some(self.cmp(other))
138 }
139}
140
141impl const From<u128> for Address {
142 #[inline(always)]
143 fn from(value: u128) -> Self {
144 let mut result = MaybeUninit::<Self>::uninit();
145 unsafe {
147 result.as_mut_ptr().cast::<u128>().write_unaligned(value);
148 result.assume_init()
149 }
150 }
151}
152
153impl const From<&Address> for u128 {
154 #[inline(always)]
155 fn from(value: &Address) -> Self {
156 unsafe { ptr::from_ref(value).cast::<u128>().read_unaligned() }
158 }
159}
160
161impl const From<Address> for u128 {
162 #[inline(always)]
163 fn from(value: Address) -> Self {
164 Self::from(&value)
165 }
166}
167impl Address {
170 pub const NULL: Self = Self::from(0);
173 pub const SYSTEM_CODE: Self = Self::from(1);
175 pub const SYSTEM_BLOCK: Self = Self::from(2);
177 pub const SYSTEM_STATE: Self = Self::from(3);
179 pub const SYSTEM_NATIVE_TOKEN: Self = Self::from(4);
181 pub const SYSTEM_SIMPLE_WALLET_BASE: Self = Self::from(10);
183
184 const FORMAT_SEPARATOR_INTERVAL: [usize; 7] = [
186 1 + 4,
188 4,
189 3,
190 4,
191 4,
192 3,
193 4,
194 ];
195 const FORMAT_SEPARATOR: u8 = b'-';
196 const FORMAT_ALL_ZEROES: u8 = b'q';
197 const FORMAT_CHECKSUM_LENGTH: usize = 6;
198
199 pub fn parse(s: &str) -> Option<(ShortHrp, Self)> {
203 let (hrp, other) = s.split_once('1')?;
204 if hrp.len() > ShortHrp::MAX_HRP_LENGTH {
205 return None;
206 }
207
208 let mut scratch = FormattedAddress {
209 buffer: [Self::FORMAT_ALL_ZEROES; _],
210 length: 0,
211 };
212
213 scratch.buffer[..hrp.len() + 1].copy_from_slice(&s.as_bytes()[..hrp.len() + 1]);
215 scratch.length = hrp.len() + FormattedAddress::MAX_ENCODING_WITHOUT_HRP_NO_SEPARATOR;
217
218 let mut chunks = other.rsplit(char::from(Self::FORMAT_SEPARATOR));
219 {
221 let checksum = chunks.next()?;
222
223 if checksum.len() != Self::FORMAT_CHECKSUM_LENGTH {
224 return None;
225 }
226 scratch.buffer[..scratch.length][scratch.length - Self::FORMAT_CHECKSUM_LENGTH..]
227 .copy_from_slice(checksum.as_bytes());
228 }
229
230 {
231 let mut buffer = &mut scratch.buffer[..scratch.length - Self::FORMAT_CHECKSUM_LENGTH];
232 let mut iterator = chunks
233 .zip(Self::FORMAT_SEPARATOR_INTERVAL.into_iter().rev())
234 .peekable();
235 while let Some((chunk, max_chunk_length)) = iterator.next() {
236 let chunk = chunk.as_bytes();
237
238 if iterator.peek().is_none() {
239 buffer[hrp.len() + 1..][..chunk.len()].copy_from_slice(chunk);
241 break;
242 }
243
244 if chunk.len() > max_chunk_length {
245 return None;
246 }
247
248 let target_chunk;
249 (buffer, target_chunk) = buffer.split_at_mut(buffer.len() - max_chunk_length);
250
251 target_chunk[max_chunk_length - chunk.len()..].copy_from_slice(chunk);
252 }
253 }
254
255 let checked_hrp_string = CheckedHrpstring::new::<Bech32m>(&scratch).ok()?;
256 let short_hrp = ShortHrp::new(checked_hrp_string.hrp())?;
257
258 let mut address_bytes = 0u128.to_be_bytes();
259 {
261 let mut address_bytes = address_bytes.as_mut_slice();
262 for byte in checked_hrp_string.byte_iter() {
263 if address_bytes.is_empty() {
264 return None;
265 }
266
267 address_bytes[0] = byte;
268
269 address_bytes = &mut address_bytes[1..];
270 }
271
272 if !address_bytes.is_empty() {
273 return None;
274 }
275 }
276 let address = Address::from(u128::from_be_bytes(address_bytes));
277
278 Some((short_hrp, address))
279 }
280
281 #[inline]
283 pub fn format(&self, hrp: &ShortHrp) -> FormattedAddress {
284 let mut scratch = FormattedAddress {
285 buffer: [0; _],
286 length: 0,
287 };
288
289 for char in u128::from(self)
290 .to_be_bytes()
291 .into_iter()
292 .bytes_to_fes()
293 .with_checksum::<Bech32m>(hrp)
294 .bytes()
295 {
296 scratch.buffer[scratch.length] = char;
297 scratch.length += 1;
298 }
299
300 let (prefix_with_shard, other) = scratch
301 .as_str()
302 .split_at(hrp.len() + Self::FORMAT_SEPARATOR_INTERVAL[0]);
303 let (mut address_within_shard, checksum) =
304 other.split_at(Self::FORMAT_SEPARATOR_INTERVAL[1..].iter().sum());
305
306 let mut formatted_address = FormattedAddress {
307 buffer: [0; _],
308 length: 0,
309 };
310
311 {
313 let prefix_with_shard = prefix_with_shard
314 .trim_end_matches(char::from(Self::FORMAT_ALL_ZEROES))
315 .as_bytes();
316
317 formatted_address.buffer[..prefix_with_shard.len()].copy_from_slice(prefix_with_shard);
318 formatted_address.length = prefix_with_shard.len();
319
320 formatted_address.buffer[prefix_with_shard.len()] = Self::FORMAT_SEPARATOR;
321 formatted_address.length += 1;
322 }
323 {
325 let mut finished_trimming = false;
326
327 for &chunk_size in Self::FORMAT_SEPARATOR_INTERVAL[1..].iter() {
328 let mut chunk;
329 (chunk, address_within_shard) = address_within_shard.split_at(chunk_size);
330
331 if !finished_trimming {
332 chunk = chunk.trim_start_matches(char::from(Self::FORMAT_ALL_ZEROES));
333
334 if chunk.is_empty() {
335 continue;
336 }
337
338 finished_trimming = true;
339 }
340
341 formatted_address.buffer[formatted_address.length..][..chunk.len()]
342 .copy_from_slice(chunk.as_bytes());
343 formatted_address.length += chunk.len();
344
345 formatted_address.buffer[formatted_address.length] = Self::FORMAT_SEPARATOR;
346 formatted_address.length += 1;
347 }
348 }
349 {
351 formatted_address.buffer[formatted_address.length..][..checksum.len()]
352 .copy_from_slice(checksum.as_bytes());
353 formatted_address.length += checksum.len();
354 }
355
356 formatted_address
357 }
358
359 #[inline(always)]
361 pub const fn system_address_allocator(shard_index: ShardIndex) -> Self {
362 Self::from(u128::from(u32::from(shard_index)).reverse_bits())
366 }
367}