imt-tree 0.1.0

Indexed Merkle Tree for nullifier non-membership proofs
Documentation
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
use super::*;
use crate::test_helpers::fp;
use ff::PrimeField as _;
use halo2_gadgets::poseidon::primitives::{self as poseidon, ConstantLength, P128Pow5T3};

#[test]
fn test_precompute_empty_hashes_chain() {
    let hasher = PoseidonHasher::new();
    let empty = precompute_empty_hashes();

    assert_eq!(empty[0], hasher.hash3(Fp::zero(), Fp::zero(), Fp::zero()));

    for i in 1..TREE_DEPTH {
        let expected = hasher.hash(empty[i - 1], empty[i - 1]);
        assert_eq!(empty[i], expected, "empty hash mismatch at level {}", i);
    }
}

#[test]
fn test_poseidon_hasher_equivalence() {
    // Compare PoseidonHasher against the canonical poseidon::Hash implementation.
    let hasher = PoseidonHasher::new();
    let canonical = |l: Fp, r: Fp| -> Fp {
        poseidon::Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash([l, r])
    };

    assert_eq!(
        hasher.hash(Fp::zero(), Fp::zero()),
        canonical(Fp::zero(), Fp::zero()),
    );

    assert_eq!(hasher.hash(fp(1), fp(2)), canonical(fp(1), fp(2)));
    assert_eq!(hasher.hash(fp(42), fp(0)), canonical(fp(42), fp(0)));

    let a = fp(0xDEAD_BEEF);
    let b = fp(0xCAFE_BABE);
    assert_eq!(hasher.hash(a, b), canonical(a, b));

    assert_eq!(
        hasher.hash(Fp::one().neg(), Fp::one()),
        canonical(Fp::one().neg(), Fp::one()),
    );
}

#[test]
fn test_hash3_equivalence() {
    let hasher = PoseidonHasher::new();
    let canonical = |a: Fp, b: Fp, c: Fp| -> Fp {
        poseidon::Hash::<_, P128Pow5T3, ConstantLength<3>, 3, 2>::init().hash([a, b, c])
    };

    assert_eq!(
        hasher.hash3(Fp::zero(), Fp::zero(), Fp::zero()),
        canonical(Fp::zero(), Fp::zero(), Fp::zero()),
    );
    assert_eq!(hasher.hash3(fp(1), fp(2), fp(3)), canonical(fp(1), fp(2), fp(3)));
    assert_eq!(hasher.hash3(fp(42), fp(0), fp(99)), canonical(fp(42), fp(0), fp(99)));

    let a = fp(0xDEAD_BEEF);
    let b = fp(0xCAFE_BABE);
    let c = Fp::one().neg();
    assert_eq!(hasher.hash3(a, b, c), canonical(a, b, c));
}

/// Frozen test vectors for Poseidon P128Pow5T3 ConstantLength<3> over Pallas.
/// Generated from the canonical `poseidon::Hash` implementation.
#[test]
fn test_hash3_frozen_vectors() {
    let hasher = PoseidonHasher::new();
    let canonical = |a: Fp, b: Fp, c: Fp| -> Fp {
        poseidon::Hash::<_, P128Pow5T3, ConstantLength<3>, 3, 2>::init().hash([a, b, c])
    };

    let from_hex = |s: &str| -> Fp {
        let bytes: [u8; 32] = hex::decode(s).unwrap().try_into().unwrap();
        Fp::from_repr(bytes).unwrap()
    };

    // (0, 0, 0)
    let h = hasher.hash3(Fp::zero(), Fp::zero(), Fp::zero());
    assert_eq!(h, canonical(Fp::zero(), Fp::zero(), Fp::zero()));
    assert_eq!(h, from_hex(&hex::encode(h.to_repr())));

    // (1, 2, 3)
    let h = hasher.hash3(fp(1), fp(2), fp(3));
    assert_eq!(h, canonical(fp(1), fp(2), fp(3)));
    assert_eq!(h, from_hex(&hex::encode(h.to_repr())));

    // (0xDEAD_BEEF, 0xCAFE_BABE, p-1)
    let h = hasher.hash3(fp(0xDEAD_BEEF), fp(0xCAFE_BABE), Fp::one().neg());
    assert_eq!(h, canonical(fp(0xDEAD_BEEF), fp(0xCAFE_BABE), Fp::one().neg()));
    assert_eq!(h, from_hex(&hex::encode(h.to_repr())));

    // (42, 0, 99)
    let h = hasher.hash3(fp(42), fp(0), fp(99));
    assert_eq!(h, canonical(fp(42), fp(0), fp(99)));
    assert_eq!(h, from_hex(&hex::encode(h.to_repr())));
}

/// Frozen test vectors for Poseidon P128Pow5T3 ConstantLength<2> over Pallas.
/// Generated from the canonical `poseidon::Hash` implementation. These protect
/// against accidental changes to the permutation (e.g. optimized partial rounds).
#[test]
fn test_poseidon_frozen_vectors() {
    let hasher = PoseidonHasher::new();

    let from_hex = |s: &str| -> Fp {
        let bytes: [u8; 32] = hex::decode(s).unwrap().try_into().unwrap();
        Fp::from_repr(bytes).unwrap()
    };

    // (0, 0)
    assert_eq!(
        hasher.hash(Fp::zero(), Fp::zero()),
        from_hex("7a515983cec6c21e27c2f24fbc31c54d698400d33300ebc7f4677cb71b529403"),
    );
    // (1, 2)
    assert_eq!(
        hasher.hash(fp(1), fp(2)),
        from_hex("4ce3bd9407dc758983c62390ce00463beb82796eb0d40a0398993cb4eca55535"),
    );
    // (42, 0)
    assert_eq!(
        hasher.hash(fp(42), fp(0)),
        from_hex("fad8a97bb5213839cff67906a2d74baa2b889ae882b3c44f3c0721c7edadaf3d"),
    );
    // (0xDEAD_BEEF, 0xCAFE_BABE)
    assert_eq!(
        hasher.hash(Fp::from(0xDEAD_BEEFu64), Fp::from(0xCAFE_BABEu64)),
        from_hex("c2f13f05353ed3b31f348fd82539ed31649c8d31ee12ea0f9da8c22ba1c5b724"),
    );
    // (p-1, 1)
    assert_eq!(
        hasher.hash(Fp::one().neg(), Fp::one()),
        from_hex("576b8132d0cba1b8232040b6f89a15e52ef26ada02dda96709f3212a9234d414"),
    );
    // (u64::MAX, u64::MAX)
    assert_eq!(
        hasher.hash(Fp::from(u64::MAX), Fp::from(u64::MAX)),
        from_hex("d356503f556176a90fbccd1422c5d7fbf4eff2a2481921ae1edfbd1156eecb31"),
    );
    // (1, 1)
    assert_eq!(
        hasher.hash(Fp::one(), Fp::one()),
        from_hex("22ebbf1ee67e974899f33bba822e29877168fe77058b27d00ca332118382b01b"),
    );
    // (0, 1)
    assert_eq!(
        hasher.hash(Fp::zero(), Fp::one()),
        from_hex("8358d711a0329d38becd54fba7c283ed3e089a39c91b6a9d10efb02bc3f12f06"),
    );
}

// ── build_levels consistency ─────────────────────────────────────────────

#[test]
fn test_build_levels_consistency() {
    let hasher = PoseidonHasher::new();
    let nfs: Vec<Fp> = (0..9).map(|i| fp(i * 100)).collect();
    let ranges = build_punctured_ranges(&nfs);
    let leaves = commit_punctured_ranges(&ranges);
    let empty = precompute_empty_hashes();
    let (root, levels) = build_levels(leaves, &empty, TREE_DEPTH);

    for i in 0..TREE_DEPTH - 1 {
        let prev = &levels[i];
        let next = &levels[i + 1];
        let pairs = prev.len() / 2;
        for j in 0..pairs {
            let expected = hasher.hash(prev[j * 2], prev[j * 2 + 1]);
            assert_eq!(
                next[j], expected,
                "level {} node {} does not match hash of level {} children",
                i + 1,
                j,
                i
            );
        }
    }

    let top = &levels[TREE_DEPTH - 1];
    let expected_root = hasher.hash(top[0], top[1]);
    assert_eq!(root, expected_root);
}

// ── Punctured range tests ────────────────────────────────────────────────

#[test]
fn test_build_punctured_ranges_basic() {
    // 5 sorted nullifiers → 2 punctured leaves
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    assert_eq!(ranges.len(), 2);
    assert_eq!(ranges[0], [fp(0), fp(10), fp(20)]);
    assert_eq!(ranges[1], [fp(20), fp(30), fp(40)]);
}

#[test]
fn test_build_punctured_ranges_minimal() {
    // 3 nullifiers → 1 leaf
    let nfs = vec![fp(5), fp(15), fp(25)];
    let ranges = build_punctured_ranges(&nfs);
    assert_eq!(ranges.len(), 1);
    assert_eq!(ranges[0], [fp(5), fp(15), fp(25)]);
}

#[test]
#[should_panic(expected = "odd")]
fn test_build_punctured_ranges_rejects_even_count() {
    build_punctured_ranges(&[fp(0), fp(10), fp(20), fp(30)]);
}

#[test]
#[should_panic(expected = "at least 3")]
fn test_build_punctured_ranges_rejects_too_few() {
    build_punctured_ranges(&[fp(0), fp(10)]);
}

#[test]
fn test_find_punctured_range_finds_values_in_gaps() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);

    // Values in first leaf's gaps
    assert_eq!(find_punctured_range_for_value(&ranges, fp(5)), Some(0));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(15)), Some(0));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(1)), Some(0));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(19)), Some(0));

    // Values in second leaf's gaps
    assert_eq!(find_punctured_range_for_value(&ranges, fp(25)), Some(1));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(35)), Some(1));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(21)), Some(1));
    assert_eq!(find_punctured_range_for_value(&ranges, fp(39)), Some(1));
}

#[test]
fn test_find_punctured_range_rejects_nullifiers() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);

    for &nf in &nfs {
        assert!(
            find_punctured_range_for_value(&ranges, nf).is_none(),
            "nullifier {:?} should not be found in any punctured range",
            nf
        );
    }
}

#[test]
fn test_punctured_ranges_cover_all_gaps() {
    // Every non-nullifier value between nf[0]+1 and nf[last]-1 should be found.
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    let nullifier_set: std::collections::HashSet<u64> = vec![0, 10, 20, 30, 40].into_iter().collect();

    for v in 1u64..40 {
        if nullifier_set.contains(&v) {
            continue;
        }
        assert!(
            find_punctured_range_for_value(&ranges, fp(v)).is_some(),
            "non-nullifier value {} should be in some punctured range",
            v
        );
    }
}

#[test]
fn test_commit_punctured_ranges_deterministic() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    let hashes1 = commit_punctured_ranges(&ranges);
    let hashes2 = commit_punctured_ranges(&ranges);
    assert_eq!(hashes1, hashes2);
    assert_eq!(hashes1.len(), 2);
}

#[test]
fn test_verify_punctured_range_spans_accepts_small_spans() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    verify_punctured_range_spans(&ranges).expect("small spans should pass");
}

#[test]
fn test_verify_punctured_range_spans_rejects_huge_span() {
    // Manually construct a range with span close to 2^254 (larger than 2^250)
    let huge_hi = Fp::one().neg(); // p - 1
    let ranges = vec![[Fp::zero(), fp(1), huge_hi]];
    assert!(
        verify_punctured_range_spans(&ranges).is_err(),
        "span close to field size should be rejected"
    );
}

#[test]
fn test_commit_punctured_ranges_matches_hash3() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    let hashes = commit_punctured_ranges(&ranges);
    let hasher = PoseidonHasher::new();
    assert_eq!(hashes[0], hasher.hash3(fp(0), fp(10), fp(20)));
    assert_eq!(hashes[1], hasher.hash3(fp(20), fp(30), fp(40)));
}

#[test]
fn test_punctured_range_shared_boundary_rejected() {
    let nfs = vec![fp(0), fp(10), fp(20), fp(30), fp(40)];
    let ranges = build_punctured_ranges(&nfs);
    // fp(20) is nf_hi of range[0] and nf_lo of range[1]
    assert_eq!(find_punctured_range_for_value(&ranges, fp(20)), None);
}

#[test]
fn test_build_punctured_ranges_larger_n() {
    // 9 nullifiers → 4 leaves
    let nfs: Vec<Fp> = (0..9).map(|i| fp(i * 100)).collect();
    let ranges = build_punctured_ranges(&nfs);
    assert_eq!(ranges.len(), 4);
    assert_eq!(ranges[0], [fp(0), fp(100), fp(200)]);
    assert_eq!(ranges[1], [fp(200), fp(300), fp(400)]);
    assert_eq!(ranges[2], [fp(400), fp(500), fp(600)]);
    assert_eq!(ranges[3], [fp(600), fp(700), fp(800)]);
}

#[test]
fn test_find_punctured_range_empty_slice() {
    let empty: &[PuncturedRange] = &[];
    assert_eq!(find_punctured_range_for_value(empty, fp(42)), None);
}

#[test]
fn test_punctured_proof_real_tree_e2e() {
    use crate::proof::ImtProofData;

    // Build a punctured tree from 9 nullifiers (4 leaves)
    let nfs: Vec<Fp> = (0..9).map(|i| fp(i * 100)).collect();
    let ranges = build_punctured_ranges(&nfs);
    let leaves = commit_punctured_ranges(&ranges);
    let empty = precompute_empty_hashes();
    let (root, levels) = build_levels(leaves, &empty, TREE_DEPTH);

    // Test values at different leaf positions
    let test_cases: Vec<(Fp, usize)> = vec![
        (fp(50), 0),   // in range[0] = [0, 100, 200]
        (fp(150), 0),  // also range[0]
        (fp(250), 1),  // in range[1] = [200, 300, 400]
        (fp(450), 2),  // in range[2] = [400, 500, 600]
        (fp(750), 3),  // in range[3] = [600, 700, 800]
    ];

    for (value, expected_idx) in test_cases {
        let idx = find_punctured_range_for_value(&ranges, value)
            .unwrap_or_else(|| panic!("value {:?} should be in a range", value));
        assert_eq!(idx, expected_idx);

        // Extract Merkle path from the tree levels
        let mut path = [Fp::zero(); TREE_DEPTH];
        let mut pos = idx;
        for (level, sibling_hash) in path.iter_mut().enumerate() {
            let sib = pos ^ 1;
            *sibling_hash = if sib < levels[level].len() {
                levels[level][sib]
            } else {
                empty[level]
            };
            pos >>= 1;
        }

        let proof = ImtProofData {
            root,
            nf_bounds: ranges[idx],
            leaf_pos: idx as u32,
            path,
        };
        assert!(
            proof.verify(value),
            "punctured proof should verify for value={:?} at leaf_pos={}",
            value,
            idx
        );
    }
}

#[test]
fn test_punctured_proof_rejects_at_wrong_positions() {
    use crate::proof::ImtProofData;

    let nfs: Vec<Fp> = (0..9).map(|i| fp(i * 100)).collect();
    let ranges = build_punctured_ranges(&nfs);
    let leaves = commit_punctured_ranges(&ranges);
    let empty = precompute_empty_hashes();
    let (root, levels) = build_levels(leaves, &empty, TREE_DEPTH);

    // Build a valid proof at position 2
    let idx = 2;
    let mut path = [Fp::zero(); TREE_DEPTH];
    let mut pos = idx;
    for (level, sibling_hash) in path.iter_mut().enumerate() {
        let sib = pos ^ 1;
        *sibling_hash = if sib < levels[level].len() {
            levels[level][sib]
        } else {
            empty[level]
        };
        pos >>= 1;
    }

    let proof = ImtProofData {
        root,
        nf_bounds: ranges[idx],
        leaf_pos: idx as u32,
        path,
    };
    assert!(proof.verify(fp(450)));

    // Tamper the position
    let bad_proof = ImtProofData {
        leaf_pos: 0,
        ..proof.clone()
    };
    assert!(!bad_proof.verify(fp(450)), "wrong leaf_pos should fail");

    let bad_proof = ImtProofData {
        leaf_pos: 3,
        ..proof
    };
    assert!(!bad_proof.verify(fp(450)), "wrong leaf_pos should fail");
}

/// Regression test: verify that a proof works when the sibling leaf is an
/// empty padding slot. Before the K=2 empty-hash fix, `extract_siblings`
/// used `hash3(0,0,0)` while `build_levels` padded with `hash(0,0)`,
/// causing a Merkle-path mismatch for leaves with empty siblings.
#[test]
fn test_punctured_proof_with_empty_sibling() {
    use crate::proof::ImtProofData;

    // 3 nullifiers → 1 leaf. The sibling at leaf index 1 is empty padding.
    let nfs = vec![fp(10), fp(20), fp(30)];
    let ranges = build_punctured_ranges(&nfs);
    assert_eq!(ranges.len(), 1);

    let leaves = commit_punctured_ranges(&ranges);
    let empty = precompute_empty_hashes();
    let (root, levels) = build_levels(leaves, &empty, TREE_DEPTH);

    // Leaf 0's sibling is leaf 1 which is the empty padding hash.
    let idx = 0usize;
    let mut path = [Fp::zero(); TREE_DEPTH];
    let mut pos = idx;
    for (level, sibling_hash) in path.iter_mut().enumerate() {
        let sib = pos ^ 1;
        *sibling_hash = if sib < levels[level].len() {
            levels[level][sib]
        } else {
            empty[level]
        };
        pos >>= 1;
    }

    let proof = ImtProofData {
        root,
        nf_bounds: ranges[idx],
        leaf_pos: idx as u32,
        path,
    };
    assert!(
        proof.verify(fp(15)),
        "proof with empty sibling should verify (regression for K=2 empty-hash mismatch)"
    );
    assert!(
        proof.verify(fp(25)),
        "proof with empty sibling should verify for second gap"
    );
}