1use 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
95impl<AUTH> Client<AUTH>
97where
98 AUTH: TransactionAuthenticator + Sync + 'static,
99{
100 pub async fn get_sync_height(&self) -> Result<BlockNumber, ClientError> {
105 self.store.get_sync_height().await.map_err(Into::into)
106 }
107
108 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 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 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 state_sync.run_apply_hooks(&state_sync_update).await?;
140
141 info!("Applying changes to the store.");
142
143 self.store
145 .apply_state_sync(state_sync_update)
146 .await
147 .map_err(ClientError::StoreError)?;
148
149 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 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 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, ¬e_tags).await?;
176 self.store.update_note_transport_cursor(new_cursor).await?;
177 Ok(ids)
178 }
179
180 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 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 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 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 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 Vec::new()
272 } else {
273 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 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 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 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#[derive(Debug, PartialEq)]
334pub struct SyncSummary {
335 pub block_num: BlockNumber,
337 pub new_public_notes: Vec<NoteId>,
339 pub new_private_notes: Vec<NoteId>,
345 pub committed_notes: Vec<NoteId>,
347 pub consumed_notes: Vec<NoteId>,
349 pub updated_accounts: Vec<AccountId>,
351 pub locked_accounts: Vec<AccountId>,
353 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}