aurora-engine-types 3.0.0

Essential types which used in Aurora Engine
Documentation
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Guarantees all properly constructed `AccountId`'s are valid for the NEAR network.
//!
//! Inspired by: `https://github.com/near/nearcore/tree/master/core/account-id`

use crate::{fmt, str, str::FromStr, AsBytes, Box, String, ToString, Vec};
use borsh::{io, BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

pub const MIN_ACCOUNT_ID_LEN: usize = 2;
pub const MAX_ACCOUNT_ID_LEN: usize = 64;

/// Account identifier.
///
/// This guarantees all properly constructed `AccountId`'s are valid for the NEAR network.
#[derive(
    Default, BorshSerialize, Serialize, Eq, Ord, Hash, Clone, Debug, PartialEq, PartialOrd,
)]
pub struct AccountId(Box<str>);

impl AccountId {
    pub fn new(account_id: &str) -> Result<Self, ParseAccountError> {
        Self::validate(account_id)?;
        Ok(Self(account_id.into()))
    }

    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.as_ref().as_bytes()
    }

    pub fn validate(account_id: &str) -> Result<(), ParseAccountError> {
        if account_id.len() < MIN_ACCOUNT_ID_LEN {
            Err(ParseAccountError::TooShort)
        } else if account_id.len() > MAX_ACCOUNT_ID_LEN {
            Err(ParseAccountError::TooLong)
        } else {
            // Adapted from https://github.com/near/near-sdk-rs/blob/fd7d4f82d0dfd15f824a1cf110e552e940ea9073/near-sdk/src/environment/env.rs#L819

            // NOTE: We don't want to use Regex here, because it requires extra time to compile it.
            // The valid account ID regex is /^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/
            // Instead the implementation is based on the previous character checks.

            // We can safely assume that last char was a separator.
            let mut last_char_is_separator = true;

            for c in account_id.bytes() {
                let current_char_is_separator = match c {
                    b'a'..=b'z' | b'0'..=b'9' => false,
                    b'-' | b'_' | b'.' => true,
                    _ => {
                        return Err(ParseAccountError::Invalid);
                    }
                };
                if current_char_is_separator && last_char_is_separator {
                    return Err(ParseAccountError::Invalid);
                }
                last_char_is_separator = current_char_is_separator;
            }

            (!last_char_is_separator)
                .then_some(())
                .ok_or(ParseAccountError::Invalid)
        }
    }

    #[must_use]
    pub fn is_top_level_account_id(&self) -> bool {
        self.0.len() >= MIN_ACCOUNT_ID_LEN
            && self.0.len() <= MAX_ACCOUNT_ID_LEN
            && self.as_ref() != "system"
            && !self.as_ref().contains('.')
    }

    /// Returns true if the `signer_id` can create a direct sub-account with the given account Id.
    #[must_use]
    pub fn is_sub_account_of(&self, parent_account_id: &Self) -> bool {
        if parent_account_id.0.len() >= self.0.len() {
            return false;
        }
        // Will not panic, since valid account id is utf-8 only and the length is checked above.
        // e.g. when `near` creates `aa.near`, it splits into `aa.` and `near`
        let (prefix, suffix) = self.0.split_at(self.0.len() - parent_account_id.0.len());

        prefix.find('.') == Some(prefix.len() - 1) && suffix == parent_account_id.as_ref()
    }
}

impl BorshDeserialize for AccountId {
    fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
        let account: String = BorshDeserialize::deserialize_reader(reader)?;

        // It's for saving backward compatibility.
        if account.is_empty() {
            return Ok(Self::default());
        }

        Self::try_from(account)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
    }
}

impl<'de> Deserialize<'de> for AccountId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
        D::Error: serde::de::Error,
    {
        let account = <String as Deserialize>::deserialize(deserializer)?;
        Self::try_from(account).map_err(serde::de::Error::custom)
    }
}

impl TryFrom<String> for AccountId {
    type Error = ParseAccountError;

    fn try_from(account_id: String) -> Result<Self, Self::Error> {
        let account_id = account_id.into_boxed_str();
        Self::validate(&account_id)?;

        Ok(Self(account_id))
    }
}

impl TryFrom<&[u8]> for AccountId {
    type Error = ParseAccountError;

    fn try_from(account_id: &[u8]) -> Result<Self, Self::Error> {
        let account_id = str::from_utf8(account_id).map_err(|_| ParseAccountError::Invalid)?;
        Self::new(account_id)
    }
}

impl TryFrom<Vec<u8>> for AccountId {
    type Error = ParseAccountError;

    fn try_from(account_id: Vec<u8>) -> Result<Self, Self::Error> {
        String::from_utf8(account_id)
            .map_err(|_| ParseAccountError::Invalid)
            .and_then(Self::try_from)
    }
}

impl FromStr for AccountId {
    type Err = ParseAccountError;

    fn from_str(account_id: &str) -> Result<Self, Self::Err> {
        Self::new(account_id)
    }
}

impl From<AccountId> for String {
    fn from(account_id: AccountId) -> Self {
        account_id.0.into_string()
    }
}

impl fmt::Display for AccountId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<AccountId> for Box<str> {
    fn from(account_id: AccountId) -> Self {
        account_id.0
    }
}

impl From<AccountId> for Vec<u8> {
    fn from(account_id: AccountId) -> Self {
        account_id.0.into_boxed_bytes().into_vec()
    }
}

impl AsBytes for AccountId {
    fn as_bytes(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<T: ?Sized> AsRef<T> for AccountId
where
    Box<str>: AsRef<T>,
{
    fn as_ref(&self) -> &T {
        self.0.as_ref()
    }
}

/// A list of errors that occur when parsing an invalid Account ID.
#[derive(Eq, Hash, Clone, Debug, PartialEq)]
pub enum ParseAccountError {
    TooLong,
    TooShort,
    Invalid,
}

impl AsRef<[u8]> for ParseAccountError {
    fn as_ref(&self) -> &[u8] {
        match self {
            Self::TooLong => b"ERR_ACCOUNT_ID_TO_LONG",
            Self::TooShort => b"ERR_ACCOUNT_ID_TO_SHORT",
            Self::Invalid => b"ERR_ACCOUNT_ID_TO_INVALID",
        }
    }
}

impl fmt::Display for ParseAccountError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = str::from_utf8(self.as_ref()).map_err(|_| fmt::Error)?;
        write!(f, "{msg}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn is_implicit(account_id: &str) -> bool {
        account_id.len() == 64
            && account_id
                .as_bytes()
                .iter()
                .all(|b| matches!(b, b'a'..=b'f' | b'0'..=b'9'))
    }

    pub const OK_ACCOUNT_IDS: [&str; 24] = [
        "aa",
        "a-a",
        "a-aa",
        "100",
        "0o",
        "com",
        "near",
        "bowen",
        "b-o_w_e-n",
        "b.owen",
        "bro.wen",
        "a.ha",
        "a.b-a.ra",
        "system",
        "over.9000",
        "google.com",
        "illia.cheapaccounts.near",
        "0o0ooo00oo00o",
        "alex-skidanov",
        "10-4.8-2",
        "b-o_w_e-n",
        "no_lols",
        "0123456789012345678901234567890123456789012345678901234567890123",
        // Valid, but can't be created
        "near.a",
    ];

    pub const BAD_ACCOUNT_IDS: [&str; 24] = [
        "a",
        "A",
        "Abc",
        "-near",
        "near-",
        "-near-",
        "near.",
        ".near",
        "near@",
        "@near",
        "неар",
        "@@@@@",
        "0__0",
        "0_-_0",
        "0_-_0",
        "..",
        "a..near",
        "nEar",
        "_bowen",
        "hello world",
        "abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz",
        "01234567890123456789012345678901234567890123456789012345678901234",
        // `@` separators are banned now
        "some-complex-address@gmail.com",
        "sub.buy_d1gitz@atata@b0-rg.c_0_m",
    ];

    #[test]
    fn test_is_valid_account_id() {
        for account_id in OK_ACCOUNT_IDS {
            if let Err(err) = AccountId::validate(account_id) {
                panic!("Valid account id {account_id:?} marked invalid: {err}");
            }
        }

        for account_id in BAD_ACCOUNT_IDS {
            assert!(
                AccountId::validate(account_id).is_err(),
                "Valid account id {account_id:?} marked valid"
            );
        }
    }

    #[test]
    fn test_is_valid_top_level_account_id() {
        let ok_top_level_account_ids = &[
            "aa",
            "a-a",
            "a-aa",
            "100",
            "0o",
            "com",
            "near",
            "bowen",
            "b-o_w_e-n",
            "0o0ooo00oo00o",
            "alex-skidanov",
            "b-o_w_e-n",
            "no_lols",
            "0123456789012345678901234567890123456789012345678901234567890123",
        ];
        for account_id in ok_top_level_account_ids {
            assert!(
                account_id
                    .parse::<AccountId>()
                    .is_ok_and(|account_id| account_id.is_top_level_account_id()),
                "Valid top level account id {account_id:?} marked invalid",
            );
        }

        let bad_top_level_account_ids = &[
            "near.a",
            "b.owen",
            "bro.wen",
            "a.ha",
            "a.b-a.ra",
            "some-complex-address@gmail.com",
            "sub.buy_d1gitz@atata@b0-rg.c_0_m",
            "over.9000",
            "google.com",
            "illia.cheapaccounts.near",
            "10-4.8-2",
            "a",
            "A",
            "Abc",
            "-near",
            "near-",
            "-near-",
            "near.",
            ".near",
            "near@",
            "@near",
            "неар",
            "@@@@@",
            "0__0",
            "0_-_0",
            "0_-_0",
            "..",
            "a..near",
            "nEar",
            "_bowen",
            "hello world",
            "abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz",
            "01234567890123456789012345678901234567890123456789012345678901234",
            // Valid regex and length, but reserved
            "system",
        ];
        for account_id in bad_top_level_account_ids {
            assert!(
                !account_id
                    .parse::<AccountId>()
                    .is_ok_and(|account_id| account_id.is_top_level_account_id()),
                "Invalid top level account id {account_id:?} marked valid",
            );
        }
    }

    #[test]
    fn test_is_valid_sub_account_id() {
        let ok_pairs = &[
            ("test", "a.test"),
            ("test-me", "abc.test-me"),
            ("gmail.com", "abc.gmail.com"),
            ("gmail.com", "abc-lol.gmail.com"),
            ("gmail.com", "abc_lol.gmail.com"),
            ("gmail.com", "bro-abc_lol.gmail.com"),
            ("g0", "0g.g0"),
            ("1g", "1g.1g"),
            ("5-3", "4_2.5-3"),
        ];
        for (signer_id, sub_account_id) in ok_pairs {
            assert!(
                matches!(
                    (signer_id.parse::<AccountId>(), sub_account_id.parse::<AccountId>()),
                    (Ok(signer_id), Ok(sub_account_id)) if sub_account_id.is_sub_account_of(&signer_id)
                ),
                "Failed to create sub-account {sub_account_id:?} by account {signer_id:?}",
            );
        }

        let bad_pairs = &[
            ("test", ".test"),
            ("test", "test"),
            ("test", "a1.a.test"),
            ("test", "est"),
            ("test", ""),
            ("test", "st"),
            ("test5", "ббб"),
            ("test", "a-test"),
            ("test", "etest"),
            ("test", "a.etest"),
            ("test", "retest"),
            ("test-me", "abc-.test-me"),
            ("test-me", "Abc.test-me"),
            ("test-me", "-abc.test-me"),
            ("test-me", "a--c.test-me"),
            ("test-me", "a_-c.test-me"),
            ("test-me", "a-_c.test-me"),
            ("test-me", "_abc.test-me"),
            ("test-me", "abc_.test-me"),
            ("test-me", "..test-me"),
            ("test-me", "a..test-me"),
            ("gmail.com", "a.abc@gmail.com"),
            ("gmail.com", ".abc@gmail.com"),
            ("gmail.com", ".abc@gmail@com"),
            ("gmail.com", "abc@gmail@com"),
            ("test", "a@test"),
            ("test_me", "abc@test_me"),
            ("gmail.com", "abc@gmail.com"),
            ("gmail@com", "abc.gmail@com"),
            ("gmail.com", "abc-lol@gmail.com"),
            ("gmail@com", "abc_lol.gmail@com"),
            ("gmail@com", "bro-abc_lol.gmail@com"),
            (
                "gmail.com",
                "123456789012345678901234567890123456789012345678901234567890@gmail.com",
            ),
            (
                "123456789012345678901234567890123456789012345678901234567890",
                "1234567890.123456789012345678901234567890123456789012345678901234567890",
            ),
            ("aa", "ъ@aa"),
            ("aa", "ъ.aa"),
        ];
        for (signer_id, sub_account_id) in bad_pairs {
            assert!(
                !matches!(
                    (signer_id.parse::<AccountId>(), sub_account_id.parse::<AccountId>()),
                    (Ok(signer_id), Ok(sub_account_id)) if sub_account_id.is_sub_account_of(&signer_id)
                ),
                "Invalid sub-account {sub_account_id:?} created by account {signer_id:?}",
            );
        }
    }

    #[test]
    fn test_is_account_id_64_len_hex() {
        let valid_64_len_hex_account_ids = &[
            "0000000000000000000000000000000000000000000000000000000000000000",
            "6174617461746174617461746174617461746174617461746174617461746174",
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            "20782e20662e64666420482123494b6b6c677573646b6c66676a646b6c736667",
        ];
        for valid_account_id in valid_64_len_hex_account_ids {
            assert!(
                matches!(
                    valid_account_id.parse::<AccountId>(),
                    Ok(account_id) if is_implicit(account_id.as_ref())
                ),
                "Account ID {valid_account_id} should be valid 64-len hex",
            );
            assert!(
                is_implicit(valid_account_id),
                "Account ID {valid_account_id} should be valid 64-len hex",
            );
        }

        let invalid_64_len_hex_account_ids = &[
            "000000000000000000000000000000000000000000000000000000000000000",
            "6.74617461746174617461746174617461746174617461746174617461746174",
            "012-456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            "fffff_ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo",
            "00000000000000000000000000000000000000000000000000000000000000",
        ];
        for invalid_account_id in invalid_64_len_hex_account_ids {
            assert!(
                !matches!(
                    invalid_account_id.parse::<AccountId>(),
                    Ok(account_id) if is_implicit(account_id.as_ref())
                ),
                "Account ID {invalid_account_id} should be invalid 64-len hex",
            );
            assert!(
                !is_implicit(invalid_account_id),
                "Account ID {invalid_account_id} should be invalid 64-len hex",
            );
        }
    }

    #[test]
    fn test_json_deserialize_account_id() {
        assert!(serde_json::from_str::<AccountId>(r#""test.near""#).is_ok());
        assert!(serde_json::from_str::<AccountId>(r#""test@.near""#).is_err());
    }
}