neptune-mutator-set 0.14.0

The mutator set, a privacy-preserving cryptographic accumulator invented by the Neptune team. Paper: https://eprint.iacr.org/2023/1208 Article: https://neptune.cash/articles/mutator-sets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use std::collections::HashMap;

#[cfg(any(test, feature = "arbitrary-impls"))]
use arbitrary::Arbitrary;
#[cfg(any(test, feature = "arbitrary-impls"))]
use arbitrary::Result;
#[cfg(any(test, feature = "arbitrary-impls"))]
use arbitrary::Unstructured;
use get_size2::GetSize;
use itertools::Itertools;
use serde::Deserialize;
use serde::Serialize;
use tasm_lib::prelude::Digest;
use tasm_lib::prelude::Tip5;
use tasm_lib::structure::tasm_object::TasmObject;
use tasm_lib::twenty_first::math::bfield_codec::BFieldCodec;
use tasm_lib::twenty_first::prelude::Sponge;

use super::super::mutator_set_accumulator::MutatorSetAccumulator;
use super::super::shared::NUM_TRIALS;
use super::MutatorSetError;
use crate::shared::indices_to_hash_map;
use crate::shared::BATCH_SIZE;
use crate::shared::CHUNK_SIZE;
use crate::shared::WINDOW_SIZE;

/// A set of 45 (=[`NUM_TRIALS`]) sliding window Bloom filter bit indices.
/// The indices live in a window that is at most 2^20 (=[`WINDOW_SIZE`]) wide.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, BFieldCodec, TasmObject, Hash, Serialize, Deserialize,
)]
pub struct AbsoluteIndexSet {
    minimum: u128,

    /// Distances of the indices relative to the minimum. Guaranteed to be in
    /// the range [0; 2^{20}-1].
    #[serde(with = "serde_arrays")]
    distances: [u32; NUM_TRIALS as usize],
}

impl GetSize for AbsoluteIndexSet {
    fn get_stack_size() -> usize {
        std::mem::size_of::<Self>()
    }

    fn get_heap_size(&self) -> usize {
        self.minimum.get_heap_size() + self.distances.get_heap_size()
    }

    fn get_size(&self) -> usize {
        Self::get_stack_size() + GetSize::get_heap_size(self)
    }
}

impl AbsoluteIndexSet {
    /// Construct a new [`AbsoluteIndexSet`] from an array of [`NUM_TRIALS`]-
    /// many `u128`s.
    ///
    /// # Panics
    ///
    ///  - If the array contains elements that are apart by more than
    ///    [`WINDOW_SIZE`].
    pub fn new(absolute_indices: [u128; NUM_TRIALS as usize]) -> Self {
        let minimum = *(absolute_indices.iter().min().unwrap());
        let distances: [u32; NUM_TRIALS as usize] = absolute_indices
            .into_iter()
            .map(|x| x - minimum)
            .map(|x| {
                if x >= WINDOW_SIZE.into() {
                    panic!(
                        "indices must lie less than WINDOW_SIZE apart, but got a distance of {x}"
                    );
                } else {
                    x
                }
            })
            .map(u32::try_from)
            .map(Result::<_, _>::unwrap)
            .collect_vec()
            .try_into()
            .unwrap();

        Self { minimum, distances }
    }

    /// Get the (absolute) indices for removing this item from the mutator set.
    pub fn compute(
        item: Digest,
        sender_randomness: Digest,
        receiver_preimage: Digest,
        aocl_leaf_index: u64,
    ) -> Self {
        let batch_index: u128 = u128::from(aocl_leaf_index) / u128::from(BATCH_SIZE);
        let batch_offset: u128 = batch_index * u128::from(CHUNK_SIZE);
        let leaf_index_bfes = aocl_leaf_index.encode();
        let input = [
            item.encode(),
            sender_randomness.encode(),
            receiver_preimage.encode(),
            leaf_index_bfes,
        ]
        .concat();

        let mut sponge = Tip5::init();
        sponge.pad_and_absorb_all(&input);
        let relative_indices = sponge.sample_indices(WINDOW_SIZE, NUM_TRIALS as usize);
        let minimum = *(relative_indices.iter().min().unwrap());
        let distances: [u32; NUM_TRIALS as usize] = relative_indices
            .into_iter()
            .map(|x| x - minimum)
            .collect_vec()
            .try_into()
            .unwrap();

        Self {
            minimum: u128::from(minimum) + batch_offset,
            distances,
        }
    }

    pub fn to_vec(self) -> Vec<u128> {
        self.to_array().to_vec()
    }

    pub fn to_array(self) -> [u128; NUM_TRIALS as usize] {
        // Saturating add to guard overflow caused by malicious absolute index
        // sets. Malicious absolute index sets will not have a valid proof, so
        // there is no risk of applying such objects to the mutator set.
        self.distances
            .map(|x| u128::from(x).saturating_add(self.minimum))
    }

    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = u128> + '_ {
        let min = self.minimum;
        self.distances
            .iter()
            .map(move |&d| min.saturating_add(u128::from(d)))
    }

    /// Split the [`AbsoluteIndexSet`] into two parts, one for chunks in the
    /// inactive part of the Bloom filter and another one for chunks in the
    /// active part of the Bloom filter.
    ///
    /// Returns an error if a removal index is a future value, i.e. one that's
    /// not yet covered by the active window.
    #[expect(clippy::type_complexity)]
    pub(crate) fn split_by_activity(
        &self,
        mutator_set: &MutatorSetAccumulator,
    ) -> Result<(HashMap<u64, Vec<u128>>, Vec<u128>), MutatorSetError> {
        let (aw_chunk_index_min, aw_chunk_index_max) = mutator_set.active_window_chunk_interval();
        let (inactive, active): (HashMap<_, _>, HashMap<_, _>) =
            indices_to_hash_map(&self.to_array())
                .into_iter()
                .partition(|&(chunk_index, _)| chunk_index < aw_chunk_index_min);

        if let Some(chunk_index) = active.keys().find(|&&k| k > aw_chunk_index_max) {
            return Err(MutatorSetError::AbsoluteRemovalIndexIsFutureIndex {
                current_max_chunk_index: aw_chunk_index_max,
                saw_chunk_index: *chunk_index,
            });
        }

        let active = active.into_values().flatten().collect_vec();

        Ok((inactive, active))
    }

    /// Return the range as a min/max pair (both inclusive) from which the
    /// absolute index set could have come from.
    ///
    /// The return value refers to the AOCL leaf indices from which the
    /// absolute index set could have been derived. In other words, this
    /// function returns the range of possible AOCL leaf indices that this set
    /// of Bloom filter indices spends. So after applying this index set to the
    /// mutator set, an AOCL leaf in this range will have been spent.
    ///
    /// Does not take the actual length of the AOCL into account, so a caller
    /// may want to further restrict the maximum in this range to the actual,
    /// current length of the AOCL.
    pub fn aocl_range(&self) -> Result<(u64, u64), MutatorSetError> {
        let max_offset: u128 = (*self.distances.iter().max().unwrap()).into();
        if max_offset >= u128::from(WINDOW_SIZE) {
            return Err(MutatorSetError::AbsoluteIndexExceedsTheoreticalBound);
        }

        let max_bf_index = max_offset + self.minimum;
        let min_active_window_start_on_insertion = (max_bf_index
            .saturating_sub(u128::from(WINDOW_SIZE) - 1))
        .next_multiple_of(u128::from(CHUNK_SIZE));
        let Ok(min_batch_index_on_insertion): Result<u64, _> =
            (min_active_window_start_on_insertion / (u128::from(CHUNK_SIZE))).try_into()
        else {
            return Err(MutatorSetError::AbsoluteIndexExceedsTheoreticalBound);
        };

        let Some(min_aocl_index) = min_batch_index_on_insertion.checked_mul(u64::from(BATCH_SIZE))
        else {
            return Err(MutatorSetError::AbsoluteIndexExceedsTheoreticalBound);
        };

        let min_bf_index = self.minimum;

        let max_active_window_end_on_insertion = (min_bf_index + (u128::from(WINDOW_SIZE)) + 1)
            .next_multiple_of(u128::from(CHUNK_SIZE))
            - u128::from(CHUNK_SIZE);

        let Ok(max_batch_index_on_insertion): Result<u64, _> = ((max_active_window_end_on_insertion
            .saturating_sub(u128::from(WINDOW_SIZE)))
            / (u128::from(CHUNK_SIZE)))
        .try_into() else {
            return Err(MutatorSetError::AbsoluteIndexExceedsTheoreticalBound);
        };

        let Some(max_aocl_index) = max_batch_index_on_insertion
            .checked_mul(u64::from(BATCH_SIZE))
            .and_then(|prod| prod.checked_add(u64::from(BATCH_SIZE) - 1))
        else {
            return Err(MutatorSetError::AbsoluteIndexExceedsTheoreticalBound);
        };

        Ok((min_aocl_index, max_aocl_index))
    }
}

#[cfg(any(test, feature = "arbitrary-impls"))]
impl<'a> Arbitrary<'a> for AbsoluteIndexSet {
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
        let aocl_index = u64::arbitrary(u)? >> 1;
        Self::arbitrary_from_aocl_index(u, aocl_index)
    }
}

#[cfg(any(test, feature = "arbitrary-impls"))]
mod neptune_arbitrary {
    use super::*;

    impl<'a> AbsoluteIndexSet {
        pub(crate) fn arbitrary_from_aocl_index(
            u: &mut Unstructured<'a>,
            aocl_index: u64,
        ) -> Result<Self> {
            let window_start =
                u128::from(aocl_index) / u128::from(BATCH_SIZE) * u128::from(CHUNK_SIZE);
            let mut relative_indices = vec![];
            for _ in 0..NUM_TRIALS {
                let index = u32::arbitrary(u)? & (crate::shared::WINDOW_SIZE - 1);
                relative_indices.push(index);
            }
            let absolute_indices = relative_indices
                .into_iter()
                .map(|ri| u128::from(ri) + window_start)
                .collect_vec()
                .try_into()
                .unwrap();
            Ok(Self::new(absolute_indices))
        }
    }
}

#[cfg(any(test, feature = "test-helpers"))]
impl rand::distr::Distribution<AbsoluteIndexSet> for rand::distr::StandardUniform {
    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> AbsoluteIndexSet {
        AbsoluteIndexSet {
            minimum: rng.random(),
            distances: rng.random(),
        }
    }
}

/// Test-only constructors and mutators for [`AbsoluteIndexSet`].
#[cfg(any(test, feature = "test-helpers"))]
impl AbsoluteIndexSet {
    /// Test-function used for negative tests of removal records
    pub fn increment_bloom_filter_index(&mut self, index: usize) {
        let mut as_array = self.to_array();
        as_array[index] = as_array[index].wrapping_add(1);
        *self = Self::new(as_array)
    }

    /// Test-function used for negative tests of removal records
    pub fn decrement_bloom_filter_index(&mut self, index: usize) {
        let mut as_array = self.to_array();
        as_array[index] = as_array[index].wrapping_sub(1);
        *self = Self::new(as_array)
    }

    pub fn set_minimum(&mut self, new_minimum: u128) {
        self.minimum = new_minimum;
    }

    pub fn minimum(&self) -> u128 {
        self.minimum
    }

    pub fn set_distance(&mut self, index: usize, new_distance: u32) {
        self.distances[index] = new_distance;
    }

    pub fn new_raw(minimum: u128, distances: [u32; NUM_TRIALS as usize]) -> Self {
        Self { minimum, distances }
    }

    pub fn empty_dummy() -> Self {
        Self {
            minimum: 0,
            distances: [0; NUM_TRIALS as usize],
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use proptest::prelude::TestCaseError;
    use proptest::prop_assert;
    use proptest::prop_assert_eq;
    use proptest_arbitrary_interop::arb;
    use test_strategy::proptest;

    use super::*;

    #[proptest]
    fn to_array_followed_by_new_is_identity(#[strategy(arb())] ais: AbsoluteIndexSet) {
        let as_array = ais.to_array();
        let as_ais_again = AbsoluteIndexSet::new(as_array);
        prop_assert_eq!(ais, as_ais_again);

        let as_array_again = as_ais_again.to_array();
        prop_assert_eq!(as_array_again, as_array);
    }

    #[proptest]
    fn iter_followed_by_collect_vec_is_to_vec(#[strategy(arb())] ais: AbsoluteIndexSet) {
        let as_vec = ais.iter().collect_vec();
        let as_vec_again = ais.to_vec();
        prop_assert_eq!(as_vec_again, as_vec);
    }

    #[test]
    fn iter_and_to_vec_and_to_array_handle_overflow_same_way() {
        fn prop(ais: AbsoluteIndexSet) {
            let as_vec = ais.to_vec();
            let as_array = ais.to_array();
            let through_iter = ais.iter().collect_vec();
            assert_eq!(as_vec, as_array.to_vec());
            assert_eq!(as_vec, through_iter);
        }
        prop(AbsoluteIndexSet::new_raw(
            u128::MAX,
            [(1 << 19); NUM_TRIALS as usize],
        ));
        prop(AbsoluteIndexSet::new_raw(
            u128::MAX,
            [u32::MAX; NUM_TRIALS as usize],
        ));
    }

    #[test]
    fn range_fails_if_offset_too_big() {
        assert!(
            AbsoluteIndexSet::new_raw(0, [WINDOW_SIZE - 1; NUM_TRIALS as usize])
                .aocl_range()
                .is_ok()
        );
        assert!(
            AbsoluteIndexSet::new_raw(0, [WINDOW_SIZE; NUM_TRIALS as usize])
                .aocl_range()
                .is_err()
        );
    }

    #[test]
    fn can_handle_max_abs_index() {
        let max_aocl_leaf_index = u64::MAX;
        let max_batch_index = u128::from(max_aocl_leaf_index) / u128::from(BATCH_SIZE);
        let max_abs_index = max_batch_index * u128::from(CHUNK_SIZE) - 1;
        assert!(
            AbsoluteIndexSet::new_raw(max_abs_index, [0; NUM_TRIALS as usize])
                .aocl_range()
                .is_ok()
        );
    }

    #[test]
    fn range_with_aocl_leaf_index_0() {
        let ais =
            AbsoluteIndexSet::compute(Digest::default(), Digest::default(), Digest::default(), 0);
        let (min, _max) = ais.aocl_range().unwrap();
        assert_eq!(0, min);
    }

    #[test]
    fn individual_cases() {
        let all_zeros = AbsoluteIndexSet::new_raw(0, [0; NUM_TRIALS as usize]);
        let mut range = all_zeros.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(7, range.1);

        let all_ones = AbsoluteIndexSet::new_raw(1, [0; NUM_TRIALS as usize]);
        range = all_ones.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(7, range.1);

        let all_chunk_size_minus_1 =
            AbsoluteIndexSet::new_raw(u128::from(CHUNK_SIZE) - 1, [0; NUM_TRIALS as usize]);
        range = all_chunk_size_minus_1.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(7, range.1);

        let all_chunk_size =
            AbsoluteIndexSet::new_raw(u128::from(CHUNK_SIZE), [0; NUM_TRIALS as usize]);
        range = all_chunk_size.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(15, range.1);

        let all_2x_chunk_size_minus_one =
            AbsoluteIndexSet::new_raw(2 * u128::from(CHUNK_SIZE) - 1, [0; NUM_TRIALS as usize]);
        range = all_2x_chunk_size_minus_one.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(15, range.1);

        let all_2x_chunk_size =
            AbsoluteIndexSet::new_raw(2 * u128::from(CHUNK_SIZE), [0; NUM_TRIALS as usize]);
        range = all_2x_chunk_size.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(23, range.1);

        let all_last_in_1st_window =
            AbsoluteIndexSet::new_raw(u128::from(WINDOW_SIZE) - 1, [0; NUM_TRIALS as usize]);
        range = all_last_in_1st_window.aocl_range().unwrap();
        assert_eq!(0, range.0);
        assert_eq!(256 * u64::from(BATCH_SIZE) - 1, range.1);

        let all_first_in_2nd_window =
            AbsoluteIndexSet::new_raw(u128::from(WINDOW_SIZE), [0; NUM_TRIALS as usize]);
        range = all_first_in_2nd_window.aocl_range().unwrap();
        assert_eq!(8, range.0);
        assert_eq!(257 * u64::from(BATCH_SIZE) - 1, range.1);
    }

    #[test]
    fn range_with_aocl_leaf_indices_ms_beginning() {
        for leaf_index in 0..100 {
            let ais = AbsoluteIndexSet::compute(
                Digest::default(),
                Digest::default(),
                Digest::default(),
                leaf_index,
            );
            let (min, max) = ais.aocl_range().unwrap();
            assert!(leaf_index >= min);
            assert!(leaf_index <= max);
        }
    }

    #[proptest]
    fn test_arbitrary_from_aocl_index_u8(
        #[strategy(arb::<Vec<u8>>())] data: Vec<u8>,
        #[strategy(0..(u64::from(u8::MAX)))] aocl_index: u64,
    ) {
        range_prop(data, aocl_index)?;
    }

    #[proptest]
    fn test_arbitrary_from_aocl_index_u16(
        #[strategy(arb::<Vec<u8>>())] data: Vec<u8>,
        #[strategy(0..(u64::from(u16::MAX)))] aocl_index: u64,
    ) {
        range_prop(data, aocl_index)?;
    }

    #[proptest]
    fn test_arbitrary_from_aocl_index_u32(
        #[strategy(arb::<Vec<u8>>())] data: Vec<u8>,
        #[strategy(0..(u64::from(u32::MAX)))] aocl_index: u64,
    ) {
        range_prop(data, aocl_index)?;
    }

    #[proptest]
    fn test_arbitrary_from_aocl_index_full_range(
        #[strategy(arb::<Vec<u8>>())] data: Vec<u8>,
        #[strategy(arb())] aocl_index: u64,
    ) {
        range_prop(data, aocl_index)?;
    }

    fn range_prop(data: Vec<u8>, aocl_index: u64) -> std::result::Result<(), TestCaseError> {
        // Create an Unstructured instance from the arbitrary data
        let mut unstructured = Unstructured::new(&data);

        // Call the function
        let (min, max) = AbsoluteIndexSet::arbitrary_from_aocl_index(&mut unstructured, aocl_index)
            .unwrap()
            .aocl_range()
            .unwrap();

        prop_assert!(aocl_index >= min);
        prop_assert!(aocl_index <= max);
        prop_assert!(max > min);
        let anonymity_set_size = max - min + 1;
        prop_assert!(
            anonymity_set_size >= u64::from(BATCH_SIZE),
            "Minimum anonymity set is BATCH_SIZE"
        );

        let max_anonymity_size =
            (2 * (u64::from(WINDOW_SIZE) / u64::from(CHUNK_SIZE)) - 1) * u64::from(BATCH_SIZE);
        prop_assert!(
            anonymity_set_size <= max_anonymity_size,
            "Anonymity set size ({anonymity_set_size}) cannot exceed max size ({max_anonymity_size})"
        );

        Ok(())
    }
}