Skip to main content

miden_client/sync/
mod.rs

1//! Provides the client APIs for synchronizing the client's local state with the Miden
2//! network. It ensures that the client maintains a valid, up-to-date view of the chain.
3//!
4//! ## Overview
5//!
6//! This module handles the synchronization process between the local client and the Miden network.
7//! The sync operation involves:
8//!
9//! - Querying the Miden node for state updates using tracked account IDs, note tags, and nullifier
10//!   prefixes.
11//! - Processing the received data to update note inclusion proofs, reconcile note state (new,
12//!   committed, or consumed), and update account states.
13//! - Incorporating new block headers and updating the local Merkle Mountain Range (MMR) with new
14//!   peaks and authentication nodes.
15//! - Aggregating transaction updates to determine which transactions have been committed or
16//!   discarded.
17//!
18//! The result of the synchronization process is captured in a [`SyncSummary`], which provides
19//! a summary of the new block number along with lists of received, committed, and consumed note
20//! IDs, updated account IDs, locked accounts, and committed transaction IDs.
21//!
22//! Once the data is requested and retrieved, updates are persisted in the client's store.
23//!
24//! ## Examples
25//!
26//! The following example shows how to initiate a state sync and handle the resulting summary:
27//!
28//! ```rust
29//! # use miden_client::auth::TransactionAuthenticator;
30//! # use miden_client::sync::SyncSummary;
31//! # use miden_client::{Client, ClientError};
32//! # use miden_protocol::{block::BlockHeader, Felt, Word};
33//! # use miden_protocol::crypto::rand::FeltRng;
34//! # async fn run_sync<AUTH: TransactionAuthenticator + Sync + 'static>(client: &mut Client<AUTH>) -> Result<(), ClientError> {
35//! // Attempt to synchronize the client's state with the Miden network.
36//! // The requested data is based on the client's state: it gets updates for accounts, relevant
37//! // notes, etc. For more information on the data that gets requested, see the doc comments for
38//! // `sync_state()`.
39//! let sync_summary: SyncSummary = client.sync_state().await?;
40//!
41//! println!("Synced up to block number: {}", sync_summary.block_num);
42//! println!("Committed notes: {}", sync_summary.committed_notes.len());
43//! println!("Consumed notes: {}", sync_summary.consumed_notes.len());
44//! println!("Updated accounts: {}", sync_summary.updated_accounts.len());
45//! println!("Locked accounts: {}", sync_summary.locked_accounts.len());
46//! println!("Committed transactions: {}", sync_summary.committed_transactions.len());
47//!
48//! Ok(())
49//! # }
50//! ```
51//!
52//! The `sync_state` method loops internally until the client is fully synced to the network tip.
53//!
54//! For more advanced usage, refer to the individual functions (such as
55//! `committed_note_updates` and `consumed_note_updates`) to understand how the sync data is
56//! processed and applied to the local store.
57
58use alloc::sync::Arc;
59use alloc::vec::Vec;
60use core::cmp::max;
61
62use miden_protocol::account::AccountId;
63use miden_protocol::block::BlockNumber;
64use miden_protocol::note::NoteId;
65use miden_protocol::transaction::TransactionId;
66use miden_tx::auth::TransactionAuthenticator;
67use miden_tx::utils::serde::{Deserializable, DeserializationError, Serializable};
68use tracing::{debug, info};
69
70use crate::store::{NoteFilter, TransactionFilter};
71use crate::{Client, ClientError};
72mod block_header;
73
74mod tag;
75pub use tag::{NoteTagRecord, NoteTagSource};
76
77mod state_sync;
78pub use state_sync::{NoteUpdateAction, OnNoteReceived, StateSync, StateSyncInput};
79
80mod state_sync_update;
81pub use state_sync_update::{
82    AccountUpdates,
83    BlockUpdates,
84    PublicAccountUpdate,
85    StateSyncUpdate,
86    TransactionUpdateTracker,
87};
88
89/// Client synchronization methods.
90impl<AUTH> Client<AUTH>
91where
92    AUTH: TransactionAuthenticator + Sync + 'static,
93{
94    // SYNC STATE
95    // --------------------------------------------------------------------------------------------
96
97    /// Returns the block number of the last state sync block.
98    pub async fn get_sync_height(&self) -> Result<BlockNumber, ClientError> {
99        self.store.get_sync_height().await.map_err(Into::into)
100    }
101
102    /// Syncs the client's state with the current state of the Miden network and returns a
103    /// [`SyncSummary`] corresponding to the local state update.
104    ///
105    /// The sync process is done in multiple steps:
106    /// 1. A request is sent to the node to get the state updates. This request includes tracked
107    ///    account IDs and the tags of notes that might have changed or that might be of interest to
108    ///    the client.
109    /// 2. A response is received with the current state of the network. The response includes
110    ///    information about new/committed/consumed notes, updated accounts, and committed
111    ///    transactions.
112    /// 3. Tracked notes are updated with their new states.
113    /// 4. New notes are checked, and only relevant ones are stored. Relevant notes are those that
114    ///    can be consumed by accounts the client is tracking (this is checked by the
115    ///    [`crate::note::NoteScreener`])
116    /// 5. Transactions are updated with their new states.
117    /// 6. Tracked public accounts are updated and private accounts are validated against the node
118    ///    state.
119    /// 7. The MMR is updated with the new peaks and authentication nodes.
120    /// 8. All updates are applied to the store to be persisted.
121    pub async fn sync_state(&mut self) -> Result<SyncSummary, ClientError> {
122        self.ensure_genesis_in_place().await?;
123        self.ensure_rpc_limits_in_place().await?;
124
125        // Note Transport update
126        // TODO We can run both sync_state, fetch_transport_notes futures in parallel
127        if self.is_note_transport_enabled() {
128            let cursor = self.store.get_note_transport_cursor().await?;
129            let note_tags = self.store.get_unique_note_tags().await?;
130            self.fetch_transport_notes(cursor, note_tags).await?;
131        }
132
133        // Build sync state components
134        let note_screener = self.note_screener();
135        let state_sync = StateSync::new(
136            self.rpc_api.clone(),
137            Some(self.store.clone()),
138            Arc::new(note_screener),
139            self.tx_discard_delta,
140        );
141        let mut current_partial_mmr = self.store.get_current_partial_mmr().await?;
142        let input = self.build_sync_input().await?;
143
144        // Get the sync update from the network
145        let state_sync_update = state_sync.sync_state(&mut current_partial_mmr, input).await?;
146
147        let sync_summary: SyncSummary = (&state_sync_update).into();
148        debug!(sync_summary = ?sync_summary, "Sync summary computed");
149        info!("Applying changes to the store.");
150
151        // Apply received and computed updates to the store
152        self.store
153            .apply_state_sync(state_sync_update)
154            .await
155            .map_err(ClientError::StoreError)?;
156
157        // Remove irrelevant block headers
158        self.store.prune_irrelevant_blocks().await?;
159
160        Ok(sync_summary)
161    }
162
163    /// Builds a default [`StateSyncInput`] from the current client state.
164    ///
165    /// This includes all tracked account headers, all unique note tags, all unspent input and
166    /// output notes, and all uncommitted transactions.
167    pub async fn build_sync_input(&self) -> Result<StateSyncInput, ClientError> {
168        let accounts = self
169            .store
170            .get_account_headers()
171            .await?
172            .into_iter()
173            .map(|(header, _status)| header)
174            .collect();
175
176        let note_tags = self.store.get_unique_note_tags().await?;
177
178        let input_notes = self.store.get_input_notes(NoteFilter::Unspent).await?;
179        let output_notes = self.store.get_output_notes(NoteFilter::Unspent).await?;
180
181        let uncommitted_transactions =
182            self.store.get_transactions(TransactionFilter::Uncommitted).await?;
183
184        Ok(StateSyncInput {
185            accounts,
186            note_tags,
187            input_notes,
188            output_notes,
189            uncommitted_transactions,
190        })
191    }
192
193    /// Applies the state sync update to the store and prunes the irrelevant block headers.
194    ///
195    /// See [`crate::Store::apply_state_sync()`] for what the update implies.
196    pub async fn apply_state_sync(&mut self, update: StateSyncUpdate) -> Result<(), ClientError> {
197        self.store.apply_state_sync(update).await?;
198
199        // Remove irrelevant block headers
200        self.store.prune_irrelevant_blocks().await?;
201
202        Ok(())
203    }
204
205    /// Ensures that the RPC limits are set in the RPC client. If not already cached,
206    /// fetches them from the node and persists them in the store.
207    pub async fn ensure_rpc_limits_in_place(&mut self) -> Result<(), ClientError> {
208        if self.rpc_api.has_rpc_limits().is_some() {
209            return Ok(());
210        }
211
212        let limits = self.rpc_api.get_rpc_limits().await?;
213        self.store.set_rpc_limits(limits).await?;
214        Ok(())
215    }
216}
217
218// SYNC SUMMARY
219// ================================================================================================
220
221/// Contains stats about the sync operation.
222#[derive(Debug, PartialEq)]
223pub struct SyncSummary {
224    /// Block number up to which the client has been synced.
225    pub block_num: BlockNumber,
226    /// IDs of new public notes that the client has received.
227    pub new_public_notes: Vec<NoteId>,
228    /// IDs of tracked notes that have been committed.
229    pub committed_notes: Vec<NoteId>,
230    /// IDs of notes that have been consumed.
231    pub consumed_notes: Vec<NoteId>,
232    /// IDs of on-chain accounts that have been updated.
233    pub updated_accounts: Vec<AccountId>,
234    /// IDs of private accounts that have been locked.
235    pub locked_accounts: Vec<AccountId>,
236    /// IDs of committed transactions.
237    pub committed_transactions: Vec<TransactionId>,
238}
239
240impl SyncSummary {
241    pub fn new(
242        block_num: BlockNumber,
243        new_public_notes: Vec<NoteId>,
244        committed_notes: Vec<NoteId>,
245        consumed_notes: Vec<NoteId>,
246        updated_accounts: Vec<AccountId>,
247        locked_accounts: Vec<AccountId>,
248        committed_transactions: Vec<TransactionId>,
249    ) -> Self {
250        Self {
251            block_num,
252            new_public_notes,
253            committed_notes,
254            consumed_notes,
255            updated_accounts,
256            locked_accounts,
257            committed_transactions,
258        }
259    }
260
261    pub fn new_empty(block_num: BlockNumber) -> Self {
262        Self {
263            block_num,
264            new_public_notes: vec![],
265            committed_notes: vec![],
266            consumed_notes: vec![],
267            updated_accounts: vec![],
268            locked_accounts: vec![],
269            committed_transactions: vec![],
270        }
271    }
272
273    pub fn is_empty(&self) -> bool {
274        self.new_public_notes.is_empty()
275            && self.committed_notes.is_empty()
276            && self.consumed_notes.is_empty()
277            && self.updated_accounts.is_empty()
278            && self.locked_accounts.is_empty()
279            && self.committed_transactions.is_empty()
280    }
281
282    pub fn combine_with(&mut self, mut other: Self) {
283        self.block_num = max(self.block_num, other.block_num);
284        self.new_public_notes.append(&mut other.new_public_notes);
285        self.committed_notes.append(&mut other.committed_notes);
286        self.consumed_notes.append(&mut other.consumed_notes);
287        self.updated_accounts.append(&mut other.updated_accounts);
288        self.locked_accounts.append(&mut other.locked_accounts);
289        self.committed_transactions.append(&mut other.committed_transactions);
290    }
291}
292
293impl Serializable for SyncSummary {
294    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
295        self.block_num.write_into(target);
296        self.new_public_notes.write_into(target);
297        self.committed_notes.write_into(target);
298        self.consumed_notes.write_into(target);
299        self.updated_accounts.write_into(target);
300        self.locked_accounts.write_into(target);
301        self.committed_transactions.write_into(target);
302    }
303}
304
305impl Deserializable for SyncSummary {
306    fn read_from<R: miden_tx::utils::serde::ByteReader>(
307        source: &mut R,
308    ) -> Result<Self, DeserializationError> {
309        let block_num = BlockNumber::read_from(source)?;
310        let new_public_notes = Vec::<NoteId>::read_from(source)?;
311        let committed_notes = Vec::<NoteId>::read_from(source)?;
312        let consumed_notes = Vec::<NoteId>::read_from(source)?;
313        let updated_accounts = Vec::<AccountId>::read_from(source)?;
314        let locked_accounts = Vec::<AccountId>::read_from(source)?;
315        let committed_transactions = Vec::<TransactionId>::read_from(source)?;
316
317        Ok(Self {
318            block_num,
319            new_public_notes,
320            committed_notes,
321            consumed_notes,
322            updated_accounts,
323            locked_accounts,
324            committed_transactions,
325        })
326    }
327}