miden_objects/account/account_id/
mod.rs

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
mod id_anchor;
pub use id_anchor::AccountIdAnchor;

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;

pub use id_version::AccountIdVersion;
use miden_crypto::{merkle::LeafIndex, utils::hex_to_bytes};
use vm_core::{
    utils::{ByteReader, Deserializable, Serializable},
    Felt, Word,
};
use vm_processor::{DeserializationError, Digest};

use crate::{errors::AccountIdError, AccountError, ACCOUNT_TREE_DEPTH};

/// 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 and is layed out as follows:
///
/// ```text
/// 1st felt: [random (56 bits) | storage mode (2 bits) | type (2 bits) | version (4 bits)]
/// 2nd felt: [anchor_epoch (16 bits) | random (40 bits) | 8 zero bits]
/// ```
///
/// # Generation
///
/// An `AccountId` is a commitment to a user-generated seed, the code and storage of an account and
/// to a certain hash of an epoch block of the blockchain. An id is generated by picking an epoch
/// block as an anchor - which is why it is also referred to as the anchor block - and creating the
/// account's initial storage and code. Then a random seed is picked and the hash of `(SEED,
/// CODE_COMMITMENT, STORAGE_COMMITMENT, ANCHOR_BLOCK_HASH)` is computed. If the hash's first
/// element has the desired storage mode, account type and version, the computation part of the ID
/// generation is done. If not, another random seed is picked and the process is repeated. The first
/// felt of the ID is then the first element of the hash.
///
/// The suffix of the ID is the second element of the hash. Its upper 16 bits are overwritten
/// with the epoch in which the ID is anchored and the lower 8 bits are zeroed. Thus, the prefix
/// of the ID must derive exactly from the hash, while only part of the suffix is derived from
/// the hash.
///
/// # 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 anchor epoch in the suffix is equal to [`u16::MAX`].
/// - 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 be able to introduce 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 anchor epoch is not important beyond the creation process, so placing it in the second
///       felt is fine. Moreover, all properties of the prefix must be derived from the seed, so
///       they add to the proof of work difficulty. Adding 16 bits of PoW for the epoch would be
///       significant.
/// - The anchor epoch is placed at the most significant end of the suffix. Its value must be less
///   than [`u16::MAX`] so that at least one of the upper 16 bits is always zero. This ensures that
///   the entire suffix is valid even if the remaining bits of the felt are one.
/// - The lower 8 bits of the suffix may be overwritten when the ID is encoded in other layouts such
///   as the [`NoteMetadata`](crate::note::NoteMetadata). In such cases, it can happen that all bits
///   of the encoded suffix would be one, so having the epoch constraint is important.
/// - The ID is dependent on the hash of an epoch block. This is a block whose number is a multiple
///   of 2^[`BlockNumber::EPOCH_LENGTH_EXPONENT`][epoch_len_exp], e.g. `0`, `65536`, `131072`, ...
///   These are the first blocks of epoch 0, 1, 2, ... We call this dependence _anchoring_ because
///   the ID is anchored to that epoch block's hash. Anchoring makes it practically impossible for
///   an attacker to construct a rainbow table of account IDs whose epoch is X, if the block for
///   epoch X has not been constructed yet because its hash is then unknown. Therefore, picking a
///   recent anchor block when generating a new ID makes it extremely unlikely that an attacker can
///   highjack this ID because the hash of that block has only been known for a short period of
///   time.
///     - An ID highjack refers to an attack where a user generates an ID and lets someone else send
///       assets to it. At this point the user has not registered the ID on-chain yet, likely
///       because they need the funds in the asset to pay for their first transaction where the
///       account would be registered. Until the ID is registered on chain, an attacker with a
///       rainbow table who happens to have a seed, code and storage commitment combination that
///       hashes to the user's ID can claim the assets sent to the user's ID. Adding the anchor
///       block hash to ID generation process makes this attack practically impossible.
///
/// [epoch_len_exp]: crate::block::BlockNumber::EPOCH_LENGTH_EXPONENT
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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 [`AccountIdAnchor::block_hash`] from the `anchor` and using the
    /// resulting first and second element of the hash as the prefix and suffix felts of the ID.
    ///
    /// The [`AccountIdAnchor::epoch`] from the `anchor` overwrites part of the suffix.
    ///
    /// Note that the `anchor` must correspond to a valid block in the chain for the ID to be deemed
    /// valid during creation.
    ///
    /// 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,
        anchor: AccountIdAnchor,
        version: AccountIdVersion,
        code_commitment: Digest,
        storage_commitment: Digest,
    ) -> Result<Self, AccountIdError> {
        match version {
            AccountIdVersion::Version0 => {
                AccountIdV0::new(seed, anchor, 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 2 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 and 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 version 0, and the given 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 anchor epoch is set to 0 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`, `storage_commitment` and `anchor_block_hash`.
    ///
    /// 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: Digest,
        storage_commitment: Digest,
        anchor_block_hash: Digest,
    ) -> Result<Word, AccountError> {
        match version {
            AccountIdVersion::Version0 => AccountIdV0::compute_account_seed(
                init_seed,
                account_type,
                storage_mode,
                version,
                code_commitment,
                storage_commitment,
                anchor_block_hash,
            ),
        }
    }

    // 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 an account with this ID is a public account.
    pub fn is_public(&self) -> bool {
        self.storage_mode() == AccountStorageMode::Public
    }

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

    /// Returns the anchor epoch of this account ID.
    ///
    /// This is the epoch to which this ID is anchored. The hash of this epoch block is used in the
    /// generation of the ID.
    pub fn anchor_epoch(&self) -> u16 {
        match self {
            AccountId::V0(account_id) => account_id.anchor_epoch(),
        }
    }

    /// 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(),
        }
    }

    /// 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(),
        }
    }
}

/// Account IDs are used as indexes in the account database, which is a tree of depth 64.
impl From<AccountId> for LeafIndex<ACCOUNT_TREE_DEPTH> {
    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_crypto::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 super::*;
    use crate::testing::account_id::{
        ACCOUNT_ID_FUNGIBLE_FAUCET_ON_CHAIN, ACCOUNT_ID_NON_FUNGIBLE_FAUCET_OFF_CHAIN,
        ACCOUNT_ID_OFF_CHAIN_SENDER, ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN,
        ACCOUNT_ID_REGULAR_ACCOUNT_UPDATABLE_CODE_OFF_CHAIN,
    };

    #[test]
    fn test_account_id_wrapper_conversion_roundtrip() {
        for (idx, account_id) in [
            ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN,
            ACCOUNT_ID_REGULAR_ACCOUNT_UPDATABLE_CODE_OFF_CHAIN,
            ACCOUNT_ID_FUNGIBLE_FAUCET_ON_CHAIN,
            ACCOUNT_ID_NON_FUNGIBLE_FAUCET_OFF_CHAIN,
            ACCOUNT_ID_OFF_CHAIN_SENDER,
        ]
        .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}"
            );
        }
    }
}