miden_objects/account/account_id/v0/
prefix.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
use alloc::string::{String, ToString};
use core::fmt;

use miden_crypto::utils::ByteWriter;
use vm_core::{
    utils::{ByteReader, Deserializable, Serializable},
    Felt,
};
use vm_processor::DeserializationError;

use crate::{
    account::{
        account_id::v0::{self, validate_prefix},
        AccountIdVersion, AccountStorageMode, AccountType,
    },
    errors::AccountIdError,
};

// ACCOUNT ID PREFIX VERSION 0
// ================================================================================================

/// The prefix of an [`AccountIdV0`](crate::account::AccountIdV0), i.e. its first field element.
///
/// See the [`AccountId`](crate::account::AccountId)'s documentation for details.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct AccountIdPrefixV0 {
    prefix: Felt,
}

impl AccountIdPrefixV0 {
    // CONSTANTS
    // --------------------------------------------------------------------------------------------

    /// The serialized size of an [`AccountIdPrefixV0`] in bytes.
    const SERIALIZED_SIZE: usize = 8;

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

    /// See [`AccountIdPrefix::new_unchecked`](crate::account::AccountIdPrefix::new_unchecked) for
    /// details.
    pub fn new_unchecked(prefix: Felt) -> Self {
        // Panic on invalid felts in debug mode.
        if cfg!(debug_assertions) {
            validate_prefix(prefix)
                .expect("AccountIdPrefix::new_unchecked called with invalid prefix");
        }

        AccountIdPrefixV0 { prefix }
    }

    /// See [`AccountIdPrefix::new`](crate::account::AccountIdPrefix::new) for details.
    pub fn new(prefix: Felt) -> Result<Self, AccountIdError> {
        validate_prefix(prefix)?;

        Ok(AccountIdPrefixV0 { prefix })
    }

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

    /// See [`AccountIdPrefix::as_felt`](crate::account::AccountIdPrefix::as_felt) for details.
    pub const fn as_felt(&self) -> Felt {
        self.prefix
    }

    /// See [`AccountIdPrefix::as_u64`](crate::account::AccountIdPrefix::as_u64) for details.
    pub const fn as_u64(&self) -> u64 {
        self.prefix.as_int()
    }

    /// See [`AccountIdPrefix::account_type`](crate::account::AccountIdPrefix::account_type) for
    /// details.
    pub const fn account_type(&self) -> AccountType {
        v0::extract_type(self.prefix.as_int())
    }

    /// See [`AccountIdPrefix::is_faucet`](crate::account::AccountIdPrefix::is_faucet) for details.
    pub fn is_faucet(&self) -> bool {
        self.account_type().is_faucet()
    }

    /// See [`AccountIdPrefix::is_regular_account`](crate::account::AccountIdPrefix::is_regular_account) for
    /// details.
    pub fn is_regular_account(&self) -> bool {
        self.account_type().is_regular_account()
    }

    /// See [`AccountIdPrefix::storage_mode`](crate::account::AccountIdPrefix::storage_mode) for
    /// details.
    pub fn storage_mode(&self) -> AccountStorageMode {
        v0::extract_storage_mode(self.prefix.as_int())
            .expect("account ID prefix should have been constructed with a valid storage mode")
    }

    /// See [`AccountIdPrefix::is_public`](crate::account::AccountIdPrefix::is_public) for details.
    pub fn is_public(&self) -> bool {
        self.storage_mode() == AccountStorageMode::Public
    }

    /// See [`AccountIdPrefix::version`](crate::account::AccountIdPrefix::version) for details.
    pub fn version(&self) -> AccountIdVersion {
        v0::extract_version(self.prefix.as_int())
            .expect("account ID prefix should have been constructed with a valid version")
    }

    /// See [`AccountIdPrefix::to_hex`](crate::account::AccountIdPrefix::to_hex) for details.
    pub fn to_hex(self) -> String {
        format!("0x{:016x}", self.prefix.as_int())
    }
}

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

impl From<AccountIdPrefixV0> for Felt {
    fn from(id: AccountIdPrefixV0) -> Self {
        id.prefix
    }
}

impl From<AccountIdPrefixV0> for [u8; 8] {
    fn from(id: AccountIdPrefixV0) -> Self {
        let mut result = [0_u8; 8];
        result[..8].copy_from_slice(&id.prefix.as_int().to_be_bytes());
        result
    }
}

impl From<AccountIdPrefixV0> for u64 {
    fn from(id: AccountIdPrefixV0) -> Self {
        id.prefix.as_int()
    }
}

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

impl TryFrom<[u8; 8]> for AccountIdPrefixV0 {
    type Error = AccountIdError;

    /// See [`TryFrom<[u8; 8]> for
    /// AccountIdPrefix`](crate::account::AccountIdPrefix#impl-TryFrom<%5Bu8;+8%
    /// 5D>-for-AccountIdPrefix) for details.
    fn try_from(mut value: [u8; 8]) -> Result<Self, Self::Error> {
        // Felt::try_from expects little-endian order.
        value.reverse();

        Felt::try_from(value.as_slice())
            .map_err(AccountIdError::AccountIdInvalidPrefixFieldElement)
            .and_then(Self::new)
    }
}

impl TryFrom<u64> for AccountIdPrefixV0 {
    type Error = AccountIdError;

    /// See [`TryFrom<u64> for
    /// AccountIdPrefix`](crate::account::AccountIdPrefix#impl-TryFrom<u64>-for-AccountIdPrefix)
    /// for details.
    fn try_from(value: u64) -> Result<Self, Self::Error> {
        let element = Felt::try_from(value.to_le_bytes().as_slice())
            .map_err(AccountIdError::AccountIdInvalidPrefixFieldElement)?;
        Self::new(element)
    }
}

impl TryFrom<Felt> for AccountIdPrefixV0 {
    type Error = AccountIdError;

    /// See [`TryFrom<Felt> for
    /// AccountIdPrefix`](crate::account::AccountIdPrefix#impl-TryFrom<Felt>-for-AccountIdPrefix)
    /// for details.
    fn try_from(element: Felt) -> Result<Self, Self::Error> {
        Self::new(element)
    }
}

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

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

impl Ord for AccountIdPrefixV0 {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.prefix.as_int().cmp(&other.prefix.as_int())
    }
}

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

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

impl Serializable for AccountIdPrefixV0 {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        let bytes: [u8; 8] = (*self).into();
        bytes.write_into(target);
    }

    fn get_size_hint(&self) -> usize {
        Self::SERIALIZED_SIZE
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        account::{AccountId, AccountIdPrefix},
        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_prefix_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 full_id = AccountId::try_from(account_id).unwrap();
            let prefix = full_id.prefix();
            assert_eq!(
                prefix,
                AccountIdPrefix::read_from_bytes(&prefix.to_bytes()).unwrap(),
                "failed in {idx}"
            );
        }
    }
}