ab_farmer_components/
shard_commitment.rs1use ab_blake3::{BLOCK_LEN, MAX_SIMD_DEGREE};
4use ab_core_primitives::hashes::Blake3Hash;
5use ab_core_primitives::segments::{HistorySize, SegmentIndex};
6use ab_core_primitives::shard::NumShards;
7use ab_core_primitives::solutions::{
8 ShardCommitmentHash, ShardMembershipEntropy, SolutionShardCommitment,
9};
10use ab_io_type::trivial_type::TrivialType;
11use ab_merkle_tree::blake3::UnbalancedMerkleTree;
12use blake3::Hasher;
13use parking_lot::RwLock;
14use schnellru::{ByLength, LruMap};
15use std::mem::MaybeUninit;
16use transparent_wrapper::TransparentWrapper;
17use triomphe::Arc;
18
19const SHARD_COMMITMENTS_ROOT_CACHE_SIZE: ByLength = ByLength::new(32);
20
21const LEAVES_PER_XOF_READ: usize = MAX_SIMD_DEGREE * BLOCK_LEN / ShardCommitmentHash::SIZE;
27
28const _: () = {
29 assert!((LEAVES_PER_XOF_READ * ShardCommitmentHash::SIZE).is_multiple_of(BLOCK_LEN));
30 assert!(SolutionShardCommitment::NUM_LEAVES.is_multiple_of(LEAVES_PER_XOF_READ));
31};
32
33#[derive(Debug)]
34struct Inner {
35 shard_commitments_seed: Blake3Hash,
36 lru: LruMap<HistorySize, ShardCommitmentHash, ByLength>,
37}
38
39#[derive(Debug, Clone)]
41pub struct ShardCommitmentsRootsCache {
42 inner: Arc<RwLock<Inner>>,
43}
44
45impl ShardCommitmentsRootsCache {
46 pub fn new(shard_commitments_seed: Blake3Hash) -> Self {
48 Self {
49 inner: Arc::new(RwLock::new(Inner {
50 shard_commitments_seed,
51 lru: LruMap::new(SHARD_COMMITMENTS_ROOT_CACHE_SIZE),
52 })),
53 }
54 }
55
56 pub fn shard_commitments_seed(&self) -> Blake3Hash {
58 self.inner.read().shard_commitments_seed
59 }
60
61 pub fn get(&self, history_size: HistorySize) -> ShardCommitmentHash {
65 if let Some(root) = self.inner.read().lru.peek(&history_size).copied() {
66 return root;
67 }
68
69 let inner = &mut *self.inner.write();
70 *inner
73 .lru
74 .get_or_insert(history_size, || {
75 derive_shard_commitments_root(&inner.shard_commitments_seed, history_size)
76 })
77 .expect("Not limited by memory; qed")
78 }
79}
80
81#[inline(always)]
86fn shard_commitment_leaves(
87 shard_commitments_seed: &Blake3Hash,
88 history_size: HistorySize,
89) -> impl Iterator<Item = [u8; ShardCommitmentHash::SIZE]> {
90 let mut stream = {
91 let mut hasher = Hasher::new_keyed(shard_commitments_seed);
92 hasher.update(SegmentIndex::from(history_size).as_bytes());
93 hasher.finalize_xof()
94 };
95
96 gen move {
97 for _ in 0..SolutionShardCommitment::NUM_LEAVES / LEAVES_PER_XOF_READ {
98 let mut leaves = [[0; ShardCommitmentHash::SIZE]; LEAVES_PER_XOF_READ];
99 stream.fill(leaves.as_flattened_mut());
100 for leaf in leaves {
101 yield leaf;
102 }
103 }
104 }
105}
106
107pub fn derive_shard_commitments_root(
109 shard_commitments_seed: &Blake3Hash,
110 history_size: HistorySize,
111) -> ShardCommitmentHash {
112 let leaves = shard_commitment_leaves(shard_commitments_seed, history_size);
113
114 let root = UnbalancedMerkleTree::compute_root_only_dynamic_len::<
117 { SolutionShardCommitment::NUM_LEAVES as u64 },
118 _,
119 _,
120 >(leaves)
121 .expect("List of leaves is not empty; qed");
122
123 ShardCommitmentHash::new(root)
124}
125
126pub fn derive_solution_shard_commitment(
128 public_key_hash: &Blake3Hash,
129 shard_commitments_seed: &Blake3Hash,
130 shard_commitments_root: &ShardCommitmentHash,
131 history_size: HistorySize,
132 shard_membership_entropy: &ShardMembershipEntropy,
133 num_shards: NumShards,
134) -> SolutionShardCommitment {
135 let leaf_index = num_shards.derive_shard_commitment_index(
136 public_key_hash,
137 shard_commitments_root,
138 shard_membership_entropy,
139 history_size,
140 ) as usize;
141
142 let mut leaf = [0; _];
143 let leaves = shard_commitment_leaves(shard_commitments_seed, history_size)
144 .enumerate()
145 .map(|(index, bytes)| {
146 if index == leaf_index {
147 leaf = bytes;
148 }
149
150 bytes
151 });
152
153 let mut proof = [MaybeUninit::uninit(); _];
154 let (_root, computed_proof) = UnbalancedMerkleTree::compute_root_and_proof_dynamic_len_in::<
157 { SolutionShardCommitment::NUM_LEAVES as u64 },
158 _,
159 _,
160 >(leaves, leaf_index, &mut proof)
161 .expect("Index is always within the list of leaves; qed");
162 debug_assert_eq!(computed_proof.len(), proof.len());
163
164 let proof = unsafe { MaybeUninit::array_assume_init(proof) };
168
169 SolutionShardCommitment {
170 root: *shard_commitments_root,
171 proof: <[ShardCommitmentHash; _]>::wrap(proof),
172 leaf: ShardCommitmentHash::new(leaf),
173 }
174}