snarkvm_ledger_block/ratifications/merkle.rs
1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> Ratifications<N> {
19 /// Returns the ratifications root, by computing the root for a Merkle tree of the ratification IDs.
20 pub fn to_ratifications_root(&self) -> Result<Field<N>> {
21 Ok(*self.to_tree()?.root())
22 }
23
24 /// Returns the Merkle path for the ratifications leaf.
25 pub fn to_path(&self, ratification_id: N::RatificationID) -> Result<RatificationsPath<N>> {
26 match self.ratifications.get_index_of(&ratification_id) {
27 Some(ratification_index) => self.to_tree()?.prove(ratification_index, &ratification_id.to_bits_le()),
28 None => bail!("The ratification '{ratification_id}' is not in the block ratifications"),
29 }
30 }
31
32 /// The Merkle tree of ratification IDs for the block.
33 pub fn to_tree(&self) -> Result<RatificationsTree<N>> {
34 Self::ratifications_tree(self.ratifications.keys())
35 }
36
37 /// Returns the Merkle tree for the given ratifications.
38 fn ratifications_tree<'a>(
39 ratifications: impl ExactSizeIterator<Item = &'a N::RatificationID>,
40 ) -> Result<RatificationsTree<N>> {
41 // Ensure the number of ratifications is within the allowed range.
42 ensure!(
43 ratifications.len() <= Self::MAX_RATIFICATIONS,
44 "Block cannot exceed {} ratifications, found {}",
45 Self::MAX_RATIFICATIONS,
46 ratifications.len()
47 );
48 // Prepare the leaves.
49 let leaves = ratifications.map(|id| id.to_bits_le());
50 // Compute the ratifications tree.
51 N::merkle_tree_bhp::<RATIFICATIONS_DEPTH>(&leaves.collect::<Vec<_>>())
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use console::network::MainnetV0;
59
60 type CurrentNetwork = MainnetV0;
61
62 #[test]
63 fn test_ratifications_depth() {
64 // Ensure the log2 relationship between depth and the maximum number of ratifications.
65 assert_eq!(2usize.pow(RATIFICATIONS_DEPTH as u32), Ratifications::<CurrentNetwork>::MAX_RATIFICATIONS);
66 }
67}