Skip to main content

miden_node_store/state/view/
sync.rs

1use std::ops::RangeInclusive;
2
3use miden_node_tracing::instrument;
4use miden_node_utils::limiter::MAX_RESPONSE_PAYLOAD_BYTES;
5use miden_protocol::account::AccountId;
6use miden_protocol::block::{BlockHeader, BlockNumber, BlockSignatures};
7use miden_protocol::crypto::merkle::mmr::{Forest, MmrDelta, MmrProof};
8
9use super::StateView;
10use crate::db::queries::{
11    AccountStorageMapValuesPaged,
12    AccountVaultAssets,
13    NoteSyncMulti,
14    NullifiersByPrefix,
15    StorageMapValuesPage,
16    TransactionsRecords,
17};
18use crate::db::{
19    AccountVaultValue,
20    NoteSyncUpdate,
21    NullifierInfo,
22    default_storage_map_entries_limit,
23};
24use crate::errors::{DatabaseError, NoteSyncError, StateSyncError};
25
26// STATE SYNCHRONIZATION ENDPOINTS
27// ================================================================================================
28
29impl StateView {
30    /// Returns the complete transaction records for the specified accounts within the specified
31    /// block range, including state commitments and note IDs.
32    ///
33    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
34    /// view's chain tip.
35    pub async fn sync_transactions(
36        &self,
37        account_ids: Vec<AccountId>,
38        block_range: RangeInclusive<BlockNumber>,
39    ) -> Result<(BlockNumber, Vec<crate::db::TransactionRecord>), DatabaseError> {
40        let block_range = self.scope_range(block_range)?;
41        let query = TransactionsRecords::new(account_ids, block_range.scoped_end());
42        let page = self.db.page(query, block_range.start()).await?;
43        Ok((page.last_block_included(block_range.end()), page.items))
44    }
45
46    /// Returns the chain MMR delta and the block header at the range's end for the specified
47    /// block range.
48    ///
49    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
50    /// view's chain tip.
51    #[instrument(level = "debug", err(level = "debug"))]
52    pub async fn sync_chain_mmr(
53        &self,
54        block_range: RangeInclusive<BlockNumber>,
55    ) -> Result<(MmrDelta, BlockHeader, BlockSignatures), StateSyncError> {
56        let block_range = self.scope_range(block_range)?;
57
58        let block_from = block_range.start();
59        let block_to = block_range.end();
60
61        // The scoped range's end is committed (at or below this view's tip), so its header must
62        // exist in the database.
63        let (block_header, signatures) = self
64            .db
65            .select_block_header_and_signatures_by_block_num(block_range.scoped_end())
66            .await?
67            .expect("the range-end header should exist in the database");
68
69        if block_from == block_to {
70            return Ok((
71                MmrDelta {
72                    forest: Forest::new(block_from.as_usize()).expect("block index fits in u32"),
73                    data: vec![],
74                },
75                block_header,
76                signatures,
77            ));
78        }
79
80        // Important notes about the boundary conditions:
81        //
82        // - The Mmr forest is 1-indexed whereas the block number is 0-indexed. The Mmr root
83        //   contained in the block header always lag behind by one block, this is because the Mmr
84        //   leaves are hashes of block headers, and we can't have self-referential hashes. These
85        //   two points cancel out and don't require adjusting.
86        // - Mmr::get_delta is inclusive, whereas the sync request block_from is defined to be the
87        //   last block already present in the caller's MMR. The delta should therefore start at the
88        //   next block, so the from_forest has to be adjusted with a +1.
89        let from_forest = (block_from + 1).as_usize();
90        let to_forest = block_to.as_usize();
91
92        let mmr_delta = self
93            .blockchain()
94            .as_mmr()
95            .get_delta(
96                Forest::new(from_forest).expect("from_forest fits in u32"),
97                Forest::new(to_forest).expect("to_forest fits in u32"),
98            )
99            .map_err(StateSyncError::FailedToBuildMmrDelta)?;
100
101        Ok((mmr_delta, block_header, signatures))
102    }
103
104    /// Loads data to synchronize a client's notes.
105    ///
106    /// Returns as many blocks with matching notes as fit within the response payload limit
107    /// ([`MAX_RESPONSE_PAYLOAD_BYTES`]).
108    /// Each block includes its header and MMR proof at forest `block_range.end() + 1`.
109    ///
110    /// Also returns the last block number checked. If this equals `block_range.end()`, the
111    /// sync is complete.
112    ///
113    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
114    /// view's chain tip.
115    #[instrument(level = "debug", err(level = "debug"))]
116    pub async fn sync_notes(
117        &self,
118        note_tags: Vec<u32>,
119        block_range: RangeInclusive<BlockNumber>,
120    ) -> Result<(Vec<(NoteSyncUpdate, MmrProof)>, BlockNumber), NoteSyncError> {
121        let block_range = self.scope_range(block_range)?;
122
123        let block_end = block_range.end();
124        // The MMR at forest N contains proofs for blocks 0..N-1, so we use block_end + 1 to include
125        // the proof for block_end. SAFETY: block_end <= this view's tip (checked above), and the
126        // view's blockchain MMR always has at least tip + 1 leaves.
127        let mmr_checkpoint = block_end + 1;
128
129        let query =
130            NoteSyncMulti::new(note_tags, block_range.scoped_end(), MAX_RESPONSE_PAYLOAD_BYTES);
131        let page = self.db.page(query, block_range.start()).await?;
132        let last_block_included = page.last_block_included(block_end);
133
134        let mut results = Vec::new();
135
136        for note_sync in page.items {
137            let mmr_proof =
138                self.blockchain().open_at(note_sync.block_header.block_num(), mmr_checkpoint)?;
139            results.push((note_sync, mmr_proof));
140        }
141
142        Ok((results, last_block_included))
143    }
144
145    /// Returns nullifiers matching the given prefixes that were created within a block range.
146    ///
147    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
148    /// view's chain tip.
149    pub async fn sync_nullifiers(
150        &self,
151        prefix_len: u32,
152        nullifier_prefixes: Vec<u32>,
153        block_range: RangeInclusive<BlockNumber>,
154    ) -> Result<(Vec<NullifierInfo>, BlockNumber), DatabaseError> {
155        let block_range = self.scope_range(block_range)?;
156        assert_eq!(prefix_len, 16, "Only 16-bit prefixes are supported");
157
158        let nullifier_prefixes =
159            nullifier_prefixes.into_iter().map(|prefix| prefix as u16).collect::<Vec<_>>();
160        let query =
161            NullifiersByPrefix::new(prefix_len as u8, nullifier_prefixes, block_range.scoped_end());
162        let page = self.db.page(query, block_range.start()).await?;
163        let last_block_included = page.last_block_included(block_range.end());
164        Ok((page.items, last_block_included))
165    }
166
167    // ACCOUNT STATE SYNCHRONIZATION
168    // --------------------------------------------------------------------------------------------
169
170    /// Returns account vault updates for specified account within a block range.
171    ///
172    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
173    /// view's chain tip, and [`RangeBelowRetention`](crate::errors::RangeBelowRetention) if the
174    /// range ends below the account history retention window.
175    pub async fn sync_account_vault(
176        &self,
177        account_id: AccountId,
178        block_range: RangeInclusive<BlockNumber>,
179    ) -> Result<(BlockNumber, Vec<AccountVaultValue>), DatabaseError> {
180        let block_range = self.scope_retained_range(block_range)?;
181        let query = AccountVaultAssets::new(account_id, block_range.scoped_end());
182        let page = self.db.page(query, block_range.start()).await?;
183        Ok((page.last_block_included(block_range.end()), page.items))
184    }
185
186    /// Returns storage map values for syncing within a block range.
187    ///
188    /// Returns [`RangeBeyondTip`](crate::errors::RangeBeyondTip) if the range extends beyond this
189    /// view's chain tip, and [`RangeBelowRetention`](crate::errors::RangeBelowRetention) if the
190    /// range ends below the account history retention window.
191    pub async fn sync_account_storage_maps(
192        &self,
193        account_id: AccountId,
194        block_range: RangeInclusive<BlockNumber>,
195    ) -> Result<StorageMapValuesPage, DatabaseError> {
196        let block_range = self.scope_retained_range(block_range)?;
197        let query = AccountStorageMapValuesPaged::new(
198            account_id,
199            block_range.scoped_end(),
200            default_storage_map_entries_limit(),
201        );
202        let page = self.db.page(query, block_range.start()).await?;
203        Ok(StorageMapValuesPage {
204            last_block_included: page.last_block_included(block_range.end()),
205            values: page.items,
206        })
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use miden_node_utils::fee::{test_fee_params, test_protocol_config};
213    use miden_protocol::block::{BlockBody, SignedBlock, ValidatorConfig};
214    use miden_protocol::crypto::merkle::mmr::Mmr;
215    use miden_protocol::testing::account_id::ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET;
216    use miden_protocol::testing::random_secret_key::random_secret_key;
217    use miden_protocol::transaction::OrderedTransactionHeaders;
218
219    use super::*;
220    use crate::GenesisState;
221    use crate::db::HISTORICAL_BLOCK_RETENTION;
222    use crate::errors::RangeBelowRetention;
223    use crate::state::{BlockWriter, State};
224
225    /// Applies `count` empty blocks on top of the current chain tip.
226    async fn apply_empty_blocks(state: &State, writer: &mut BlockWriter, count: u32) {
227        let view = state.view();
228        let mut mmr = Mmr::new();
229        let mut parent = None;
230        for height in 0..=view.tip().as_u32() {
231            let (header, _) = view.get_block_header(Some(height.into()), false).await.unwrap();
232            let header = header.expect("block header should exist");
233            mmr.add(header.commitment()).unwrap();
234            parent = Some(header);
235        }
236        drop(view);
237        let mut parent = parent.expect("chain should have a parent block");
238
239        for _ in 0..count {
240            let body = BlockBody::new(
241                Vec::new(),
242                Vec::new(),
243                Vec::new(),
244                OrderedTransactionHeaders::new_unchecked(Vec::new()),
245            )
246            .unwrap();
247            let header = BlockHeader::new(
248                parent.commitment(),
249                parent.block_num().child(),
250                mmr.peaks().hash_peaks(),
251                parent.account_root(),
252                parent.nullifier_root(),
253                body.compute_block_note_tree().root(),
254                body.transaction_commitment(),
255                parent.validator_config().clone(),
256                parent.fee_parameters().clone(),
257                parent.protocol_config_commitment(),
258                None,
259                parent.timestamp() + 1,
260            );
261            let block = SignedBlock::new_unchecked(
262                header.clone(),
263                body,
264                BlockSignatures::new(Vec::new()).unwrap(),
265            );
266            writer.apply_block(block, None).await.expect("empty block should apply");
267            mmr.add(header.commitment()).unwrap();
268            parent = header;
269        }
270    }
271
272    async fn bootstrap_store(path: &std::path::Path) {
273        let signer = random_secret_key();
274        let genesis_block = GenesisState::new(
275            vec![],
276            test_fee_params(),
277            1,
278            ValidatorConfig::new(vec![signer.public_key()], 1)
279                .expect("validator config should be valid"),
280            test_protocol_config(),
281        )
282        .into_block()
283        .expect("genesis block should be created");
284
285        State::bootstrap(genesis_block, path).await.expect("store should bootstrap");
286    }
287
288    /// Account history rows are pruned once they fall out of the retention window. A sync range
289    /// that ends below the window can miss updates, so it must be rejected instead of answered.
290    #[tokio::test(flavor = "multi_thread")]
291    async fn account_syncs_reject_ranges_that_end_below_the_retention_window() {
292        let data_directory = tempfile::tempdir().expect("tempdir should be created");
293        bootstrap_store(data_directory.path()).await;
294        let (state, mut writer, _proof_writer) = State::for_tests(data_directory.path()).await;
295        apply_empty_blocks(&state, &mut writer, HISTORICAL_BLOCK_RETENTION + 10).await;
296
297        let view = state.view();
298        let tip = *view.tip();
299        let oldest_retained = BlockNumber::from(tip.as_u32() - HISTORICAL_BLOCK_RETENTION);
300        let below_window = BlockNumber::from(oldest_retained.as_u32() - 1);
301        let account_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();
302
303        let vault = view.sync_account_vault(account_id, BlockNumber::GENESIS..=below_window).await;
304        assert!(
305            matches!(
306                vault,
307                Err(DatabaseError::RangeBelowRetention(RangeBelowRetention {
308                    oldest_retained: oldest,
309                    block_to,
310                })) if oldest == oldest_retained && block_to == below_window
311            ),
312            "vault sync below the retention window must fail, got {vault:?}"
313        );
314
315        let storage = view
316            .sync_account_storage_maps(account_id, BlockNumber::GENESIS..=below_window)
317            .await;
318        assert!(
319            matches!(
320                storage,
321                Err(DatabaseError::RangeBelowRetention(RangeBelowRetention {
322                    oldest_retained: oldest,
323                    block_to,
324                })) if oldest == oldest_retained && block_to == below_window
325            ),
326            "storage map sync below the retention window must fail, got {storage:?}"
327        );
328
329        // A range that ends at the oldest retained block is still complete.
330        let (last_block, updates) = view
331            .sync_account_vault(account_id, BlockNumber::GENESIS..=oldest_retained)
332            .await
333            .expect("vault sync at the retention boundary should succeed");
334        assert_eq!(last_block, oldest_retained);
335        assert!(updates.is_empty());
336        view.sync_account_storage_maps(account_id, BlockNumber::GENESIS..=oldest_retained)
337            .await
338            .expect("storage map sync at the retention boundary should succeed");
339    }
340}