Skip to main content

ab_farmer_components/
shard_commitment.rs

1//! Utilities related to shard commitments
2
3use 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
21/// Number of shard commitment leaves read from the XOF stream at once.
22///
23/// BLAKE3 computes up to `MAX_SIMD_DEGREE` whole output blocks of the XOF stream in parallel with
24/// SIMD, but recomputes a whole block for every read shorter than a block. Reading this many leaves
25/// at once keeps SIMD saturated with a small buffer on the stack instead of all leaves on the heap.
26const 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/// Cache for shard commitments roots to avoid recomputing them repeatedly
40#[derive(Debug, Clone)]
41pub struct ShardCommitmentsRootsCache {
42    inner: Arc<RwLock<Inner>>,
43}
44
45impl ShardCommitmentsRootsCache {
46    /// Create a new instance
47    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    /// Seed used during instantiation
57    pub fn shard_commitments_seed(&self) -> Blake3Hash {
58        self.inner.read().shard_commitments_seed
59    }
60
61    /// Get root for a specified history size.
62    ///
63    /// Root will be recomputed unless already known.
64    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        // NOTE: See https://github.com/koute/schnellru/issues/7 for an explanation of the
71        // `Option` return type
72        *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/// Shard commitment leaves derived from the seed and history size.
82///
83/// Yields exactly [`SolutionShardCommitment::NUM_LEAVES`] leaves, which are consecutive chunks of
84/// the XOF stream.
85#[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
107/// Derive shard commitments root from the seed and history size
108pub 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    // NOTE: Using unbalanced implementation since balanced implementation requires allocation of
115    // leaves
116    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
126/// Derive solution shard commitment
127pub 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    // NOTE: Using unbalanced implementation since balanced implementation requires an allocation
155    // and uses a lot more RAM
156    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    // SAFETY: The iterator yields exactly `NUM_LEAVES` leaves, which is a power of two, so the tree
165    // is full and the proof of any leaf has exactly `NUM_LEAVES.ilog2()` elements, which is the
166    // length of the array
167    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}