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!("New private notes: {}", sync_summary.new_private_notes.len());
43//! println!("Committed notes: {}", sync_summary.committed_notes.len());
44//! println!("Consumed notes: {}", sync_summary.consumed_notes.len());
45//! println!("Updated accounts: {}", sync_summary.updated_accounts.len());
46//! println!("Locked accounts: {}", sync_summary.locked_accounts.len());
47//! println!("Committed transactions: {}", sync_summary.committed_transactions.len());
48//!
49//! Ok(())
50//! # }
51//! ```
52//!
53//! The `sync_state` method loops internally until the client is fully synced to the network tip.
54//!
55//! For more advanced usage, refer to the individual functions (such as
56//! `committed_note_updates` and `consumed_note_updates`) to understand how the sync data is
57//! processed and applied to the local store.
58
59use alloc::collections::BTreeSet;
60use alloc::sync::Arc;
61use alloc::vec::Vec;
62use core::cmp::max;
63
64use miden_protocol::account::AccountId;
65use miden_protocol::block::BlockNumber;
66use miden_protocol::note::NoteId;
67use miden_protocol::transaction::TransactionId;
68use miden_tx::auth::TransactionAuthenticator;
69use miden_tx::utils::serde::{Deserializable, DeserializationError, Serializable};
70use tracing::{debug, info};
71
72use crate::pswap::PswapChainObserver;
73use crate::store::{NoteFilter, TransactionFilter};
74use crate::{Client, ClientError};
75mod block_header;
76
77mod tag;
78pub use tag::{NoteTagRecord, NoteTagSource};
79
80mod note_observer;
81pub use note_observer::NoteObserver;
82
83mod state_sync;
84pub use state_sync::{NoteUpdateAction, OnNoteReceived, StateSync, StateSyncInput};
85
86mod state_sync_update;
87pub use state_sync_update::{
88    AccountUpdates,
89    PartialBlockchainUpdates,
90    PublicAccountUpdate,
91    StateSyncUpdate,
92    TransactionUpdateTracker,
93};
94
95/// Client synchronization methods.
96impl<AUTH> Client<AUTH>
97where
98    AUTH: TransactionAuthenticator + Sync + 'static,
99{
100    // SYNC STATE
101    // --------------------------------------------------------------------------------------------
102
103    /// Returns the block number of the last state sync block.
104    pub async fn get_sync_height(&self) -> Result<BlockNumber, ClientError> {
105        self.store.get_sync_height().await.map_err(Into::into)
106    }
107
108    /// Syncs the client's on-chain state with the current state of the Miden network and returns
109    /// a [`SyncSummary`] corresponding to the local state update.
110    ///
111    /// Does **not** fetch private notes from the Note Transport Layer. Use
112    /// [`Client::sync_state`] for the combined sync, or call [`Client::sync_note_transport`]
113    /// separately.
114    ///
115    /// Builds the default sync input, runs [`StateSync::sync_state`] (see that method for the
116    /// detailed pipeline), applies the resulting update to the store, caches the partial MMR, and
117    /// prunes irrelevant blocks according to the configured cadence.
118    pub async fn sync_chain(&mut self) -> Result<SyncSummary, ClientError> {
119        self.ensure_genesis_in_place().await?;
120        self.ensure_rpc_limits_in_place().await?;
121
122        // Each `NoteObserver` owns its own per-sync state; `with_note_observer` just attaches.
123        let note_screener = self.note_screener();
124        let state_sync =
125            StateSync::new(self.rpc_api.clone(), Arc::new(note_screener), self.tx_discard_delta)
126                .with_note_observer(Arc::new(PswapChainObserver::new(self.store.clone())));
127        let input = self.build_sync_input().await?;
128
129        let mut partial_mmr = self.get_current_partial_mmr().await?;
130
131        // Get the sync update from the network
132        let state_sync_update = state_sync.sync_state(&mut partial_mmr, input).await?;
133
134        let sync_summary: SyncSummary = (&state_sync_update).into();
135        debug!(sync_summary = ?sync_summary, "Sync summary computed");
136
137        // Post-sync observer hooks; run before persisting. Per-observer errors are logged, not
138        // propagated.
139        state_sync.run_apply_hooks(&state_sync_update).await?;
140
141        info!("Applying changes to the store.");
142
143        // Apply received and computed updates to the store
144        self.store
145            .apply_state_sync(state_sync_update)
146            .await
147            .map_err(ClientError::StoreError)?;
148
149        // Cache MMR so pruning can reuse in-memory MMR.
150        self.cache_partial_mmr(partial_mmr).await?;
151
152        self.maybe_untrack_and_prune_irrelevant_blocks().await?;
153
154        Ok(sync_summary)
155    }
156
157    /// Fetches private notes from the Note Transport Layer for the tracked note tags.
158    ///
159    /// Returns the IDs of notes imported in this call. No-op (returns an empty vec) if note
160    /// transport is disabled.
161    pub async fn sync_note_transport(&mut self) -> Result<Vec<NoteId>, ClientError> {
162        if !self.is_note_transport_enabled() {
163            return Ok(Vec::new());
164        }
165
166        // Drain any private notes whose previous relay attempt failed. A flush
167        // error is logged, not propagated: a failing relay must not block the
168        // sync, and the entries stay durable for the next attempt.
169        if let Err(err) = self.flush_relay_outbox().await {
170            tracing::warn!(?err, "relay outbox flush failed during sync; entries retained");
171        }
172
173        let cursor = self.store.get_note_transport_cursor().await?;
174        let note_tags: Vec<_> = self.store.get_unique_note_tags().await?.into_iter().collect();
175        let (ids, new_cursor) = self.fetch_transport_notes(cursor, &note_tags).await?;
176        self.store.update_note_transport_cursor(new_cursor).await?;
177        Ok(ids)
178    }
179
180    /// Runs the full client sync.
181    ///
182    /// First fetches private notes from the Note Transport Layer (see
183    /// [`Client::sync_note_transport`]), then syncs the client's on-chain state with the Miden
184    /// node (see [`Client::sync_chain`]). If note transport is disabled, this is equivalent to
185    /// [`Client::sync_chain`].
186    ///
187    /// Fails fast on the first error. Private notes delivered via NTL are imported before the
188    /// chain sync reads its input set, so their nullifiers are checked in the same call.
189    pub async fn sync_state(&mut self) -> Result<SyncSummary, ClientError> {
190        let new_private_notes = self.sync_note_transport().await?;
191        let mut summary = self.sync_chain().await?;
192        summary.new_private_notes = new_private_notes;
193        Ok(summary)
194    }
195
196    /// Builds a default [`StateSyncInput`] from the current client state.
197    ///
198    /// This includes all tracked account headers, all unique note tags, all unspent input and
199    /// output notes, and all uncommitted transactions.
200    pub async fn build_sync_input(&self) -> Result<StateSyncInput, ClientError> {
201        let accounts = self
202            .store
203            .get_account_headers()
204            .await?
205            .into_iter()
206            .map(|(header, _status)| header)
207            .collect();
208
209        let note_tags = self.store.get_unique_note_tags().await?;
210
211        let input_notes = self.store.get_input_notes(NoteFilter::Unspent).await?;
212        let output_notes = self.store.get_output_notes(NoteFilter::Unspent).await?;
213
214        let uncommitted_transactions =
215            self.store.get_transactions(TransactionFilter::Uncommitted).await?;
216
217        Ok(StateSyncInput {
218            accounts,
219            note_tags,
220            input_notes,
221            output_notes,
222            uncommitted_transactions,
223        })
224    }
225
226    /// Applies the state sync update to the store and prunes irrelevant blocks according to the
227    /// configured cadence.
228    ///
229    /// See [`crate::Store::apply_state_sync()`] for what the update implies.
230    pub async fn apply_state_sync(&mut self, update: StateSyncUpdate) -> Result<(), ClientError> {
231        self.store.apply_state_sync(update).await?;
232
233        self.maybe_untrack_and_prune_irrelevant_blocks().await?;
234
235        Ok(())
236    }
237
238    /// Prunes irrelevant blocks and their MMR authentication nodes according to the configured
239    /// cadence.
240    async fn maybe_untrack_and_prune_irrelevant_blocks(&mut self) -> Result<(), ClientError> {
241        let Some(interval) = self.irrelevant_block_prune_interval else {
242            return Ok(());
243        };
244
245        let sync_height = self.store.get_sync_height().await?;
246
247        if let Some(last_prune_height) = self.last_irrelevant_block_prune_sync_height
248            && sync_height < last_prune_height + interval
249        {
250            return Ok(());
251        }
252
253        self.untrack_and_prune_irrelevant_blocks().await?;
254        self.last_irrelevant_block_prune_sync_height = Some(sync_height);
255
256        Ok(())
257    }
258
259    /// Prunes irrelevant block data from the store.
260    ///
261    /// Identifies tracked blocks whose input notes have all been consumed, untracks them from the
262    /// `PartialMmr` to determine which authentication nodes are no longer needed, then delegates
263    /// to [`Store::untrack_and_prune_irrelevant_blocks`] to atomically remove the stale nodes,
264    /// mark the blocks as irrelevant, and delete irrelevant block headers.
265    /// Any caller of this function should've cached the `PartialMmr` beforehand.
266    async fn untrack_and_prune_irrelevant_blocks(&mut self) -> Result<(), ClientError> {
267        let tracked_blocks = self.store.get_tracked_block_header_numbers().await?;
268        let to_untrack: Vec<usize> = if tracked_blocks.is_empty() {
269            // Do not early-return: even without blocks to untrack, old irrelevant tip headers may
270            // need pruning.
271            Vec::new()
272        } else {
273            // Blocks that still have at least one unspent note need to stay tracked.
274            let unspent_notes = self.store.get_input_notes(NoteFilter::Unspent).await?;
275            let live_blocks: BTreeSet<usize> = unspent_notes
276                .iter()
277                .filter_map(|n| n.inclusion_proof().map(|p| p.location().block_num().as_usize()))
278                .collect();
279
280            tracked_blocks.difference(&live_blocks).copied().collect()
281        };
282
283        let mut blocks_to_untrack = Vec::new();
284        let mut nodes_to_remove = Vec::new();
285        let mut updated_partial_mmr = None;
286
287        if !to_untrack.is_empty() {
288            // Rebuild the PartialMmr and untrack each block to collect the authentication node
289            // indices that are no longer needed by any remaining tracked leaf.
290            let mut partial_mmr = self.get_current_partial_mmr().await?;
291            for &block_pos in &to_untrack {
292                nodes_to_remove
293                    .extend(partial_mmr.untrack(block_pos).into_iter().map(|(idx, _)| idx));
294            }
295
296            blocks_to_untrack = to_untrack
297                .iter()
298                .map(|&b| BlockNumber::from(u32::try_from(b).expect("block number fits in u32")))
299                .collect();
300            updated_partial_mmr = Some(partial_mmr);
301        }
302
303        // Store deletes stale auth nodes, marks blocks as irrelevant, and removes irrelevant
304        // block headers. Old irrelevant tip headers may still need pruning.
305        self.store
306            .untrack_and_prune_irrelevant_blocks(&blocks_to_untrack, &nodes_to_remove)
307            .await?;
308
309        if let Some(partial_mmr) = updated_partial_mmr {
310            self.cache_partial_mmr(partial_mmr).await?;
311        }
312
313        Ok(())
314    }
315
316    /// Ensures that the RPC limits are set in the RPC client. If not already cached,
317    /// fetches them from the node and persists them in the store.
318    pub async fn ensure_rpc_limits_in_place(&mut self) -> Result<(), ClientError> {
319        if self.rpc_api.has_rpc_limits().is_some() {
320            return Ok(());
321        }
322
323        let limits = self.rpc_api.get_rpc_limits().await?;
324        self.store.set_rpc_limits(limits).await?;
325        Ok(())
326    }
327}
328
329// SYNC SUMMARY
330// ================================================================================================
331
332/// Contains stats about the sync operation.
333#[derive(Debug, PartialEq)]
334pub struct SyncSummary {
335    /// Block number up to which the client has been synced.
336    pub block_num: BlockNumber,
337    /// IDs of new public notes that the client has received.
338    pub new_public_notes: Vec<NoteId>,
339    /// IDs of private notes imported from the Note Transport Layer in this sync. They are still
340    /// `Expected` until observed on-chain.
341    ///
342    /// Only populated by [`Client::sync_state`]; [`Client::sync_chain`] always leaves this empty
343    /// because it does not touch the Note Transport Layer.
344    pub new_private_notes: Vec<NoteId>,
345    /// IDs of tracked notes that have been committed.
346    pub committed_notes: Vec<NoteId>,
347    /// IDs of notes that have been consumed.
348    pub consumed_notes: Vec<NoteId>,
349    /// IDs of on-chain accounts that have been updated.
350    pub updated_accounts: Vec<AccountId>,
351    /// IDs of private accounts that have been locked.
352    pub locked_accounts: Vec<AccountId>,
353    /// IDs of committed transactions.
354    pub committed_transactions: Vec<TransactionId>,
355}
356
357impl SyncSummary {
358    pub fn new(
359        block_num: BlockNumber,
360        new_public_notes: Vec<NoteId>,
361        new_private_notes: Vec<NoteId>,
362        committed_notes: Vec<NoteId>,
363        consumed_notes: Vec<NoteId>,
364        updated_accounts: Vec<AccountId>,
365        locked_accounts: Vec<AccountId>,
366        committed_transactions: Vec<TransactionId>,
367    ) -> Self {
368        Self {
369            block_num,
370            new_public_notes,
371            new_private_notes,
372            committed_notes,
373            consumed_notes,
374            updated_accounts,
375            locked_accounts,
376            committed_transactions,
377        }
378    }
379
380    pub fn new_empty(block_num: BlockNumber) -> Self {
381        Self {
382            block_num,
383            new_public_notes: vec![],
384            new_private_notes: vec![],
385            committed_notes: vec![],
386            consumed_notes: vec![],
387            updated_accounts: vec![],
388            locked_accounts: vec![],
389            committed_transactions: vec![],
390        }
391    }
392
393    pub fn is_empty(&self) -> bool {
394        self.new_public_notes.is_empty()
395            && self.new_private_notes.is_empty()
396            && self.committed_notes.is_empty()
397            && self.consumed_notes.is_empty()
398            && self.updated_accounts.is_empty()
399            && self.locked_accounts.is_empty()
400            && self.committed_transactions.is_empty()
401    }
402
403    pub fn combine_with(&mut self, mut other: Self) {
404        self.block_num = max(self.block_num, other.block_num);
405        self.new_public_notes.append(&mut other.new_public_notes);
406        self.new_private_notes.append(&mut other.new_private_notes);
407        self.committed_notes.append(&mut other.committed_notes);
408        self.consumed_notes.append(&mut other.consumed_notes);
409        self.updated_accounts.append(&mut other.updated_accounts);
410        self.locked_accounts.append(&mut other.locked_accounts);
411        self.committed_transactions.append(&mut other.committed_transactions);
412    }
413}
414
415impl Serializable for SyncSummary {
416    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
417        self.block_num.write_into(target);
418        self.new_public_notes.write_into(target);
419        self.new_private_notes.write_into(target);
420        self.committed_notes.write_into(target);
421        self.consumed_notes.write_into(target);
422        self.updated_accounts.write_into(target);
423        self.locked_accounts.write_into(target);
424        self.committed_transactions.write_into(target);
425    }
426}
427
428impl Deserializable for SyncSummary {
429    fn read_from<R: miden_tx::utils::serde::ByteReader>(
430        source: &mut R,
431    ) -> Result<Self, DeserializationError> {
432        let block_num = BlockNumber::read_from(source)?;
433        let new_public_notes = Vec::<NoteId>::read_from(source)?;
434        let new_private_notes = Vec::<NoteId>::read_from(source)?;
435        let committed_notes = Vec::<NoteId>::read_from(source)?;
436        let consumed_notes = Vec::<NoteId>::read_from(source)?;
437        let updated_accounts = Vec::<AccountId>::read_from(source)?;
438        let locked_accounts = Vec::<AccountId>::read_from(source)?;
439        let committed_transactions = Vec::<TransactionId>::read_from(source)?;
440
441        Ok(Self {
442            block_num,
443            new_public_notes,
444            new_private_notes,
445            committed_notes,
446            consumed_notes,
447            updated_accounts,
448            locked_accounts,
449            committed_transactions,
450        })
451    }
452}