miden_protocol/account/partial.rs
1use alloc::string::ToString;
2use alloc::vec::Vec;
3
4use miden_core::{Felt, ZERO};
5
6use super::{Account, AccountCode, AccountId, PartialStorage};
7use crate::Word;
8use crate::account::{AccountHeader, validate_account_seed};
9use crate::asset::PartialVault;
10use crate::crypto::SequentialCommit;
11use crate::errors::AccountError;
12use crate::utils::serde::{
13 ByteReader,
14 ByteWriter,
15 Deserializable,
16 DeserializationError,
17 Serializable,
18};
19
20/// A partial representation of an account.
21///
22/// A partial account is used as inputs to the transaction kernel and contains only the essential
23/// data needed for verification and transaction processing without requiring the full account
24/// state.
25///
26/// For new accounts, the partial storage must be the full initial account storage.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct PartialAccount {
29 /// The ID for the partial account
30 id: AccountId,
31 /// Partial representation of the account's vault, containing the vault root and necessary
32 /// proof information for asset verification
33 partial_vault: PartialVault,
34 /// Partial representation of the account's storage, containing the storage commitment and
35 /// proofs for specific storage slots that need to be accessed
36 partial_storage: PartialStorage,
37 /// Account code
38 code: AccountCode,
39 /// The current transaction nonce of the account
40 nonce: Felt,
41 /// The seed of the account ID, if any.
42 seed: Option<Word>,
43}
44
45impl PartialAccount {
46 // CONSTRUCTORS
47 // --------------------------------------------------------------------------------------------
48
49 /// Creates a new [`PartialAccount`] with the provided account parts and seed.
50 ///
51 /// # Errors
52 ///
53 /// Returns an error if:
54 /// - an account seed is provided but the account's nonce indicates the account already exists.
55 /// - an account seed is not provided but the account's nonce indicates the account is new.
56 /// - an account seed is provided but the account ID derived from it is invalid or does not
57 /// match the provided ID.
58 pub fn new(
59 id: AccountId,
60 nonce: Felt,
61 code: AccountCode,
62 partial_storage: PartialStorage,
63 partial_vault: PartialVault,
64 seed: Option<Word>,
65 ) -> Result<Self, AccountError> {
66 validate_account_seed(id, code.commitment(), partial_storage.commitment(), seed, nonce)?;
67
68 let account = Self {
69 id,
70 nonce,
71 code,
72 partial_storage,
73 partial_vault,
74 seed,
75 };
76
77 Ok(account)
78 }
79
80 // ACCESSORS
81 // --------------------------------------------------------------------------------------------
82
83 /// Returns the account's unique identifier.
84 pub fn id(&self) -> AccountId {
85 self.id
86 }
87
88 /// Returns the account's current nonce value.
89 pub fn nonce(&self) -> Felt {
90 self.nonce
91 }
92
93 /// Returns a reference to the account code.
94 pub fn code(&self) -> &AccountCode {
95 &self.code
96 }
97
98 /// Returns a reference to the partial storage representation of the account.
99 pub fn storage(&self) -> &PartialStorage {
100 &self.partial_storage
101 }
102
103 /// Returns a reference to the partial vault representation of the account.
104 pub fn vault(&self) -> &PartialVault {
105 &self.partial_vault
106 }
107
108 /// Returns the seed of the account's ID if the account is new.
109 ///
110 /// That is, if [`PartialAccount::is_new`] returns `true`, the seed will be `Some`.
111 pub fn seed(&self) -> Option<Word> {
112 self.seed
113 }
114
115 /// Returns `true` if the account is new, `false` otherwise.
116 ///
117 /// An account is considered new if the account's nonce is zero and it hasn't been registered on
118 /// chain yet.
119 pub fn is_new(&self) -> bool {
120 self.nonce == ZERO
121 }
122
123 /// Returns the commitment of this account.
124 ///
125 /// See [`AccountHeader::to_commitment`] for details on how it is computed.
126 pub fn to_commitment(&self) -> Word {
127 AccountHeader::from(self).to_commitment()
128 }
129
130 /// Returns the commitment of this account as used for the initial account state commitment in
131 /// transaction proofs.
132 ///
133 /// For existing accounts, this is exactly the same as [Account::to_commitment], however, for
134 /// new accounts this value is set to [`Word::empty`]. This is because when a transaction is
135 /// executed against a new account, public input for the initial account state is set to
136 /// [`Word::empty`] to distinguish new accounts from existing accounts. The actual
137 /// commitment of the initial account state (and the initial state itself), are provided to
138 /// the VM via the advice provider.
139 pub fn initial_commitment(&self) -> Word {
140 if self.is_new() {
141 Word::empty()
142 } else {
143 self.to_commitment()
144 }
145 }
146
147 /// Consumes self and returns the underlying parts of the partial account.
148 pub fn into_parts(
149 self,
150 ) -> (AccountId, PartialVault, PartialStorage, AccountCode, Felt, Option<Word>) {
151 (
152 self.id,
153 self.partial_vault,
154 self.partial_storage,
155 self.code,
156 self.nonce,
157 self.seed,
158 )
159 }
160}
161
162impl From<&Account> for PartialAccount {
163 /// Constructs a [`PartialAccount`] from the provided account.
164 ///
165 /// The behavior is different whether the [`Account::is_new`] or not:
166 /// - For new accounts, the storage is tracked in full. This is because transactions that create
167 /// accounts need the full state.
168 /// - For existing accounts, the storage is tracked minimally, i.e. the minimal necessary data
169 /// is included.
170 ///
171 /// Because new accounts always have empty vaults, in both cases, the asset vault is a minimal
172 /// representation.
173 ///
174 /// For precise control over how an account is converted to a partial account, use
175 /// [`PartialAccount::new`].
176 fn from(account: &Account) -> Self {
177 let partial_storage = if account.is_new() {
178 // This is somewhat expensive, but it allows us to do this conversion from &Account and
179 // it penalizes only the rare case (new accounts).
180 PartialStorage::new_full(account.storage.clone())
181 } else {
182 PartialStorage::new_minimal(account.storage())
183 };
184
185 Self::new(
186 account.id(),
187 account.nonce(),
188 account.code().clone(),
189 partial_storage,
190 PartialVault::new_minimal(account.vault()),
191 account.seed(),
192 )
193 .expect("account should ensure that seed is valid for account")
194 }
195}
196
197impl SequentialCommit for PartialAccount {
198 type Commitment = Word;
199
200 fn to_elements(&self) -> Vec<Felt> {
201 AccountHeader::from(self).to_elements()
202 }
203
204 fn to_commitment(&self) -> Self::Commitment {
205 AccountHeader::from(self).to_commitment()
206 }
207}
208// SERIALIZATION
209// ================================================================================================
210
211impl Serializable for PartialAccount {
212 fn write_into<W: ByteWriter>(&self, target: &mut W) {
213 target.write(self.id);
214 target.write(self.nonce);
215 target.write(&self.code);
216 target.write(&self.partial_storage);
217 target.write(&self.partial_vault);
218 target.write(self.seed);
219 }
220}
221
222impl Deserializable for PartialAccount {
223 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
224 let account_id = source.read()?;
225 let nonce = source.read()?;
226 let account_code = source.read()?;
227 let partial_storage = source.read()?;
228 let partial_vault = source.read()?;
229 let seed: Option<Word> = source.read()?;
230
231 PartialAccount::new(account_id, nonce, account_code, partial_storage, partial_vault, seed)
232 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
233 }
234}