miden_protocol/transaction/
partial_blockchain.rs

1use alloc::collections::BTreeMap;
2use alloc::vec::Vec;
3use core::ops::RangeTo;
4
5use crate::block::{BlockHeader, BlockNumber};
6use crate::crypto::merkle::InnerNodeInfo;
7use crate::crypto::merkle::mmr::{MmrPeaks, PartialMmr};
8use crate::errors::PartialBlockchainError;
9use crate::utils::serde::{Deserializable, Serializable};
10
11// PARTIAL BLOCKCHAIN
12// ================================================================================================
13
14/// A partial view into the full [`Blockchain`](crate::block::Blockchain)'s Merkle Mountain Range
15/// (MMR).
16///
17/// It allows for efficient authentication of input notes during transaction execution or
18/// authentication of reference blocks during batch or block execution. Authentication is achieved
19/// by providing inclusion proofs for the notes consumed in the transaction against the partial
20/// blockchain root associated with the transaction's reference block.
21///
22/// [`PartialBlockchain`] contains authentication paths for a limited set of blocks. The intent is
23/// to include only the blocks relevant for execution:
24/// - For transactions: the set of blocks in which all input notes were created.
25/// - For batches: the set of reference blocks of all transactions in the batch and the blocks to
26///   prove any unauthenticated note's inclusion.
27/// - For blocks: the set of reference blocks of all batches in the block and the blocks to prove
28///   any unauthenticated note's inclusion.
29///
30/// # Guarantees
31///
32/// The [`PartialBlockchain`] contains the full authenticated [`BlockHeader`]s of all blocks
33/// it tracks in its partial MMR and users of this type can make this assumption. This is ensured
34/// when using [`PartialBlockchain::new`]. [`PartialBlockchain::new_unchecked`] should only be used
35/// whenever this guarantee can be upheld.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct PartialBlockchain {
38    /// Partial view of the blockchain with authentication paths for the blocks listed below.
39    mmr: PartialMmr,
40    /// A map of block_num |-> block_header for all blocks for which the partial MMR contains
41    /// authentication paths.
42    blocks: BTreeMap<BlockNumber, BlockHeader>,
43}
44
45impl PartialBlockchain {
46    // CONSTRUCTOR
47    // --------------------------------------------------------------------------------------------
48    /// Returns a new [PartialBlockchain] instantiated from the provided partial MMR and a list of
49    /// block headers.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if:
54    /// - block_num for any of the blocks is greater than the chain length implied by the provided
55    ///   partial MMR.
56    /// - The same block appears more than once in the provided list of block headers.
57    /// - The partial MMR does not track authentication paths for any of the specified blocks.
58    /// - Any of the provided block header's commitment is not tracked in the MMR, i.e. its
59    ///   inclusion cannot be verified.
60    pub fn new(
61        mmr: PartialMmr,
62        blocks: impl IntoIterator<Item = BlockHeader>,
63    ) -> Result<Self, PartialBlockchainError> {
64        let partial_chain = Self::new_unchecked(mmr, blocks)?;
65
66        // Verify inclusion of all provided blocks in the partial MMR.
67        for (block_num, block) in partial_chain.blocks.iter() {
68            // SAFETY: new_unchecked returns an error if a block is not tracked in the MMR, so
69            // retrieving a proof here should succeed.
70            let proof = partial_chain
71                .mmr
72                .open(block_num.as_usize())
73                .expect("block should not exceed chain length")
74                .expect("block should be tracked in the partial MMR");
75
76            partial_chain.mmr.peaks().verify(block.commitment(), proof).map_err(|source| {
77                PartialBlockchainError::BlockHeaderCommitmentMismatch {
78                    block_num: *block_num,
79                    block_commitment: block.commitment(),
80                    source,
81                }
82            })?;
83        }
84
85        Ok(partial_chain)
86    }
87
88    /// Returns a new [PartialBlockchain] instantiated from the provided partial MMR and a list of
89    /// block headers.
90    ///
91    /// # Warning
92    ///
93    /// This does not verify that the provided block commitments are in the MMR. Use [`Self::new`]
94    /// to run this verification. This constructor is provided to bypass this check in trusted
95    /// environment because it is relatively expensive.
96    ///
97    /// # Errors
98    ///
99    /// Returns an error if:
100    /// - block_num for any of the blocks is greater than the chain length implied by the provided
101    ///   partial MMR.
102    /// - The same block appears more than once in the provided list of block headers.
103    /// - The partial MMR does not track authentication paths for any of the specified blocks.
104    pub fn new_unchecked(
105        mmr: PartialMmr,
106        blocks: impl IntoIterator<Item = BlockHeader>,
107    ) -> Result<Self, PartialBlockchainError> {
108        let chain_length = mmr.forest().num_leaves();
109        let mut block_map = BTreeMap::new();
110        for block in blocks {
111            let block_num = block.block_num();
112            if block.block_num().as_usize() >= chain_length {
113                return Err(PartialBlockchainError::block_num_too_big(chain_length, block_num));
114            }
115
116            // Note that this only checks if a leaf exists at that position but it doesn't
117            // assert that it matches the block's commitment provided in the iterator.
118            if !mmr.is_tracked(block_num.as_usize()) {
119                return Err(PartialBlockchainError::untracked_block(block_num));
120            }
121
122            if block_map.insert(block_num, block).is_some() {
123                return Err(PartialBlockchainError::duplicate_block(block_num));
124            }
125        }
126
127        Ok(Self { mmr, blocks: block_map })
128    }
129
130    // PUBLIC ACCESSORS
131    // --------------------------------------------------------------------------------------------
132
133    /// Returns the underlying [`PartialMmr`].
134    pub fn mmr(&self) -> &PartialMmr {
135        &self.mmr
136    }
137
138    /// Returns peaks of this MMR.
139    pub fn peaks(&self) -> MmrPeaks {
140        self.mmr.peaks()
141    }
142
143    /// Returns total number of blocks contain in the chain described by this MMR.
144    pub fn chain_length(&self) -> BlockNumber {
145        BlockNumber::from(
146            u32::try_from(self.mmr.forest().num_leaves())
147                .expect("partial blockchain should never contain more than u32::MAX blocks"),
148        )
149    }
150
151    /// Returns the number of blocks tracked by this partial blockchain.
152    pub fn num_tracked_blocks(&self) -> usize {
153        self.blocks.len()
154    }
155
156    /// Returns `true` if a block with the given number is present in this partial blockchain.
157    ///
158    /// Note that this only checks whether an entry with the block's number exists in the MMR.
159    pub fn contains_block(&self, block_num: BlockNumber) -> bool {
160        self.blocks.contains_key(&block_num)
161    }
162
163    /// Returns the block header for the specified block, or None if the block is not present in
164    /// this partial blockchain.
165    pub fn get_block(&self, block_num: BlockNumber) -> Option<&BlockHeader> {
166        self.blocks.get(&block_num)
167    }
168
169    /// Returns an iterator over the block headers in this partial blockchain.
170    pub fn block_headers(&self) -> impl Iterator<Item = &BlockHeader> {
171        self.blocks.values()
172    }
173
174    // DATA MUTATORS
175    // --------------------------------------------------------------------------------------------
176
177    /// Appends the provided block header to this partial blockchain. This method assumes that the
178    /// provided block header is for the next block in the chain.
179    ///
180    /// If `track` parameter is set to true, the authentication path for the provided block header
181    /// will be added to this partial blockchain.
182    ///
183    /// # Panics
184    /// Panics if the `block_header.block_num` is not equal to the current chain length (i.e., the
185    /// provided block header is not the next block in the chain).
186    pub fn add_block(&mut self, block_header: &BlockHeader, track: bool) {
187        assert_eq!(block_header.block_num(), self.chain_length());
188        self.mmr.add(block_header.commitment(), track);
189    }
190
191    /// Drop every block header whose number is strictly less than `to.end`.
192    ///
193    /// After the call, all such headers are removed, and each pruned header’s path is `untrack`‑ed
194    /// from the internal [`PartialMmr`], eliminating local authentication data for those leaves
195    /// while leaving the MMR root commitment unchanged.
196    pub fn prune_to(&mut self, to: RangeTo<BlockNumber>) {
197        let kept = self.blocks.split_off(&to.end);
198
199        for block_num in self.blocks.keys() {
200            self.mmr.untrack(block_num.as_usize());
201        }
202        self.blocks = kept;
203    }
204
205    /// Removes a single block header and the associated authentication path from this
206    /// [`PartialBlockchain`].
207    ///
208    /// This does not change the commitment to the underlying MMR, but the current partial MMR
209    /// will no longer track the removed data.
210    pub fn remove(&mut self, block_num: BlockNumber) {
211        if self.blocks.remove(&block_num).is_some() {
212            self.mmr.untrack(block_num.as_usize());
213        }
214    }
215
216    // ITERATORS
217    // --------------------------------------------------------------------------------------------
218
219    /// Returns an iterator over the inner nodes of authentication paths contained in this chain
220    /// MMR.
221    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
222        self.mmr.inner_nodes(
223            self.blocks
224                .values()
225                .map(|block| (block.block_num().as_usize(), block.commitment())),
226        )
227    }
228
229    // TESTING
230    // --------------------------------------------------------------------------------------------
231
232    /// Returns a mutable reference to the map of block numbers to block headers in this partial
233    /// blockchain.
234    ///
235    /// Allows mutating the inner map for testing purposes.
236    #[cfg(any(feature = "testing", test))]
237    pub fn block_headers_mut(&mut self) -> &mut BTreeMap<BlockNumber, BlockHeader> {
238        &mut self.blocks
239    }
240
241    /// Returns a mutable reference to the partial MMR of this partial blockchain.
242    ///
243    /// Allows mutating the inner partial MMR for testing purposes.
244    #[cfg(any(feature = "testing", test))]
245    pub fn partial_mmr_mut(&mut self) -> &mut PartialMmr {
246        &mut self.mmr
247    }
248}
249
250impl Serializable for PartialBlockchain {
251    fn write_into<W: miden_crypto::utils::ByteWriter>(&self, target: &mut W) {
252        self.mmr.write_into(target);
253        self.blocks.write_into(target);
254    }
255}
256
257impl Deserializable for PartialBlockchain {
258    fn read_from<R: miden_crypto::utils::ByteReader>(
259        source: &mut R,
260    ) -> Result<Self, miden_crypto::utils::DeserializationError> {
261        let mmr = PartialMmr::read_from(source)?;
262        let blocks = BTreeMap::<BlockNumber, BlockHeader>::read_from(source)?;
263        Ok(Self { mmr, blocks })
264    }
265}
266
267impl Default for PartialBlockchain {
268    fn default() -> Self {
269        Self::new(PartialMmr::default(), Vec::new())
270            .expect("empty partial blockchain should be valid")
271    }
272}
273
274// TESTS
275// ================================================================================================
276
277#[cfg(test)]
278mod tests {
279    use assert_matches::assert_matches;
280    use miden_core::utils::{Deserializable, Serializable};
281    use rand::SeedableRng;
282    use rand_chacha::ChaCha20Rng;
283
284    use super::PartialBlockchain;
285    use crate::Word;
286    use crate::alloc::vec::Vec;
287    use crate::block::{BlockHeader, BlockNumber, FeeParameters};
288    use crate::crypto::dsa::ecdsa_k256_keccak::SecretKey;
289    use crate::crypto::merkle::mmr::{Mmr, PartialMmr};
290    use crate::errors::PartialBlockchainError;
291    use crate::testing::account_id::ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET;
292
293    #[test]
294    fn test_partial_blockchain_add() {
295        // create partial blockchain with 3 blocks - i.e., 2 peaks
296        let mut mmr = Mmr::default();
297        for i in 0..3 {
298            let block_header = int_to_block_header(i);
299            mmr.add(block_header.commitment());
300        }
301        let partial_mmr: PartialMmr = mmr.peaks().into();
302        let mut partial_blockchain = PartialBlockchain::new(partial_mmr, Vec::new()).unwrap();
303
304        // add a new block to the partial blockchain, this reduces the number of peaks to 1
305        let block_num = 3;
306        let block_header = int_to_block_header(block_num);
307        mmr.add(block_header.commitment());
308        partial_blockchain.add_block(&block_header, true);
309
310        assert_eq!(
311            mmr.open(block_num as usize).unwrap(),
312            partial_blockchain.mmr.open(block_num as usize).unwrap().unwrap()
313        );
314
315        // add one more block to the partial blockchain, the number of peaks is again 2
316        let block_num = 4;
317        let block_header = int_to_block_header(block_num);
318        mmr.add(block_header.commitment());
319        partial_blockchain.add_block(&block_header, true);
320
321        assert_eq!(
322            mmr.open(block_num as usize).unwrap(),
323            partial_blockchain.mmr.open(block_num as usize).unwrap().unwrap()
324        );
325
326        // add one more block to the partial blockchain, the number of peaks is still 2
327        let block_num = 5;
328        let block_header = int_to_block_header(block_num);
329        mmr.add(block_header.commitment());
330        partial_blockchain.add_block(&block_header, true);
331
332        assert_eq!(
333            mmr.open(block_num as usize).unwrap(),
334            partial_blockchain.mmr.open(block_num as usize).unwrap().unwrap()
335        );
336    }
337
338    #[test]
339    fn partial_blockchain_new_on_invalid_header_fails() {
340        let block_header0 = int_to_block_header(0);
341        let block_header1 = int_to_block_header(1);
342        let block_header2 = int_to_block_header(2);
343
344        let mut mmr = Mmr::default();
345        mmr.add(block_header0.commitment());
346        mmr.add(block_header1.commitment());
347        mmr.add(block_header2.commitment());
348
349        let mut partial_mmr = PartialMmr::from_peaks(mmr.peaks());
350        for i in 0..3 {
351            partial_mmr
352                .track(i, mmr.get(i).unwrap(), &mmr.open(i).unwrap().merkle_path)
353                .unwrap();
354        }
355
356        let fake_block_header2 = BlockHeader::mock(2, None, None, &[], Word::empty());
357
358        assert_ne!(block_header2.commitment(), fake_block_header2.commitment());
359
360        // Construct a PartialBlockchain with an invalid block header.
361        let error = PartialBlockchain::new(
362            partial_mmr,
363            vec![block_header0, block_header1, fake_block_header2.clone()],
364        )
365        .unwrap_err();
366
367        assert_matches!(
368            error,
369            PartialBlockchainError::BlockHeaderCommitmentMismatch {
370                block_commitment,
371                block_num,
372                ..
373            } if block_commitment == fake_block_header2.commitment() && block_num == fake_block_header2.block_num()
374        )
375    }
376
377    #[test]
378    fn partial_blockchain_new_on_block_number_exceeding_chain_length_fails() {
379        let block_header0 = int_to_block_header(0);
380        let mmr = Mmr::default();
381        let partial_mmr = PartialMmr::from_peaks(mmr.peaks());
382
383        let error = PartialBlockchain::new(partial_mmr, [block_header0]).unwrap_err();
384
385        assert_matches!(error, PartialBlockchainError::BlockNumTooBig {
386          chain_length,
387          block_num,
388        } if chain_length == 0 && block_num == BlockNumber::from(0));
389    }
390
391    #[test]
392    fn partial_blockchain_new_on_untracked_block_number_fails() {
393        let block_header0 = int_to_block_header(0);
394        let block_header1 = int_to_block_header(1);
395
396        let mut mmr = Mmr::default();
397        mmr.add(block_header0.commitment());
398        mmr.add(block_header1.commitment());
399
400        let mut partial_mmr = PartialMmr::from_peaks(mmr.peaks());
401        partial_mmr
402            .track(1, block_header1.commitment(), &mmr.open(1).unwrap().merkle_path)
403            .unwrap();
404
405        let error =
406            PartialBlockchain::new(partial_mmr, [block_header0, block_header1]).unwrap_err();
407
408        assert_matches!(error, PartialBlockchainError::UntrackedBlock {
409          block_num,
410        } if block_num == BlockNumber::from(0));
411    }
412
413    #[test]
414    fn partial_blockchain_serialization() {
415        // create partial blockchain with 3 blocks - i.e., 2 peaks
416        let mut mmr = Mmr::default();
417        for i in 0..3 {
418            let block_header = int_to_block_header(i);
419            mmr.add(block_header.commitment());
420        }
421        let partial_mmr: PartialMmr = mmr.peaks().into();
422        let partial_blockchain = PartialBlockchain::new(partial_mmr, Vec::new()).unwrap();
423
424        let bytes = partial_blockchain.to_bytes();
425        let deserialized = PartialBlockchain::read_from_bytes(&bytes).unwrap();
426
427        assert_eq!(partial_blockchain, deserialized);
428    }
429
430    fn int_to_block_header(block_num: impl Into<BlockNumber>) -> BlockHeader {
431        let fee_parameters =
432            FeeParameters::new(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap(), 500)
433                .expect("native asset ID should be a fungible faucet ID");
434        let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
435        let validator_key = SecretKey::with_rng(&mut rng).public_key();
436
437        BlockHeader::new(
438            0,
439            Word::empty(),
440            block_num.into(),
441            Word::empty(),
442            Word::empty(),
443            Word::empty(),
444            Word::empty(),
445            Word::empty(),
446            Word::empty(),
447            validator_key,
448            fee_parameters,
449            0,
450        )
451    }
452
453    #[test]
454    fn prune_before_and_remove() {
455        let total_blocks = 128;
456        let remove_before = 40;
457
458        let mut full_mmr = Mmr::default();
459        let mut headers = Vec::new();
460        for i in 0..total_blocks {
461            let h = int_to_block_header(i);
462            full_mmr.add(h.commitment());
463            headers.push(h);
464        }
465        let mut partial_mmr: PartialMmr = full_mmr.peaks().into();
466        for i in 0..total_blocks {
467            let i: usize = i as usize;
468            partial_mmr
469                .track(i, full_mmr.get(i).unwrap(), &full_mmr.open(i).unwrap().merkle_path)
470                .unwrap();
471        }
472        let mut chain = PartialBlockchain::new(partial_mmr, headers).unwrap();
473        assert_eq!(chain.num_tracked_blocks(), total_blocks as usize);
474
475        chain.remove(BlockNumber::from(2));
476        assert!(!chain.contains_block(2.into()));
477        assert!(!chain.mmr().is_tracked(2));
478        assert_eq!(chain.num_tracked_blocks(), (total_blocks - 1) as usize);
479
480        assert!(chain.contains_block(3.into()));
481
482        chain.prune_to(..40.into());
483        assert_eq!(chain.num_tracked_blocks(), (total_blocks - 40) as usize);
484
485        assert_eq!(chain.block_headers().count(), (total_blocks - remove_before) as usize);
486        for block_num in remove_before..total_blocks {
487            assert!(chain.contains_block(block_num.into()));
488            assert!(chain.mmr().is_tracked(block_num as usize));
489        }
490        for block_num in 0u32..remove_before {
491            assert!(!chain.contains_block(block_num.into()));
492            assert!(!chain.mmr().is_tracked(block_num as usize));
493        }
494    }
495}