Skip to main content

miden_node_store/state/view/
sync.rs

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