miden_client/sync/mod.rs
1//! Provides the client APIs for synchronizing the client's local state with the Miden network. It
2//! 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 a
19//! summary of the new block number along with lists of received, committed, and consumed note IDs,
20//! 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 `committed_note_updates` and
56//! `consumed_note_updates`) to understand how the sync data is processed and applied to the local
57//! store.
58
59use alloc::collections::BTreeSet;
60use alloc::format;
61use alloc::sync::Arc;
62use alloc::vec::Vec;
63use core::cmp::max;
64
65use miden_protocol::account::AccountId;
66use miden_protocol::block::BlockNumber;
67use miden_protocol::crypto::merkle::mmr::{InOrderIndex, PartialMmr};
68use miden_protocol::note::NoteId;
69use miden_protocol::transaction::TransactionId;
70use miden_tx::auth::TransactionAuthenticator;
71use miden_tx::utils::serde::{Deserializable, DeserializationError, Serializable};
72use tracing::{debug, info, warn};
73
74use crate::pswap::PswapChainObserver;
75use crate::store::{NoteFilter, TransactionFilter};
76use crate::{Client, ClientError};
77mod block_header;
78
79mod tag;
80pub use tag::{NoteTagRecord, NoteTagSource};
81
82mod note_observer;
83pub use note_observer::NoteObserver;
84
85mod state_sync;
86pub(crate) use state_sync::block_num_from_forest;
87pub use state_sync::{ChainSyncData, NoteUpdateAction, OnNoteReceived, StateSync, StateSyncInput};
88
89mod state_sync_update;
90pub use state_sync_update::{
91 AccountUpdates,
92 PartialBlockchainUpdates,
93 PublicAccountUpdate,
94 StateSyncUpdate,
95 TransactionUpdateTracker,
96};
97
98/// Untracks the given block leaves from `partial_mmr`, returning the authentication-node indices
99/// that are no longer needed by any remaining tracked leaf.
100///
101/// Untracking a leaf frees an inner node only once no other tracked leaf still needs it, so the
102/// returned indices are exactly the nodes that became removable.
103fn untrack_blocks(
104 partial_mmr: &mut PartialMmr,
105 block_positions: impl IntoIterator<Item = usize>,
106) -> Vec<InOrderIndex> {
107 block_positions
108 .into_iter()
109 .flat_map(|block_pos| partial_mmr.untrack(block_pos))
110 .map(|(index, _)| index)
111 .collect()
112}
113
114/// Client synchronization methods.
115impl<AUTH> Client<AUTH>
116where
117 AUTH: TransactionAuthenticator + Sync + 'static,
118{
119 // SYNC STATE
120 // --------------------------------------------------------------------------------------------
121
122 /// Returns the block number of the last state sync block.
123 pub async fn get_sync_height(&self) -> Result<BlockNumber, ClientError> {
124 self.store.get_sync_height().await.map_err(Into::into)
125 }
126
127 /// Syncs the client's on-chain state with the current state of the Miden network and returns a
128 /// [`SyncSummary`] corresponding to the local state update.
129 ///
130 /// Does **not** fetch private notes from the Note Transport Layer. Use [`Client::sync_state`]
131 /// for the combined sync, or call [`Client::sync_note_transport`] separately.
132 ///
133 /// Fetches everything from the node first ([`Client::fetch_chain_updates`] and
134 /// [`StateSync::fetch_nullifiers`]), then applies the result with
135 /// [`Client::apply_chain_updates`], which also caches the partial MMR and prunes irrelevant
136 /// blocks according to the configured cadence.
137 pub async fn sync_chain(&mut self) -> Result<SyncSummary, ClientError> {
138 self.ensure_genesis_in_place().await?;
139 self.ensure_rpc_limits_in_place().await?;
140
141 let state_sync = self.state_sync();
142 let mut chain_sync_data = self.fetch_chain_updates(&state_sync).await?;
143 state_sync.derive_state_updates(&mut chain_sync_data).await?;
144 state_sync.fetch_nullifiers(&mut chain_sync_data).await?;
145
146 self.apply_chain_updates(&state_sync, chain_sync_data).await
147 }
148
149 /// Fetches the node's view of everything that changed since the client's chain tip, without
150 /// storing anything or modifying the partial MMR.
151 ///
152 /// Builds the default sync input and runs [`StateSync::fetch_state`]. The state updates must be
153 /// derived with [`StateSync::derive_state_updates`]. The nullifier check is not part of this:
154 /// run [`StateSync::fetch_nullifiers`] on the result before applying it, so it can also cover
155 /// transport-delivered notes another sync path fetched in the same call.
156 pub async fn fetch_chain_updates(
157 &self,
158 state_sync: &StateSync,
159 ) -> Result<ChainSyncData, ClientError> {
160 let input = self.build_sync_input().await?;
161 let block_from = block_num_from_forest(&self.get_current_partial_mmr().await?)?;
162
163 state_sync.fetch_state(block_from, input).await
164 }
165
166 /// Builds the [`StateSync`] driving one chain sync.
167 ///
168 /// Each `NoteObserver` owns its own per-sync state, so this must be called once per sync rather
169 /// than shared; `with_note_observer` just attaches it.
170 fn state_sync(&self) -> StateSync {
171 StateSync::new(self.rpc_api.clone(), Arc::new(self.note_screener()), self.tx_discard_delta)
172 .with_note_observer(Arc::new(PswapChainObserver::new(self.store.clone())))
173 }
174
175 /// Verifies fetched chain data against the client's partial MMR and saves the resulting update
176 /// to the store.
177 ///
178 /// [`StateSync::derive_state_updates`] and [`StateSync::fetch_nullifiers`] must have run on the
179 /// data first. Also caches the partial MMR and prunes irrelevant blocks.
180 ///
181 /// # Errors
182 ///
183 /// Returns an error if the client no longer starts where the data was fetched from, which means
184 /// another sync advanced the store in between and the data is stale.
185 pub async fn apply_chain_updates(
186 &mut self,
187 state_sync: &StateSync,
188 chain_sync_data: ChainSyncData,
189 ) -> Result<SyncSummary, ClientError> {
190 let mut partial_mmr = self.get_current_partial_mmr().await?;
191
192 let block_from = block_num_from_forest(&partial_mmr)?;
193 if block_from != chain_sync_data.block_from {
194 return Err(ClientError::ChainValidationError(format!(
195 "chain sync chain_sync_data starts at block {} but the client is at block {block_from}",
196 chain_sync_data.block_from
197 )));
198 }
199
200 let state_sync_update = StateSync::build_update(chain_sync_data, &mut partial_mmr)?;
201
202 let sync_summary: SyncSummary = (&state_sync_update).into();
203 debug!(sync_summary = ?sync_summary, "Sync summary computed");
204
205 // Post-sync observer hooks; run before persisting. Per-observer errors are logged, not
206 // propagated.
207 state_sync.run_apply_hooks(&state_sync_update).await?;
208
209 info!("Applying changes to the store.");
210
211 // Apply received and computed updates to the store
212 self.store
213 .apply_state_sync(state_sync_update)
214 .await
215 .map_err(ClientError::StoreError)?;
216
217 // Cache MMR so pruning can reuse in-memory MMR.
218 self.cache_partial_mmr(partial_mmr).await?;
219
220 self.maybe_untrack_and_prune_irrelevant_blocks().await?;
221
222 Ok(sync_summary)
223 }
224
225 /// Fetches private notes from the Note Transport Layer for the tracked note tags.
226 ///
227 /// Returns the IDs of notes imported in this call. No-op (returns an empty vec) if note
228 /// transport is disabled.
229 pub async fn sync_note_transport(&mut self) -> Result<Vec<NoteId>, ClientError> {
230 if !self.is_note_transport_enabled() {
231 return Ok(Vec::new());
232 }
233 self.ensure_genesis_in_place().await?;
234
235 let note_transport_update = self.fetch_note_transport_updates().await?;
236 let (imported_ids, _) = self.apply_note_transport_update(note_transport_update).await?;
237 Ok(imported_ids)
238 }
239
240 /// Runs the full client sync: private notes from the Note Transport Layer and the client's
241 /// on-chain state with the Miden node.
242 ///
243 /// The NTL and the node are fetched concurrently, and everything that writes runs sequentially
244 /// afterwards:
245 ///
246 /// 1. Concurrently: the note transport fetch and [`Client::fetch_chain_updates`]. Only node and
247 /// NTL calls happen here, which is all that benefits from overlapping.
248 /// 2. The transport writes, when its fetch succeeded, whose records are then tracked in the
249 /// chain sync's note updates.
250 /// 3. [`StateSync::derive_state_updates`], which screens the node's notes against the store —
251 /// hence after step 2, so a transport-delivered note is recognised rather than discarded —
252 /// and applies a commitment reported this sync to those records.
253 /// 4. [`StateSync::fetch_nullifiers`], covering the tracked notes *and* the transport-delivered
254 /// ones, so a note delivered and consumed in the same window is reported as consumed by this
255 /// call.
256 /// 5. The chain update, written last: a nullified transport-delivered note is saved as an
257 /// update to the row step 2 inserts.
258 ///
259 /// A transport failure is logged and the chain sync continues without it, leaving the transport
260 /// cursor for the next call to retry. Before step 2 but the relay outbox, which
261 /// [`Client::flush_relay_outbox`] persists during the fetch and the next sync retries.
262 pub async fn sync_state(&mut self) -> Result<SyncSummary, ClientError> {
263 // Both fetch phases need genesis in place, and connecting here means the two concurrent
264 // futures never race on the RPC client's lazy connect.
265 self.ensure_genesis_in_place().await?;
266 self.ensure_rpc_limits_in_place().await?;
267
268 let state_sync = self.state_sync();
269 let (note_transport_update, chain_sync_data) = futures::join!(
270 self.fetch_note_transport_updates(),
271 self.fetch_chain_updates(&state_sync),
272 );
273
274 // An NTL failure does not end the sync
275 let (new_private_notes, imported_notes) = match note_transport_update {
276 Ok(note_transport_update) => {
277 self.apply_note_transport_update(note_transport_update).await?
278 },
279 Err(err) => {
280 warn!(?err, "note transport fetch failed; syncing the chain without it");
281 (Vec::new(), Vec::new())
282 },
283 };
284
285 let mut chain_sync_data = chain_sync_data?;
286
287 // The chain sync built its note updates from a store snapshot taken before the import, so
288 // the imported records are added here. Without them this sync has no record to apply its
289 // verdicts to, and a note committed within this sync's own block range stays expected.
290 let imported_notes =
291 self.get_input_notes(NoteFilter::DetailsCommitments(imported_notes)).await?;
292 chain_sync_data.note_updates.track_existing_input_notes(imported_notes);
293
294 state_sync.derive_state_updates(&mut chain_sync_data).await?;
295 state_sync.fetch_nullifiers(&mut chain_sync_data).await?;
296
297 let mut summary = self.apply_chain_updates(&state_sync, chain_sync_data).await?;
298 summary.new_private_notes = new_private_notes;
299 Ok(summary)
300 }
301
302 /// Builds a default [`StateSyncInput`] from the current client state.
303 ///
304 /// This includes all tracked account headers, all unique note tags, all unspent input and
305 /// output notes, and all uncommitted transactions.
306 pub async fn build_sync_input(&self) -> Result<StateSyncInput, ClientError> {
307 let accounts = self
308 .store
309 .get_account_headers()
310 .await?
311 .into_iter()
312 .map(|(header, _status)| header)
313 .collect();
314
315 let note_tags = self.store.get_unique_note_tags().await?;
316
317 let input_notes = self.store.get_input_notes(NoteFilter::Unspent).await?;
318 let output_notes = self.store.get_output_notes(NoteFilter::Unspent).await?;
319
320 let uncommitted_transactions =
321 self.store.get_transactions(TransactionFilter::Uncommitted).await?;
322
323 Ok(StateSyncInput {
324 accounts,
325 note_tags,
326 input_notes,
327 output_notes,
328 uncommitted_transactions,
329 })
330 }
331
332 /// Applies the state sync update to the store and prunes irrelevant blocks according to the
333 /// configured cadence.
334 ///
335 /// See [`crate::Store::apply_state_sync()`] for what the update implies.
336 pub async fn apply_state_sync(&mut self, update: StateSyncUpdate) -> Result<(), ClientError> {
337 self.store.apply_state_sync(update).await?;
338
339 self.maybe_untrack_and_prune_irrelevant_blocks().await?;
340
341 Ok(())
342 }
343
344 /// Prunes irrelevant blocks and their MMR authentication nodes according to the configured
345 /// cadence.
346 async fn maybe_untrack_and_prune_irrelevant_blocks(&mut self) -> Result<(), ClientError> {
347 let Some(interval) = self.irrelevant_block_prune_interval else {
348 return Ok(());
349 };
350
351 let sync_height = self.store.get_sync_height().await?;
352
353 if let Some(last_prune_height) = self.last_irrelevant_block_prune_sync_height
354 && sync_height < last_prune_height + interval
355 {
356 return Ok(());
357 }
358
359 self.untrack_and_prune_irrelevant_blocks().await?;
360 self.last_irrelevant_block_prune_sync_height = Some(sync_height);
361
362 Ok(())
363 }
364
365 /// Prunes irrelevant block data from the store.
366 ///
367 /// Identifies tracked blocks whose input notes have all been consumed, untracks them from the
368 /// `PartialMmr` to determine which authentication nodes are no longer needed, then delegates to
369 /// [`Store::untrack_and_prune_irrelevant_blocks`] to atomically remove the stale nodes, mark
370 /// the blocks as irrelevant, and delete irrelevant block headers. Any caller of this function
371 /// should've cached the `PartialMmr` beforehand.
372 async fn untrack_and_prune_irrelevant_blocks(&mut self) -> Result<(), ClientError> {
373 let tracked_blocks = self.store.get_tracked_block_header_numbers().await?;
374 let to_untrack: Vec<usize> = if tracked_blocks.is_empty() {
375 // Do not early-return: even without blocks to untrack, old irrelevant tip headers may
376 // need pruning.
377 Vec::new()
378 } else {
379 // Blocks that still have at least one unspent note need to stay tracked.
380 let unspent_notes = self.store.get_input_notes(NoteFilter::Unspent).await?;
381 let live_blocks: BTreeSet<usize> = unspent_notes
382 .iter()
383 .filter_map(|n| n.inclusion_proof().map(|p| p.location().block_num().as_usize()))
384 .collect();
385
386 tracked_blocks.difference(&live_blocks).copied().collect()
387 };
388
389 let mut blocks_to_untrack = Vec::new();
390 let mut nodes_to_remove = Vec::new();
391 let mut updated_partial_mmr = None;
392
393 if !to_untrack.is_empty() {
394 // Rebuild the PartialMmr and untrack each block to collect the authentication node
395 // indices that are no longer needed by any remaining tracked leaf.
396 let mut partial_mmr = self.get_current_partial_mmr().await?;
397 nodes_to_remove = untrack_blocks(&mut partial_mmr, to_untrack.iter().copied());
398
399 blocks_to_untrack = to_untrack
400 .iter()
401 .map(|&b| BlockNumber::from(u32::try_from(b).expect("block number fits in u32")))
402 .collect();
403 updated_partial_mmr = Some(partial_mmr);
404 }
405
406 // Store deletes stale auth nodes, marks blocks as irrelevant, and removes irrelevant block
407 // headers. Old irrelevant tip headers may still need pruning.
408 self.store
409 .untrack_and_prune_irrelevant_blocks(&blocks_to_untrack, &nodes_to_remove)
410 .await?;
411
412 if let Some(partial_mmr) = updated_partial_mmr {
413 self.cache_partial_mmr(partial_mmr).await?;
414 }
415
416 Ok(())
417 }
418
419 /// Ensures that the RPC limits are set in the RPC client. If not already cached, fetches them
420 /// from the node and persists them in the store.
421 pub async fn ensure_rpc_limits_in_place(&mut self) -> Result<(), ClientError> {
422 if self.rpc_api.has_rpc_limits().is_some() {
423 return Ok(());
424 }
425
426 let limits = self.rpc_api.get_rpc_limits().await?;
427 self.store.set_rpc_limits(limits).await?;
428 Ok(())
429 }
430}
431
432// SYNC SUMMARY
433// ================================================================================================
434
435/// Contains stats about the sync operation.
436#[derive(Debug, PartialEq)]
437pub struct SyncSummary {
438 /// Block number up to which the client has been synced.
439 pub block_num: BlockNumber,
440 /// IDs of new public notes that the client has received.
441 pub new_public_notes: Vec<NoteId>,
442 /// IDs of private notes imported from the Note Transport Layer in this sync. They are still
443 /// `Expected` until observed on-chain.
444 ///
445 /// Only populated by [`Client::sync_state`]; [`Client::sync_chain`] always leaves this empty
446 /// because it does not touch the Note Transport Layer.
447 pub new_private_notes: Vec<NoteId>,
448 /// IDs of tracked notes that have been committed.
449 pub committed_notes: Vec<NoteId>,
450 /// IDs of notes that have been consumed.
451 pub consumed_notes: Vec<NoteId>,
452 /// IDs of on-chain accounts that have been updated.
453 pub updated_accounts: Vec<AccountId>,
454 /// IDs of private accounts that have been locked.
455 pub locked_accounts: Vec<AccountId>,
456 /// IDs of committed transactions.
457 pub committed_transactions: Vec<TransactionId>,
458}
459
460impl SyncSummary {
461 pub fn new(
462 block_num: BlockNumber,
463 new_public_notes: Vec<NoteId>,
464 new_private_notes: Vec<NoteId>,
465 committed_notes: Vec<NoteId>,
466 consumed_notes: Vec<NoteId>,
467 updated_accounts: Vec<AccountId>,
468 locked_accounts: Vec<AccountId>,
469 committed_transactions: Vec<TransactionId>,
470 ) -> Self {
471 Self {
472 block_num,
473 new_public_notes,
474 new_private_notes,
475 committed_notes,
476 consumed_notes,
477 updated_accounts,
478 locked_accounts,
479 committed_transactions,
480 }
481 }
482
483 pub fn new_empty(block_num: BlockNumber) -> Self {
484 Self {
485 block_num,
486 new_public_notes: vec![],
487 new_private_notes: vec![],
488 committed_notes: vec![],
489 consumed_notes: vec![],
490 updated_accounts: vec![],
491 locked_accounts: vec![],
492 committed_transactions: vec![],
493 }
494 }
495
496 pub fn is_empty(&self) -> bool {
497 self.new_public_notes.is_empty()
498 && self.new_private_notes.is_empty()
499 && self.committed_notes.is_empty()
500 && self.consumed_notes.is_empty()
501 && self.updated_accounts.is_empty()
502 && self.locked_accounts.is_empty()
503 && self.committed_transactions.is_empty()
504 }
505
506 pub fn combine_with(&mut self, mut other: Self) {
507 self.block_num = max(self.block_num, other.block_num);
508 self.new_public_notes.append(&mut other.new_public_notes);
509 self.new_private_notes.append(&mut other.new_private_notes);
510 self.committed_notes.append(&mut other.committed_notes);
511 self.consumed_notes.append(&mut other.consumed_notes);
512 self.updated_accounts.append(&mut other.updated_accounts);
513 self.locked_accounts.append(&mut other.locked_accounts);
514 self.committed_transactions.append(&mut other.committed_transactions);
515 }
516}
517
518impl Serializable for SyncSummary {
519 fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
520 self.block_num.write_into(target);
521 self.new_public_notes.write_into(target);
522 self.new_private_notes.write_into(target);
523 self.committed_notes.write_into(target);
524 self.consumed_notes.write_into(target);
525 self.updated_accounts.write_into(target);
526 self.locked_accounts.write_into(target);
527 self.committed_transactions.write_into(target);
528 }
529}
530
531impl Deserializable for SyncSummary {
532 fn read_from<R: miden_tx::utils::serde::ByteReader>(
533 source: &mut R,
534 ) -> Result<Self, DeserializationError> {
535 let block_num = BlockNumber::read_from(source)?;
536 let new_public_notes = Vec::<NoteId>::read_from(source)?;
537 let new_private_notes = Vec::<NoteId>::read_from(source)?;
538 let committed_notes = Vec::<NoteId>::read_from(source)?;
539 let consumed_notes = Vec::<NoteId>::read_from(source)?;
540 let updated_accounts = Vec::<AccountId>::read_from(source)?;
541 let locked_accounts = Vec::<AccountId>::read_from(source)?;
542 let committed_transactions = Vec::<TransactionId>::read_from(source)?;
543
544 Ok(Self {
545 block_num,
546 new_public_notes,
547 new_private_notes,
548 committed_notes,
549 consumed_notes,
550 updated_accounts,
551 locked_accounts,
552 committed_transactions,
553 })
554 }
555}