ic_auth/
chain_key_batch.rs1use ic_auth_protocol_types::{ChainKeyBatchWitnessStepV1, ChainKeyBatchWitnessV1};
8use sha2::{Digest, Sha256};
9use std::ops::Range;
10use thiserror::Error;
11
12#[derive(Debug, Error, Eq, PartialEq)]
14pub enum ChainKeyBatchError {
15 #[error("chain-key batch requires at least one leaf")]
17 EmptyBatch,
18 #[error("chain-key batch has {found} leaves, exceeding the limit {max}")]
20 TooManyLeaves {
21 found: usize,
23 max: usize,
25 },
26}
27
28pub fn merkle_root_and_witnesses(
41 leaf_hashes: &[[u8; 32]],
42 max_leaves: usize,
43) -> Result<([u8; 32], Vec<ChainKeyBatchWitnessV1>), ChainKeyBatchError> {
44 if leaf_hashes.is_empty() {
45 return Err(ChainKeyBatchError::EmptyBatch);
46 }
47 if leaf_hashes.len() > max_leaves {
48 return Err(ChainKeyBatchError::TooManyLeaves {
49 found: leaf_hashes.len(),
50 max: max_leaves,
51 });
52 }
53
54 if leaf_hashes.len() == 1 {
55 return Ok((
56 leaf_hashes[0],
57 vec![ChainKeyBatchWitnessV1 { steps: Vec::new() }],
58 ));
59 }
60 let depth = leaf_hashes.len().next_power_of_two().ilog2() as usize;
61 let mut witnesses: Vec<_> = (0..leaf_hashes.len())
62 .map(|_| ChainKeyBatchWitnessV1 {
63 steps: Vec::with_capacity(depth),
64 })
65 .collect();
66 let mut level: Vec<_> = leaf_hashes
67 .iter()
68 .enumerate()
69 .map(|(index, hash)| Node {
70 hash: *hash,
71 leaves: index..index + 1,
72 })
73 .collect();
74 let mut next = Vec::with_capacity(level.len().div_ceil(2));
75 while level.len() > 1 {
76 next.clear();
77 for pair in level.chunks(2) {
78 let left = &pair[0];
79 if pair.len() == 1 {
80 next.push(left.clone());
81 continue;
82 }
83 let right = &pair[1];
84 for index in left.leaves.clone() {
85 witnesses[index]
86 .steps
87 .push(ChainKeyBatchWitnessStepV1::RightSibling(right.hash));
88 }
89 for index in right.leaves.clone() {
90 witnesses[index]
91 .steps
92 .push(ChainKeyBatchWitnessStepV1::LeftSibling(left.hash));
93 }
94 next.push(Node {
95 hash: node_hash(left.hash, right.hash),
96 leaves: left.leaves.start..right.leaves.end,
97 });
98 }
99 std::mem::swap(&mut level, &mut next);
100 }
101 Ok((level[0].hash, witnesses))
102}
103
104#[derive(Clone)]
105struct Node {
106 hash: [u8; 32],
107 leaves: Range<usize>,
108}
109
110#[cfg(feature = "chain-key-verification")]
113pub(crate) fn witness_root(leaf: [u8; 32], witness: &ChainKeyBatchWitnessV1) -> [u8; 32] {
114 witness.steps.iter().fold(leaf, |current, step| match step {
115 ChainKeyBatchWitnessStepV1::LeftSibling(hash) => node_hash(*hash, current),
116 ChainKeyBatchWitnessStepV1::RightSibling(hash) => node_hash(current, *hash),
117 })
118}
119
120fn node_hash(left: [u8; 32], right: [u8; 32]) -> [u8; 32] {
121 let mut hasher = Sha256::new();
122 hasher.update([1]);
123 hasher.update(left);
124 hasher.update(right);
125 hasher.finalize().into()
126}