Skip to main content

miden_client/sync/
block_header.rs

1use alloc::sync::Arc;
2use alloc::vec::Vec;
3
4use miden_protocol::Word;
5use miden_protocol::block::{BlockHeader, BlockNumber};
6use miden_protocol::crypto::merkle::MerklePath;
7use miden_protocol::crypto::merkle::mmr::{Forest, InOrderIndex, MmrPeaks, PartialMmr};
8use tracing::warn;
9
10use crate::rpc::NodeRpcClient;
11use crate::store::{BlockRelevance, StoreError};
12use crate::{Client, ClientError};
13
14/// Network information management methods.
15impl<AUTH> Client<AUTH> {
16    /// Retrieves a block header by its block number from the store.
17    ///
18    /// Returns `None` if the block header is not found in the store.
19    pub async fn get_block_header_by_num(
20        &self,
21        block_num: BlockNumber,
22    ) -> Result<Option<(BlockHeader, BlockRelevance)>, ClientError> {
23        self.store.get_block_header_by_num(block_num).await.map_err(Into::into)
24    }
25
26    /// Ensures that the genesis block is available. If the genesis commitment is already
27    /// cached in the RPC client, returns early. Otherwise, fetches the genesis block from
28    /// the node, stores it, and sets the commitment in the RPC client.
29    pub async fn ensure_genesis_in_place(&mut self) -> Result<(), ClientError> {
30        if self.rpc_api.has_genesis_commitment().is_some() {
31            return Ok(());
32        }
33
34        let (genesis, _) = self
35            .rpc_api
36            .get_block_header_by_number(Some(BlockNumber::GENESIS), false)
37            .await?;
38
39        let blank_mmr_peaks = MmrPeaks::new(Forest::empty(), vec![])
40            .expect("Blank MmrPeaks should not fail to instantiate");
41        self.store.insert_block_header(&genesis, blank_mmr_peaks, false).await?;
42        self.rpc_api.set_genesis_commitment(genesis.commitment()).await?;
43        Ok(())
44    }
45
46    /// Fetches from the store the current view of the chain's [`PartialMmr`].
47    pub async fn get_current_partial_mmr(&self) -> Result<PartialMmr, ClientError> {
48        self.store.get_current_partial_mmr().await.map_err(Into::into)
49    }
50
51    // HELPERS
52    // --------------------------------------------------------------------------------------------
53
54    /// Retrieves and stores a [`BlockHeader`] by number, and stores its authentication data as
55    /// well.
56    ///
57    /// If the store already contains MMR data for the requested block number, the request isn't
58    /// done and the stored block header is returned.
59    pub(crate) async fn get_and_store_authenticated_block(
60        &self,
61        block_num: BlockNumber,
62        current_partial_mmr: &mut PartialMmr,
63    ) -> Result<BlockHeader, ClientError> {
64        if current_partial_mmr.is_tracked(block_num.as_usize()) {
65            warn!("Current partial MMR already contains the requested data");
66            let (block_header, _) = self
67                .store
68                .get_block_header_by_num(block_num)
69                .await?
70                .expect("Block header should be tracked");
71            return Ok(block_header);
72        }
73
74        // Fetch the block header and MMR proof from the node
75        let (block_header, path_nodes) =
76            fetch_block_header(self.rpc_api.clone(), block_num, current_partial_mmr).await?;
77
78        // Insert header and MMR nodes
79        self.store
80            .insert_block_header(&block_header, current_partial_mmr.peaks(), true)
81            .await?;
82        self.store.insert_partial_blockchain_nodes(&path_nodes).await?;
83
84        Ok(block_header)
85    }
86}
87
88// UTILS
89// --------------------------------------------------------------------------------------------
90
91/// Returns a merkle path nodes for a specific block adjusted for a defined forest size.
92/// This function trims the merkle path to include only the nodes that are relevant for
93/// the MMR forest.
94///
95/// # Parameters
96/// - `merkle_path`: Original merkle path.
97/// - `block_num`: The block number for which the path is computed.
98/// - `forest`: The target size of the forest.
99pub(crate) fn adjust_merkle_path_for_forest(
100    merkle_path: &MerklePath,
101    block_num: BlockNumber,
102    forest: Forest,
103) -> Vec<(InOrderIndex, Word)> {
104    let expected_path_len = forest
105        .leaf_to_corresponding_tree(block_num.as_usize())
106        .expect("forest includes block number") as usize;
107
108    let mut idx = InOrderIndex::from_leaf_pos(block_num.as_usize());
109    let mut path_nodes = Vec::with_capacity(expected_path_len);
110
111    for node in merkle_path.nodes().iter().take(expected_path_len) {
112        path_nodes.push((idx.sibling(), *node));
113        idx = idx.parent();
114    }
115
116    path_nodes
117}
118
119pub(crate) async fn fetch_block_header(
120    rpc_api: Arc<dyn NodeRpcClient>,
121    block_num: BlockNumber,
122    current_partial_mmr: &mut PartialMmr,
123) -> Result<(BlockHeader, Vec<(InOrderIndex, Word)>), ClientError> {
124    let (block_header, mmr_proof) = rpc_api.get_block_header_with_proof(block_num).await?;
125
126    // Trim merkle path to keep nodes relevant to our current PartialMmr since the node's MMR
127    // might be of a forest arbitrarily higher
128    let path_nodes = adjust_merkle_path_for_forest(
129        &mmr_proof.merkle_path,
130        block_num,
131        current_partial_mmr.forest(),
132    );
133
134    let merkle_path = MerklePath::new(path_nodes.iter().map(|(_, n)| *n).collect());
135
136    current_partial_mmr
137        .track(block_num.as_usize(), block_header.commitment(), &merkle_path)
138        .map_err(StoreError::MmrError)?;
139
140    Ok((block_header, path_nodes))
141}
142
143#[cfg(test)]
144mod tests {
145    use miden_protocol::block::BlockNumber;
146    use miden_protocol::crypto::merkle::MerklePath;
147    use miden_protocol::crypto::merkle::mmr::{Forest, InOrderIndex, Mmr, PartialMmr};
148    use miden_protocol::{Felt, Word};
149
150    use super::adjust_merkle_path_for_forest;
151
152    fn word(n: u64) -> Word {
153        Word::new([Felt::new(n), Felt::new(0), Felt::new(0), Felt::new(0)])
154    }
155
156    #[test]
157    fn adjust_merkle_path_truncates_to_forest_bounds() {
158        let forest = Forest::new(5);
159        // Forest 5 <=> block 4 is rightmost leaf
160        let block_num = BlockNumber::from(4u32);
161        let path = MerklePath::new(vec![word(1), word(2), word(3)]);
162
163        let adjusted = adjust_merkle_path_for_forest(&path, block_num, forest);
164        // Block 4 conforms a single leaf tree so it should be empty
165        assert!(adjusted.is_empty());
166    }
167
168    #[test]
169    fn adjust_merkle_path_keeps_proof_valid_for_smaller_forest() {
170        // Build a proof in a larger forest and ensure truncation does not keep siblings from a
171        // different tree in the smaller forest, which would invalidate the proof.
172        let mut mmr = Mmr::new();
173        for value in 0u64..8 {
174            mmr.add(word(value));
175        }
176
177        let large_forest = Forest::new(8);
178        let small_forest = Forest::new(5);
179        let leaf_pos = 4usize;
180        let block_num = BlockNumber::from(u32::try_from(leaf_pos).unwrap());
181
182        let proof = mmr.open_at(leaf_pos, large_forest).expect("valid proof");
183        let adjusted_nodes =
184            adjust_merkle_path_for_forest(&proof.merkle_path, block_num, small_forest);
185        let adjusted_path = MerklePath::new(adjusted_nodes.iter().map(|(_, n)| *n).collect());
186
187        let peaks = mmr.peaks_at(small_forest).unwrap();
188        let mut partial = PartialMmr::from_peaks(peaks);
189        let leaf = mmr.get(leaf_pos).expect("leaf exists");
190
191        partial
192            .track(leaf_pos, leaf, &adjusted_path)
193            .expect("adjusted path should verify against smaller forest peaks");
194    }
195
196    #[test]
197    fn adjust_merkle_path_correct_indices() {
198        // Forest 6 has trees of size 2 and 4
199        let forest = Forest::new(6);
200        // Block 1 is on tree with size 4 (merkle path should have 2 nodes)
201        let block_num = BlockNumber::from(1u32);
202        let nodes = vec![word(10), word(11), word(12), word(13)];
203        let path = MerklePath::new(nodes.clone());
204
205        let adjusted = adjust_merkle_path_for_forest(&path, block_num, forest);
206
207        assert_eq!(adjusted.len(), 2);
208        assert_eq!(adjusted[0].1, nodes[0]);
209        assert_eq!(adjusted[1].1, nodes[1]);
210
211        let mut idx = InOrderIndex::from_leaf_pos(1);
212        let expected0 = idx.sibling();
213        idx = idx.parent();
214        let expected1 = idx.sibling();
215
216        assert_eq!(adjusted[0].0, expected0);
217        assert_eq!(adjusted[1].0, expected1);
218    }
219
220    #[test]
221    fn adjust_path_limit_correct_when_siblings_in_bounds() {
222        // Ensure the expected depth limit matters even when the next sibling
223        // is "in-bounds" (but not part of the leaf's subtree for that forest)
224        let large_leaves = 8usize;
225        let small_leaves = 7usize;
226        let leaf_pos = 2usize;
227        let mut mmr = Mmr::new();
228        for value in 0u64..large_leaves as u64 {
229            mmr.add(word(value));
230        }
231
232        let small_forest = Forest::new(small_leaves);
233        let proof = mmr.open_at(leaf_pos, Forest::new(large_leaves)).expect("valid proof");
234        let expected_depth =
235            small_forest.leaf_to_corresponding_tree(leaf_pos).expect("leaf is in forest") as usize;
236
237        // Confirm the next sibling after the expected depth is still in bounds, which would
238        // create an overlong path without the depth cap.
239        let mut idx = InOrderIndex::from_leaf_pos(leaf_pos);
240        for _ in 0..expected_depth {
241            idx = idx.parent();
242        }
243        let next_sibling = idx.sibling();
244        let rightmost = InOrderIndex::from_leaf_pos(small_leaves - 1);
245        assert!(next_sibling <= rightmost);
246        assert!(proof.merkle_path.depth() as usize > expected_depth);
247
248        let adjusted = adjust_merkle_path_for_forest(
249            &proof.merkle_path,
250            BlockNumber::from(u32::try_from(leaf_pos).unwrap()),
251            small_forest,
252        );
253        assert_eq!(adjusted.len(), expected_depth);
254    }
255}