miden-objects 0.12.4

Core components of the Miden protocol
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
pub(crate) mod v0;
pub use v0::{AccountIdPrefixV0, AccountIdV0};

mod id_prefix;
pub use id_prefix::AccountIdPrefix;

mod seed;

mod account_type;
pub use account_type::AccountType;

mod storage_mode;
pub use storage_mode::AccountStorageMode;

mod id_version;
use alloc::string::{String, ToString};
use core::fmt;

use bech32::primitives::decode::ByteIter;
pub use id_version::AccountIdVersion;
use miden_core::Felt;
use miden_core::utils::{ByteReader, Deserializable, Serializable};
use miden_crypto::utils::hex_to_bytes;
use miden_processor::DeserializationError;

use crate::address::NetworkId;
use crate::errors::AccountIdError;
use crate::{AccountError, Word};

/// The identifier of an [`Account`](crate::account::Account).
///
/// This enum is a wrapper around concrete versions of IDs. The following documents version 0.
///
/// # Layout
///
/// An `AccountId` consists of two field elements, where the first is called the prefix and the
/// second is called the suffix. It is laid out as follows:
///
/// ```text
/// prefix: [hash (56 bits) | storage mode (2 bits) | type (2 bits) | version (4 bits)]
/// suffix: [zero bit | hash (55 bits) | 8 zero bits]
/// ```
///
/// # Generation
///
/// An `AccountId` is a commitment to a user-generated seed and the code and storage of an account.
/// An id is generated by first creating the account's initial storage and code. Then a random seed
/// is picked and the hash of `(SEED, CODE_COMMITMENT, STORAGE_COMMITMENT, EMPTY_WORD)` is computed.
/// This process is repeated until the hash's first element has the desired storage mode, account
/// type and version and the suffix' most significant bit is zero.
///
/// The prefix of the ID is exactly the first element of the hash. The suffix of the ID is the
/// second element of the hash, but its lower 8 bits are zeroed. Thus, the prefix of the ID must
/// derive exactly from the hash, while only the first 56 bits of the suffix are derived from the
/// hash.
///
/// In total, due to requiring specific bits for storage mode, type, version and the most
/// significant bit in the suffix, generating an ID requires 9 bits of Proof-of-Work.
///
/// # Constraints
///
/// Constructors will return an error if:
///
/// - The prefix contains account ID metadata (storage mode, type or version) that does not match
///   any of the known values.
/// - The most significant bit of the suffix is not zero.
/// - The lower 8 bits of the suffix are not zero, although [`AccountId::new`] ensures this is the
///   case rather than return an error.
///
/// # Design Rationale
///
/// The rationale behind the above layout is as follows.
///
/// - The prefix is the output of a hash function so it will be a valid field element without
///   requiring additional constraints.
/// - The version is placed at a static offset such that future ID versions which may change the
///   number of type or storage mode bits will not cause the version to be at a different offset.
///   This is important so that a parser can always reliably read the version and then parse the
///   remainder of the ID depending on the version. Having only 4 bits for the version is a trade
///   off between future proofing to allow introducing more versions and the version requiring Proof
///   of Work as part of the ID generation.
/// - The version, type and storage mode are part of the prefix which is included in the
///   representation of a non-fungible asset. The prefix alone is enough to determine all of these
///   properties about the ID.
/// - The most significant bit of the suffix must be zero to ensure the value of the suffix is
///   always a valid felt, even if the lower 8 bits are all set to `1`. The lower 8 bits of the
///   suffix may be overwritten when the ID is embedded in other layouts such as the
///   [`NoteMetadata`](crate::note::NoteMetadata). In that case, it can happen that all lower bits
///   of the encoded suffix are one, so having the zero bit constraint is important for validity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AccountId {
    V0(AccountIdV0),
}

impl AccountId {
    // CONSTANTS
    // --------------------------------------------------------------------------------------------

    /// The serialized size of an [`AccountId`] in bytes.
    pub const SERIALIZED_SIZE: usize = 15;

    // CONSTRUCTORS
    // --------------------------------------------------------------------------------------------

    /// Creates an [`AccountId`] by hashing the given `seed`, `code_commitment`,
    /// `storage_commitment` and using the resulting first and second element of the hash as the
    /// prefix and suffix felts of the ID.
    ///
    /// See the documentation of the [`AccountId`] for more details on the generation.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the ID constraints are not met. See the [constraints
    /// documentation](AccountId#constraints) for details.
    pub fn new(
        seed: Word,
        version: AccountIdVersion,
        code_commitment: Word,
        storage_commitment: Word,
    ) -> Result<Self, AccountIdError> {
        match version {
            AccountIdVersion::Version0 => {
                AccountIdV0::new(seed, code_commitment, storage_commitment).map(Self::V0)
            },
        }
    }

    /// Creates an [`AccountId`] from the given felts where the felt at index 0 is the prefix
    /// and the felt at index 1 is the suffix.
    ///
    /// # Warning
    ///
    /// Validity of the ID must be ensured by the caller. An invalid ID may lead to panics.
    ///
    /// # Panics
    ///
    /// Panics if the prefix does not contain a known account ID version.
    ///
    /// If debug_assertions are enabled (e.g. in debug mode), this function panics if any of the ID
    /// constraints are not met. See the [constraints documentation](AccountId#constraints) for
    /// details.
    pub fn new_unchecked(elements: [Felt; 2]) -> Self {
        // The prefix contains the metadata.
        // If we add more versions in the future, we may need to generalize this.
        match v0::extract_version(elements[0].as_int())
            .expect("prefix should contain a valid account ID version")
        {
            AccountIdVersion::Version0 => Self::V0(AccountIdV0::new_unchecked(elements)),
        }
    }

    /// Constructs an [`AccountId`] for testing purposes with the given account type, storage
    /// mode.
    ///
    /// This function does the following:
    /// - Split the given bytes into a `prefix = bytes[0..8]` and `suffix = bytes[8..]` part to be
    ///   used for the prefix and suffix felts, respectively.
    /// - The least significant byte of the prefix is set to the given version, type and storage
    ///   mode.
    /// - The 32nd most significant bit in the prefix is cleared to ensure it is a valid felt. The
    ///   32nd is chosen as it is the lowest bit that we can clear and still ensure felt validity.
    ///   This leaves the upper 31 bits to be set by the input `bytes` which makes it simpler to
    ///   create test values which more often need specific values for the most significant end of
    ///   the ID.
    /// - In the suffix the most significant bit and the lower 8 bits are cleared.
    #[cfg(any(feature = "testing", test))]
    pub fn dummy(
        bytes: [u8; 15],
        version: AccountIdVersion,
        account_type: AccountType,
        storage_mode: AccountStorageMode,
    ) -> AccountId {
        match version {
            AccountIdVersion::Version0 => {
                Self::V0(AccountIdV0::dummy(bytes, account_type, storage_mode))
            },
        }
    }

    /// Grinds an account seed until its hash matches the given `account_type`, `storage_mode` and
    /// `version` and returns it as a [`Word`]. The input to the hash function next to the seed are
    /// the `code_commitment` and `storage_commitment`.
    ///
    /// The grinding process is started from the given `init_seed` which should be a random seed
    /// generated from a cryptographically secure source.
    pub fn compute_account_seed(
        init_seed: [u8; 32],
        account_type: AccountType,
        storage_mode: AccountStorageMode,
        version: AccountIdVersion,
        code_commitment: Word,
        storage_commitment: Word,
    ) -> Result<Word, AccountError> {
        match version {
            AccountIdVersion::Version0 => AccountIdV0::compute_account_seed(
                init_seed,
                account_type,
                storage_mode,
                version,
                code_commitment,
                storage_commitment,
            ),
        }
    }

    // PUBLIC ACCESSORS
    // --------------------------------------------------------------------------------------------

    /// Returns the type of this account ID.
    pub const fn account_type(&self) -> AccountType {
        match self {
            AccountId::V0(account_id) => account_id.account_type(),
        }
    }

    /// Returns `true` if an account with this ID is a faucet which can issue assets.
    pub fn is_faucet(&self) -> bool {
        self.account_type().is_faucet()
    }

    /// Returns `true` if an account with this ID is a regular account.
    pub fn is_regular_account(&self) -> bool {
        self.account_type().is_regular_account()
    }

    /// Returns the storage mode of this account ID.
    pub fn storage_mode(&self) -> AccountStorageMode {
        match self {
            AccountId::V0(account_id) => account_id.storage_mode(),
        }
    }

    /// Returns `true` if the full state of the account is public on chain, i.e. if the modes are
    /// [`AccountStorageMode::Public`] or [`AccountStorageMode::Network`], `false` otherwise.
    pub fn has_public_state(&self) -> bool {
        self.storage_mode().has_public_state()
    }

    /// Returns `true` if the storage mode is [`AccountStorageMode::Public`], `false` otherwise.
    pub fn is_public(&self) -> bool {
        self.storage_mode().is_public()
    }

    /// Returns `true` if the storage mode is [`AccountStorageMode::Network`], `false` otherwise.
    pub fn is_network(&self) -> bool {
        self.storage_mode().is_network()
    }

    /// Returns `true` if the storage mode is [`AccountStorageMode::Private`], `false` otherwise.
    pub fn is_private(&self) -> bool {
        self.storage_mode().is_private()
    }

    /// Returns the version of this account ID.
    pub fn version(&self) -> AccountIdVersion {
        match self {
            AccountId::V0(_) => AccountIdVersion::Version0,
        }
    }

    /// Creates an [`AccountId`] from a hex string. Assumes the string starts with "0x" and
    /// that the hexadecimal characters are big-endian encoded.
    pub fn from_hex(hex_str: &str) -> Result<Self, AccountIdError> {
        hex_to_bytes(hex_str)
            .map_err(AccountIdError::AccountIdHexParseError)
            .and_then(AccountId::try_from)
    }

    /// Returns a big-endian, hex-encoded string of length 32, including the `0x` prefix. This means
    /// it encodes 15 bytes.
    pub fn to_hex(self) -> String {
        match self {
            AccountId::V0(account_id) => account_id.to_hex(),
        }
    }

    /// Encodes the [`AccountId`] into a [bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
    /// string.
    ///
    /// # Encoding
    ///
    /// The encoding of an account ID into bech32 is done as follows:
    /// - Convert the account ID into its `[u8; 15]` data format.
    /// - Insert the address type `AddressType::AccountId` byte at index 0, shifting all other
    ///   elements to the right.
    /// - Choose an HRP, defined as a [`NetworkId`], for example [`NetworkId::Mainnet`] whose string
    ///   representation is `mm`.
    /// - Encode the resulting HRP together with the data into a bech32 string using the
    ///   [`bech32::Bech32m`] checksum algorithm.
    ///
    /// This is an example of an account ID in hex and bech32 representations:
    ///
    /// ```text
    /// hex:    0x6d449e4034fadca075d1976fef7e38
    /// bech32: mm1apk5f8jqxnadegr46xtklmm78qhdgkwc
    /// ```
    ///
    /// ## Rationale
    ///
    /// Having the address type at the very beginning is so that it can be decoded to detect the
    /// type of the address without having to decode the entire data. Moreover, choosing the
    /// address type as a multiple of 8 means the first character of the bech32 string after the
    /// `1` separator will be different for every address type. This makes the type of the address
    /// conveniently human-readable.
    pub fn to_bech32(&self, network_id: NetworkId) -> String {
        match self {
            AccountId::V0(account_id_v0) => account_id_v0.to_bech32(network_id),
        }
    }

    /// Decodes a [bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) string into an [`AccountId`].
    ///
    /// See [`AccountId::to_bech32`] for details on the format. The procedure for decoding the
    /// bech32 data into the ID consists of the inverse operations of encoding.
    pub fn from_bech32(bech32_string: &str) -> Result<(NetworkId, Self), AccountIdError> {
        AccountIdV0::from_bech32(bech32_string)
            .map(|(network_id, account_id)| (network_id, AccountId::V0(account_id)))
    }

    /// Decodes the data from the bech32 byte iterator into an [`AccountId`].
    pub(crate) fn from_bech32_byte_iter(byte_iter: ByteIter<'_>) -> Result<Self, AccountIdError> {
        AccountIdV0::from_bech32_byte_iter(byte_iter).map(AccountId::V0)
    }

    /// Returns the [`AccountIdPrefix`] of this ID.
    ///
    /// The prefix of an account ID is guaranteed to be unique.
    pub fn prefix(&self) -> AccountIdPrefix {
        match self {
            AccountId::V0(account_id) => AccountIdPrefix::V0(account_id.prefix()),
        }
    }

    /// Returns the suffix of this ID as a [`Felt`].
    pub const fn suffix(&self) -> Felt {
        match self {
            AccountId::V0(account_id) => account_id.suffix(),
        }
    }
}

// CONVERSIONS FROM ACCOUNT ID
// ================================================================================================

impl From<AccountId> for [Felt; 2] {
    fn from(id: AccountId) -> Self {
        match id {
            AccountId::V0(account_id) => account_id.into(),
        }
    }
}

impl From<AccountId> for [u8; 15] {
    fn from(id: AccountId) -> Self {
        match id {
            AccountId::V0(account_id) => account_id.into(),
        }
    }
}

impl From<AccountId> for u128 {
    fn from(id: AccountId) -> Self {
        match id {
            AccountId::V0(account_id) => account_id.into(),
        }
    }
}

// CONVERSIONS TO ACCOUNT ID
// ================================================================================================

impl From<AccountIdV0> for AccountId {
    fn from(id: AccountIdV0) -> Self {
        Self::V0(id)
    }
}

impl TryFrom<[Felt; 2]> for AccountId {
    type Error = AccountIdError;

    /// Returns an [`AccountId`] instantiated with the provided field elements where `elements[0]`
    /// is taken as the prefix and `elements[1]` is taken as the suffix.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the ID constraints are not met. See the [constraints
    /// documentation](AccountId#constraints) for details.
    fn try_from(elements: [Felt; 2]) -> Result<Self, Self::Error> {
        // The prefix contains the metadata.
        // If we add more versions in the future, we may need to generalize this.
        match v0::extract_version(elements[0].as_int())? {
            AccountIdVersion::Version0 => AccountIdV0::try_from(elements).map(Self::V0),
        }
    }
}

impl TryFrom<[u8; 15]> for AccountId {
    type Error = AccountIdError;

    /// Tries to convert a byte array in big-endian order to an [`AccountId`].
    ///
    /// # Errors
    ///
    /// Returns an error if any of the ID constraints are not met. See the [constraints
    /// documentation](AccountId#constraints) for details.
    fn try_from(bytes: [u8; 15]) -> Result<Self, Self::Error> {
        // The least significant byte of the ID prefix contains the metadata.
        let metadata_byte = bytes[7];
        // We only have one supported version for now, so we use the extractor from that version.
        // If we add more versions in the future, we may need to generalize this.
        let version = v0::extract_version(metadata_byte as u64)?;

        match version {
            AccountIdVersion::Version0 => AccountIdV0::try_from(bytes).map(Self::V0),
        }
    }
}

impl TryFrom<u128> for AccountId {
    type Error = AccountIdError;

    /// Tries to convert a u128 into an [`AccountId`].
    ///
    /// # Errors
    ///
    /// Returns an error if any of the ID constraints are not met. See the [constraints
    /// documentation](AccountId#constraints) for details.
    fn try_from(int: u128) -> Result<Self, Self::Error> {
        let mut bytes: [u8; 15] = [0; 15];
        bytes.copy_from_slice(&int.to_be_bytes()[0..15]);

        Self::try_from(bytes)
    }
}

// COMMON TRAIT IMPLS
// ================================================================================================

impl PartialOrd for AccountId {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AccountId {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        u128::from(*self).cmp(&u128::from(*other))
    }
}

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

// SERIALIZATION
// ================================================================================================

impl Serializable for AccountId {
    fn write_into<W: miden_core::utils::ByteWriter>(&self, target: &mut W) {
        match self {
            AccountId::V0(account_id) => {
                account_id.write_into(target);
            },
        }
    }

    fn get_size_hint(&self) -> usize {
        match self {
            AccountId::V0(account_id) => account_id.get_size_hint(),
        }
    }
}

impl Deserializable for AccountId {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        <[u8; 15]>::read_from(source)?
            .try_into()
            .map_err(|err: AccountIdError| DeserializationError::InvalidValue(err.to_string()))
    }
}

// TESTS
// ================================================================================================

#[cfg(test)]
mod tests {
    use alloc::boxed::Box;

    use assert_matches::assert_matches;
    use bech32::{Bech32, Bech32m, NoChecksum};

    use super::*;
    use crate::account::account_id::v0::{extract_storage_mode, extract_type, extract_version};
    use crate::address::{AddressType, CustomNetworkId};
    use crate::errors::Bech32Error;
    use crate::testing::account_id::{
        ACCOUNT_ID_NETWORK_NON_FUNGIBLE_FAUCET,
        ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
        ACCOUNT_ID_PRIVATE_SENDER,
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
        ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
        AccountIdBuilder,
    };

    #[test]
    fn test_account_id_wrapper_conversion_roundtrip() {
        for (idx, account_id) in [
            ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
            ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
            ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
            ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
            ACCOUNT_ID_PRIVATE_SENDER,
            ACCOUNT_ID_NETWORK_NON_FUNGIBLE_FAUCET,
        ]
        .into_iter()
        .enumerate()
        {
            let wrapper = AccountId::try_from(account_id).unwrap();
            assert_eq!(
                wrapper,
                AccountId::read_from_bytes(&wrapper.to_bytes()).unwrap(),
                "failed in {idx}"
            );
        }
    }

    #[test]
    fn bech32_encode_decode_roundtrip() -> anyhow::Result<()> {
        // We use this to check that encoding does not panic even when using the longest possible
        // HRP.
        let longest_possible_hrp =
            "01234567890123456789012345678901234567890123456789012345678901234567890123456789012";
        assert_eq!(longest_possible_hrp.len(), 83);

        let random_id = AccountIdBuilder::new().build_with_rng(&mut rand::rng());

        for network_id in [
            NetworkId::Mainnet,
            NetworkId::Custom(Box::new("custom".parse::<CustomNetworkId>()?)),
            NetworkId::Custom(Box::new(longest_possible_hrp.parse::<CustomNetworkId>()?)),
        ] {
            for account_id in [
                ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
                ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
                ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
                ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
                ACCOUNT_ID_PRIVATE_SENDER,
                random_id.into(),
            ]
            .into_iter()
            {
                let account_id = AccountId::try_from(account_id).unwrap();

                let bech32_string = account_id.to_bech32(network_id.clone());
                let (decoded_network_id, decoded_account_id) =
                    AccountId::from_bech32(&bech32_string).unwrap();

                assert_eq!(network_id, decoded_network_id, "network id failed for {account_id}",);
                assert_eq!(account_id, decoded_account_id, "account id failed for {account_id}");

                let (_, data) = bech32::decode(&bech32_string).unwrap();

                // Raw bech32 data should contain the address type as the first byte.
                assert_eq!(data[0], AddressType::AccountId as u8);

                // Raw bech32 data should contain the metadata byte at index 8.
                assert_eq!(extract_version(data[8] as u64).unwrap(), account_id.version());
                assert_eq!(extract_type(data[8] as u64), account_id.account_type());
                assert_eq!(
                    extract_storage_mode(data[8] as u64).unwrap(),
                    account_id.storage_mode()
                );
            }
        }

        Ok(())
    }

    #[test]
    fn bech32_invalid_checksum() {
        let network_id = NetworkId::Mainnet;
        let account_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();

        let bech32_string = account_id.to_bech32(network_id);
        let mut invalid_bech32_1 = bech32_string.clone();
        invalid_bech32_1.remove(0);
        let mut invalid_bech32_2 = bech32_string.clone();
        invalid_bech32_2.remove(7);

        let error = AccountId::from_bech32(&invalid_bech32_1).unwrap_err();
        assert_matches!(error, AccountIdError::Bech32DecodeError(Bech32Error::DecodeError(_)));

        let error = AccountId::from_bech32(&invalid_bech32_2).unwrap_err();
        assert_matches!(error, AccountIdError::Bech32DecodeError(Bech32Error::DecodeError(_)));
    }

    #[test]
    fn bech32_invalid_address_type() {
        let account_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();
        let mut id_bytes = account_id.to_bytes();

        // Set invalid address type.
        id_bytes.insert(0, 16);

        let invalid_bech32 =
            bech32::encode::<Bech32m>(NetworkId::Mainnet.into_hrp(), &id_bytes).unwrap();

        let error = AccountId::from_bech32(&invalid_bech32).unwrap_err();
        assert_matches!(
            error,
            AccountIdError::Bech32DecodeError(Bech32Error::UnknownAddressType(16))
        );
    }

    #[test]
    fn bech32_invalid_other_checksum() {
        let account_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();
        let mut id_bytes = account_id.to_bytes();
        id_bytes.insert(0, AddressType::AccountId as u8);

        // Use Bech32 instead of Bech32m which is disallowed.
        let invalid_bech32_regular =
            bech32::encode::<Bech32>(NetworkId::Mainnet.into_hrp(), &id_bytes).unwrap();
        let error = AccountId::from_bech32(&invalid_bech32_regular).unwrap_err();
        assert_matches!(error, AccountIdError::Bech32DecodeError(Bech32Error::DecodeError(_)));

        // Use no checksum instead of Bech32m which is disallowed.
        let invalid_bech32_no_checksum =
            bech32::encode::<NoChecksum>(NetworkId::Mainnet.into_hrp(), &id_bytes).unwrap();
        let error = AccountId::from_bech32(&invalid_bech32_no_checksum).unwrap_err();
        assert_matches!(error, AccountIdError::Bech32DecodeError(Bech32Error::DecodeError(_)));
    }

    #[test]
    fn bech32_invalid_length() {
        let account_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();
        let mut id_bytes = account_id.to_bytes();
        id_bytes.insert(0, AddressType::AccountId as u8);
        // Add one byte to make the length invalid.
        id_bytes.push(5);

        let invalid_bech32 =
            bech32::encode::<Bech32m>(NetworkId::Mainnet.into_hrp(), &id_bytes).unwrap();

        let error = AccountId::from_bech32(&invalid_bech32).unwrap_err();
        assert_matches!(
            error,
            AccountIdError::Bech32DecodeError(Bech32Error::InvalidDataLength { .. })
        );
    }
}