miden_client/sync/
state_sync_update.rs

1use alloc::collections::{BTreeMap, BTreeSet};
2use alloc::vec::Vec;
3
4use miden_objects::Word;
5use miden_objects::account::AccountId;
6use miden_objects::block::{BlockHeader, BlockNumber};
7use miden_objects::crypto::merkle::{InOrderIndex, MmrPeaks};
8use miden_objects::note::{NoteId, Nullifier};
9use miden_objects::transaction::TransactionId;
10
11use super::SyncSummary;
12use crate::account::Account;
13use crate::note::{NoteUpdateTracker, NoteUpdateType};
14use crate::rpc::domain::transaction::TransactionInclusion;
15use crate::transaction::{DiscardCause, TransactionRecord, TransactionStatus};
16
17// STATE SYNC UPDATE
18// ================================================================================================
19
20/// Contains all information needed to apply the update in the store after syncing with the node.
21#[derive(Default)]
22pub struct StateSyncUpdate {
23    /// The block number of the last block that was synced.
24    pub block_num: BlockNumber,
25    /// New blocks and authentication nodes.
26    pub block_updates: BlockUpdates,
27    /// New and updated notes to be upserted in the store.
28    pub note_updates: NoteUpdateTracker,
29    /// Committed and discarded transactions after the sync.
30    pub transaction_updates: TransactionUpdateTracker,
31    /// Public account updates and mismatched private accounts after the sync.
32    pub account_updates: AccountUpdates,
33}
34
35impl From<&StateSyncUpdate> for SyncSummary {
36    fn from(value: &StateSyncUpdate) -> Self {
37        let new_public_note_ids = value
38            .note_updates
39            .updated_input_notes()
40            .filter_map(|note_update| {
41                let note = note_update.inner();
42                if let NoteUpdateType::Insert = note_update.update_type() {
43                    Some(note.id())
44                } else {
45                    None
46                }
47            })
48            .collect();
49
50        let committed_note_ids: BTreeSet<NoteId> = value
51            .note_updates
52            .updated_input_notes()
53            .filter_map(|note_update| {
54                let note = note_update.inner();
55                if let NoteUpdateType::Update = note_update.update_type() {
56                    note.is_committed().then_some(note.id())
57                } else {
58                    None
59                }
60            })
61            .chain(value.note_updates.updated_output_notes().filter_map(|note_update| {
62                let note = note_update.inner();
63                if let NoteUpdateType::Update = note_update.update_type() {
64                    note.is_committed().then_some(note.id())
65                } else {
66                    None
67                }
68            }))
69            .collect();
70
71        let consumed_note_ids: BTreeSet<NoteId> = value
72            .note_updates
73            .updated_input_notes()
74            .filter_map(|note| note.inner().is_consumed().then_some(note.inner().id()))
75            .collect();
76
77        SyncSummary::new(
78            value.block_num,
79            new_public_note_ids,
80            committed_note_ids.into_iter().collect(),
81            consumed_note_ids.into_iter().collect(),
82            value
83                .account_updates
84                .updated_public_accounts()
85                .iter()
86                .map(Account::id)
87                .collect(),
88            value
89                .account_updates
90                .mismatched_private_accounts()
91                .iter()
92                .map(|(id, _)| *id)
93                .collect(),
94            value.transaction_updates.committed_transactions().map(|t| t.id).collect(),
95        )
96    }
97}
98
99/// Contains all the block information that needs to be added in the client's store after a sync.
100#[derive(Debug, Clone, Default)]
101pub struct BlockUpdates {
102    /// New block headers to be stored, along with a flag indicating whether the block contains
103    /// notes that are relevant to the client and the MMR peaks for the block.
104    block_headers: Vec<(BlockHeader, bool, MmrPeaks)>,
105    /// New authentication nodes that are meant to be stored in order to authenticate block
106    /// headers.
107    new_authentication_nodes: Vec<(InOrderIndex, Word)>,
108}
109
110impl BlockUpdates {
111    /// Creates a new instance of [`BlockUpdates`].
112    pub fn new(
113        block_headers: Vec<(BlockHeader, bool, MmrPeaks)>,
114        new_authentication_nodes: Vec<(InOrderIndex, Word)>,
115    ) -> Self {
116        Self { block_headers, new_authentication_nodes }
117    }
118
119    /// Adds a new block header and its corresponding data to this [`BlockUpdates`].
120    ///
121    /// # Parameters
122    /// - `block_header`: The block header to add.
123    /// - `has_client_notes`: Whether this block contains input notes that the client could use.
124    /// - `peaks`: The MMR peaks after including `block_header`.
125    /// - `new_authentication_nodes`: Authentication (MMR) nodes produced while adding
126    ///   `block_header` to the client's MMR.
127    pub fn insert(
128        &mut self,
129        block_header: BlockHeader,
130        has_client_notes: bool,
131        peaks: MmrPeaks,
132        new_authentication_nodes: Vec<(InOrderIndex, Word)>,
133    ) {
134        self.block_headers.push((block_header, has_client_notes, peaks));
135
136        self.new_authentication_nodes.reserve(new_authentication_nodes.len());
137        self.new_authentication_nodes.extend(new_authentication_nodes);
138    }
139
140    /// Returns the new block headers to be stored, along with a flag indicating whether the block
141    /// contains notes that are relevant to the client and the MMR peaks for the block.
142    pub fn block_headers(&self) -> &[(BlockHeader, bool, MmrPeaks)] {
143        &self.block_headers
144    }
145
146    /// Returns the new authentication nodes that are meant to be stored in order to authenticate
147    /// block headers.
148    pub fn new_authentication_nodes(&self) -> &[(InOrderIndex, Word)] {
149        &self.new_authentication_nodes
150    }
151}
152
153/// Contains transaction changes to apply to the store.
154#[derive(Default)]
155pub struct TransactionUpdateTracker {
156    transactions: BTreeMap<TransactionId, TransactionRecord>,
157}
158
159impl TransactionUpdateTracker {
160    /// Creates a new [`TransactionUpdateTracker`]
161    pub fn new(transactions: Vec<TransactionRecord>) -> Self {
162        let transactions =
163            transactions.into_iter().map(|tx| (tx.id, tx)).collect::<BTreeMap<_, _>>();
164
165        Self { transactions }
166    }
167
168    /// Returns a reference to committed transactions.
169    pub fn committed_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
170        self.transactions
171            .values()
172            .filter(|tx| matches!(tx.status, TransactionStatus::Committed { .. }))
173    }
174
175    /// Returns a reference to discarded transactions.
176    pub fn discarded_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
177        self.transactions
178            .values()
179            .filter(|tx| matches!(tx.status, TransactionStatus::Discarded(_)))
180    }
181
182    /// Returns a mutable reference to pending transactions in the tracker.
183    fn mutable_pending_transactions(&mut self) -> impl Iterator<Item = &mut TransactionRecord> {
184        self.transactions
185            .values_mut()
186            .filter(|tx| matches!(tx.status, TransactionStatus::Pending))
187    }
188
189    /// Returns transaction IDs of all transactions that have been updated.
190    pub fn updated_transaction_ids(&self) -> impl Iterator<Item = TransactionId> {
191        self.committed_transactions()
192            .chain(self.discarded_transactions())
193            .map(|tx| tx.id)
194    }
195
196    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a
197    /// transaction is included in a block.
198    pub fn apply_transaction_inclusion(
199        &mut self,
200        transaction_inclusion: &TransactionInclusion,
201        timestamp: u64,
202    ) {
203        if let Some(transaction) = self.transactions.get_mut(&transaction_inclusion.transaction_id)
204        {
205            transaction.commit_transaction(transaction_inclusion.block_num, timestamp);
206        }
207    }
208
209    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a the sync
210    /// height of the client is updated. This may result in stale or expired transactions.
211    pub fn apply_sync_height_update(
212        &mut self,
213        new_sync_height: BlockNumber,
214        tx_graceful_blocks: Option<u32>,
215    ) {
216        if let Some(tx_graceful_blocks) = tx_graceful_blocks {
217            self.discard_transaction_with_predicate(
218                |transaction| {
219                    transaction.details.submission_height
220                        < new_sync_height.checked_sub(tx_graceful_blocks).unwrap_or_default()
221                },
222                DiscardCause::Stale,
223            );
224        }
225
226        // NOTE: we check for <= new_sync height because at this point we would have committed the
227        // transaction otherwise
228        self.discard_transaction_with_predicate(
229            |transaction| transaction.details.expiration_block_num <= new_sync_height,
230            DiscardCause::Expired,
231        );
232    }
233
234    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a note is
235    /// nullified. this may result in transactions being discarded because they were processing the
236    /// nullified note.
237    pub fn apply_input_note_nullified(&mut self, input_note_nullifier: Nullifier) {
238        self.discard_transaction_with_predicate(
239            |transaction| {
240                // Check if the note was being processed by a local transaction that didn't end up
241                // being committed so it should be discarded
242                transaction
243                    .details
244                    .input_note_nullifiers
245                    .contains(&input_note_nullifier.as_word())
246            },
247            DiscardCause::InputConsumed,
248        );
249    }
250
251    /// Discards transactions that have the same initial account state as the provided one.
252    pub fn apply_invalid_initial_account_state(&mut self, invalid_account_state: Word) {
253        self.discard_transaction_with_predicate(
254            |transaction| transaction.details.init_account_state == invalid_account_state,
255            DiscardCause::DiscardedInitialState,
256        );
257    }
258
259    /// Discards transactions that match the predicate and also applies the new invalid account
260    /// states
261    fn discard_transaction_with_predicate<F>(&mut self, predicate: F, discard_cause: DiscardCause)
262    where
263        F: Fn(&TransactionRecord) -> bool,
264    {
265        let mut new_invalid_account_states = vec![];
266
267        for transaction in self.mutable_pending_transactions() {
268            // Discard transactions, and also push the invalid account state if the transaction
269            // got correctly discarded
270            // NOTE: previous updates in a chain of state syncs could have committed a transaction,
271            // so we need to check that `discard_transaction` returns `true` here (aka, it got
272            // discarded from a valid state)
273            if predicate(transaction) && transaction.discard_transaction(discard_cause) {
274                new_invalid_account_states.push(transaction.details.final_account_state);
275            }
276        }
277
278        for state in new_invalid_account_states {
279            self.apply_invalid_initial_account_state(state);
280        }
281    }
282}
283
284// ACCOUNT UPDATES
285// ================================================================================================
286
287/// Contains account changes to apply to the store after a sync request.
288#[derive(Debug, Clone, Default)]
289pub struct AccountUpdates {
290    /// Updated public accounts.
291    updated_public_accounts: Vec<Account>,
292    /// Account commitments received from the network that don't match the currently
293    /// locally-tracked state of the private accounts.
294    ///
295    /// These updates may represent a stale account commitment (meaning that the latest local state
296    /// hasn't been committed). If this is not the case, the account may be locked until the state
297    /// is restored manually.
298    mismatched_private_accounts: Vec<(AccountId, Word)>,
299}
300
301impl AccountUpdates {
302    /// Creates a new instance of `AccountUpdates`.
303    pub fn new(
304        updated_public_accounts: Vec<Account>,
305        mismatched_private_accounts: Vec<(AccountId, Word)>,
306    ) -> Self {
307        Self {
308            updated_public_accounts,
309            mismatched_private_accounts,
310        }
311    }
312
313    /// Returns the updated public accounts.
314    pub fn updated_public_accounts(&self) -> &[Account] {
315        &self.updated_public_accounts
316    }
317
318    /// Returns the mismatched private accounts.
319    pub fn mismatched_private_accounts(&self) -> &[(AccountId, Word)] {
320        &self.mismatched_private_accounts
321    }
322
323    pub fn extend(&mut self, other: AccountUpdates) {
324        self.updated_public_accounts.extend(other.updated_public_accounts);
325        self.mismatched_private_accounts.extend(other.mismatched_private_accounts);
326    }
327}