commonware-storage 2026.4.0

Persist and retrieve data from an abstract store.
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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
//! Stateless Binary Merkle Tree (BMT).
//!
//! The Binary Merkle Tree is constructed level-by-level. The first level consists of position-hashed leaf digests.
//! On each additional level, pairs of nodes are hashed from the previous level (if a level contains an odd
//! number of nodes, the last node is duplicated). The finalized root of the tree incorporates the leaf count
//! to prevent proof malleability: `root = hash(leaf_count || tree_root)`.
//!
//! For example, given three leaves A, B, and C, the tree is constructed as follows:
//!
//! ```text
//!     Level 2 (tree_root):  [hash(hash(hash(0,A),hash(1,B)),hash(hash(2,C),hash(2,C)))]
//!     Level 1:              [hash(hash(0,A),hash(1,B)),hash(hash(2,C),hash(2,C))]
//!     Level 0 (leaves):     [hash(0,A),hash(1,B),hash(2,C)]
//!     Finalized root:       hash(3 || tree_root)
//! ```
//!
//! A proof for one or more leaves is generated by collecting the siblings needed to reconstruct the root.
//! An external process can then use this proof (with some trusted root) to verify that the leaves
//! are part of the tree.
//!
//! # Example
//!
//! ```rust
//! use commonware_storage::bmt::{Builder, Tree};
//! use commonware_cryptography::{Sha256, sha256::Digest, Hasher as _};
//!
//! // Create transactions and compute their digests
//! let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
//! let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();
//!
//! // Build a Merkle Tree from the digests
//! let mut builder = Builder::<Sha256>::new(digests.len());
//! for digest in &digests {
//!    builder.add(digest);
//! }
//! let tree = builder.build();
//! let root = tree.root();
//!
//! // Generate a proof for leaf at index 1
//! let mut hasher = Sha256::default();
//! let proof = tree.proof(1).unwrap();
//! assert!(proof.verify_element_inclusion(&mut hasher, &digests[1], 1, &root).is_ok());
//! ```

use alloc::collections::btree_set::BTreeSet;
use commonware_codec::{EncodeSize, Read, ReadExt, ReadRangeExt, Write};
use commonware_cryptography::{Digest, Hasher};
use commonware_runtime::{Buf, BufMut};
use commonware_utils::{non_empty_vec, vec::NonEmptyVec};
use thiserror::Error;

/// There should never be more than 255 levels in a proof (would mean the Binary Merkle Tree
/// has more than 2^255 leaves).
pub const MAX_LEVELS: usize = u8::MAX as usize;

/// Errors that can occur when working with a Binary Merkle Tree (BMT).
#[derive(Error, Debug)]
pub enum Error {
    #[error("invalid position: {0}")]
    InvalidPosition(u32),
    #[error("invalid proof: {0} != {1}")]
    InvalidProof(String, String),
    #[error("no leaves")]
    NoLeaves,
    #[error("unaligned proof")]
    UnalignedProof,
    #[error("duplicate position: {0}")]
    DuplicatePosition(u32),
}

/// Constructor for a Binary Merkle Tree (BMT).
pub struct Builder<H: Hasher> {
    hasher: H,
    leaves: Vec<H::Digest>,
}

impl<H: Hasher> Builder<H> {
    /// Creates a new Binary Merkle Tree builder.
    pub fn new(leaves: usize) -> Self {
        Self {
            hasher: H::new(),
            leaves: Vec::with_capacity(leaves),
        }
    }

    /// Adds a leaf to the Binary Merkle Tree.
    ///
    /// When added, the leaf is hashed with its position.
    pub fn add(&mut self, leaf: &H::Digest) -> u32 {
        let position: u32 = self.leaves.len().try_into().expect("too many leaves");
        self.hasher.update(&position.to_be_bytes());
        self.hasher.update(leaf);
        self.leaves.push(self.hasher.finalize());
        position
    }

    /// Builds the Binary Merkle Tree.
    ///
    /// It is valid to build a tree with no leaves, in which case
    /// just an "empty" node is included (no leaves will be provable).
    pub fn build(self) -> Tree<H::Digest> {
        Tree::new(self.hasher, self.leaves)
    }
}

/// Constructed Binary Merkle Tree (BMT).
#[derive(Clone, Debug)]
pub struct Tree<D: Digest> {
    /// Records whether the tree is empty.
    empty: bool,

    /// The digests at each level of the tree (from leaves to root).
    levels: NonEmptyVec<NonEmptyVec<D>>,

    /// The finalized root digest, which incorporates the leaf count.
    ///
    /// This is computed as `H(leaf_count || tree_root)` to prevent
    /// proof malleability where proofs that declare different leaf
    /// counts could verify against the same root.
    root: D,
}

impl<D: Digest> Tree<D> {
    /// Builds a Merkle Tree from a slice of position-hashed leaf digests.
    fn new<H: Hasher<Digest = D>>(mut hasher: H, mut leaves: Vec<D>) -> Self {
        // If no leaves, add an empty node.
        //
        // Because this node only includes a position, there is no way a valid proof
        // can be generated that references it.
        let mut empty = false;
        let leaf_count = leaves.len() as u32;
        if leaves.is_empty() {
            leaves.push(hasher.finalize());
            empty = true;
        }

        // Create the first level
        let mut levels = non_empty_vec![non_empty_vec![@leaves]];

        // Construct the tree level-by-level
        let mut current_level = levels.last();
        while !current_level.is_singleton() {
            let mut next_level = Vec::with_capacity(current_level.len().get().div_ceil(2));
            for chunk in current_level.chunks(2) {
                // Hash the left child
                hasher.update(&chunk[0]);

                // Hash the right child
                if chunk.len() == 2 {
                    hasher.update(&chunk[1]);
                } else {
                    // If no right child exists, duplicate left child.
                    hasher.update(&chunk[0]);
                };

                // Compute the parent digest
                next_level.push(hasher.finalize());
            }

            // Add the computed level to the tree
            levels.push(non_empty_vec![@next_level]);
            current_level = levels.last();
        }

        // Compute the finalized root: H(leaf_count || tree_root)
        // This binds the root to the tree size, preventing malleability attacks.
        let tree_root = levels.last().first();
        hasher.update(&leaf_count.to_be_bytes());
        hasher.update(tree_root);
        let root = hasher.finalize();

        Self {
            empty,
            levels,
            root,
        }
    }

    /// Returns the finalized root of the tree.
    ///
    /// The root incorporates the leaf count via `H(leaf_count || tree_root)`,
    /// which prevents proof malleability attacks where different tree sizes
    /// could produce valid proofs for the same root.
    pub const fn root(&self) -> D {
        self.root
    }

    /// Generates a Merkle proof for the leaf at `position`.
    ///
    /// This is a single-element multi-proof, which includes the minimal siblings
    /// needed to reconstruct the root.
    pub fn proof(&self, position: u32) -> Result<Proof<D>, Error> {
        self.multi_proof(core::iter::once(position))
    }

    /// Generates a Merkle range proof for a contiguous set of leaves from `start`
    /// to `end` (inclusive).
    ///
    /// The proof contains the minimal set of sibling digests needed to reconstruct
    /// the root for all elements in the range. This is more efficient than individual
    /// proofs when proving multiple consecutive elements.
    pub fn range_proof(&self, start: u32, end: u32) -> Result<Proof<D>, Error> {
        // For empty trees, return an empty proof
        if self.empty {
            if start == 0 && end == 0 {
                return Ok(Proof::default());
            }
            return Err(Error::InvalidPosition(start));
        }

        // Validate range bounds
        if start > end {
            return Err(Error::InvalidPosition(start));
        }
        let leaf_count = self.levels.first().len().get() as u32;
        if start >= leaf_count {
            return Err(Error::InvalidPosition(start));
        }
        if end >= leaf_count {
            return Err(Error::InvalidPosition(end));
        }

        // Compute required siblings without enumerating every leaf in the range.
        let sibling_positions = siblings_required_for_range_proof(leaf_count, start, end)?;
        let siblings: Vec<D> = sibling_positions
            .iter()
            .map(|&(level, index)| self.levels[level][index])
            .collect();

        Ok(Proof {
            leaf_count,
            siblings,
        })
    }

    /// Generates a Merkle proof for multiple non-contiguous leaves at the given `positions`.
    ///
    /// The proof contains the minimal set of sibling digests needed to reconstruct
    /// the root for all elements at the specified positions. This is more efficient
    /// than individual proofs when proving multiple elements because shared siblings
    /// are deduplicated.
    ///
    /// Positions are sorted internally; duplicate positions will return an error.
    pub fn multi_proof<I, P>(&self, positions: I) -> Result<Proof<D>, Error>
    where
        I: IntoIterator<Item = P>,
        P: core::borrow::Borrow<u32>,
    {
        let mut positions = positions.into_iter().peekable();

        // Handle empty positions first - can't prove zero elements
        let first = *positions.peek().ok_or(Error::NoLeaves)?.borrow();

        // Handle empty tree case
        if self.empty {
            return Err(Error::InvalidPosition(first));
        }

        let leaf_count = self.levels.first().len().get() as u32;

        // Get required sibling positions (this validates positions and checks for duplicates)
        let sibling_positions =
            siblings_required_for_multi_proof(leaf_count, positions.map(|p| *p.borrow()))?;

        // Collect sibling digests in order
        let siblings: Vec<D> = sibling_positions
            .iter()
            .map(|&(level, index)| self.levels[level][index])
            .collect();

        Ok(Proof {
            leaf_count,
            siblings,
        })
    }
}

/// A Merkle proof for multiple non-contiguous leaves in a Binary Merkle Tree.
///
/// This proof type is more space-efficient than generating individual proofs
/// for each leaf because sibling nodes that are shared between multiple paths
/// are deduplicated.
///
/// The proof contains the leaf count and sibling digests required for verification.
/// The leaf count is incorporated into the root hash during finalization, so
/// modifying it will cause verification to fail (preventing malleability attacks).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Proof<D: Digest> {
    /// The number of leaves in the tree.
    ///
    /// This value is incorporated into the root hash during finalization,
    /// so modifying it will cause verification to fail (prevents malleability).
    pub leaf_count: u32,

    /// The deduplicated sibling digests required to verify all elements,
    /// ordered by their position in the tree (level-major, then index within level).
    pub siblings: Vec<D>,
}

impl<D: Digest> Default for Proof<D> {
    fn default() -> Self {
        Self {
            leaf_count: 0,
            siblings: Vec::new(),
        }
    }
}

impl<D: Digest> Write for Proof<D> {
    fn write(&self, writer: &mut impl BufMut) {
        self.leaf_count.write(writer);
        self.siblings.write(writer);
    }
}

impl<D: Digest> Read for Proof<D> {
    /// The maximum number of items being proven.
    ///
    /// The upper bound on sibling hashes is derived as `max_items * MAX_LEVELS`.
    type Cfg = usize;

    fn read_cfg(
        reader: &mut impl Buf,
        max_items: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        let leaf_count = u32::read(reader)?;
        let max_siblings = max_items.saturating_mul(MAX_LEVELS);
        let siblings = Vec::<D>::read_range(reader, ..=max_siblings)?;
        Ok(Self {
            leaf_count,
            siblings,
        })
    }
}

impl<D: Digest> EncodeSize for Proof<D> {
    fn encode_size(&self) -> usize {
        self.leaf_count.encode_size() + self.siblings.encode_size()
    }
}

#[cfg(feature = "arbitrary")]
impl<D: Digest> arbitrary::Arbitrary<'_> for Proof<D>
where
    D: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        Ok(Self {
            leaf_count: u.arbitrary()?,
            siblings: u.arbitrary()?,
        })
    }
}

/// Returns the number of levels in a tree with `leaf_count` leaves.
/// A tree with 1 leaf has 1 level, a tree with 2 leaves has 2 levels, etc.
const fn levels_in_tree(leaf_count: u32) -> usize {
    (u32::BITS - (leaf_count.saturating_sub(1)).leading_zeros() + 1) as usize
}

/// Returns the sorted, deduplicated positions of siblings required to prove
/// inclusion of leaves at the given positions.
///
/// Each position in the result is encoded as `(level, index)` where level 0 is the leaf level.
fn siblings_required_for_multi_proof(
    leaf_count: u32,
    positions: impl IntoIterator<Item = u32>,
) -> Result<BTreeSet<(usize, usize)>, Error> {
    // Validate positions and check for duplicates.
    let mut current = BTreeSet::new();
    for pos in positions {
        if pos >= leaf_count {
            return Err(Error::InvalidPosition(pos));
        }
        if !current.insert(pos as usize) {
            return Err(Error::DuplicatePosition(pos));
        }
    }

    if current.is_empty() {
        return Err(Error::NoLeaves);
    }

    // Track positions we can compute at each level and record missing siblings.
    // This keeps the work proportional to the number of positions, not the tree size.
    let mut sibling_positions = BTreeSet::new();
    let levels_count = levels_in_tree(leaf_count);
    let mut level_size = leaf_count as usize;
    for level in 0..levels_count - 1 {
        for &index in &current {
            let sibling_index = if index.is_multiple_of(2) {
                if index + 1 < level_size {
                    index + 1
                } else {
                    index
                }
            } else {
                index - 1
            };

            if sibling_index != index && !current.contains(&sibling_index) {
                sibling_positions.insert((level, sibling_index));
            }
        }

        current = current.iter().map(|idx| idx / 2).collect();
        level_size = level_size.div_ceil(2);
    }

    Ok(sibling_positions)
}

/// Returns the sorted, deduplicated positions of siblings required to prove
/// inclusion of a contiguous range of leaves from `start` to `end` (inclusive).
fn siblings_required_for_range_proof(
    leaf_count: u32,
    start: u32,
    end: u32,
) -> Result<BTreeSet<(usize, usize)>, Error> {
    if leaf_count == 0 {
        return Err(Error::NoLeaves);
    }
    if start > end {
        return Err(Error::InvalidPosition(start));
    }
    if start >= leaf_count {
        return Err(Error::InvalidPosition(start));
    }
    if end >= leaf_count {
        return Err(Error::InvalidPosition(end));
    }

    let mut sibling_positions = BTreeSet::new();
    let levels_count = levels_in_tree(leaf_count);
    let mut level_start = start as usize;
    let mut level_end = end as usize;
    let mut level_size = leaf_count as usize;

    for level in 0..levels_count - 1 {
        if !level_start.is_multiple_of(2) {
            sibling_positions.insert((level, level_start - 1));
        }
        if level_end.is_multiple_of(2) {
            let right = level_end + 1;
            if right < level_size {
                sibling_positions.insert((level, right));
            }
        }

        level_start /= 2;
        level_end /= 2;
        level_size = level_size.div_ceil(2);
    }

    Ok(sibling_positions)
}

impl<D: Digest> Proof<D> {
    /// Verifies that a given `leaf` at `position` is included in a Binary Merkle Tree
    /// with `root` using the provided `hasher`.
    ///
    /// The proof consists of sibling hashes stored from the leaf up to the root. At each
    /// level, if the current node is a left child (even index), the sibling is combined
    /// to the right; if it is a right child (odd index), the sibling is combined to the
    /// left.
    ///
    /// The `leaf_count` stored in the proof is incorporated into the finalized root
    /// computation, so any modification to it will cause verification to fail.
    pub fn verify_element_inclusion<H: Hasher<Digest = D>>(
        &self,
        hasher: &mut H,
        leaf: &D,
        mut position: u32,
        root: &D,
    ) -> Result<(), Error> {
        // Validate position
        if position >= self.leaf_count {
            return Err(Error::InvalidPosition(position));
        }

        // Compute the position-hashed leaf
        hasher.update(&position.to_be_bytes());
        hasher.update(leaf);
        let mut computed = hasher.finalize();

        // Track level size to handle odd-sized levels
        let mut level_size = self.leaf_count as usize;
        let mut sibling_iter = self.siblings.iter();

        // Traverse from leaf to root
        while level_size > 1 {
            // Check if this is the last node at an odd-sized level (no real sibling)
            let is_last_odd = position.is_multiple_of(2) && position as usize + 1 >= level_size;

            let (left_node, right_node) = if is_last_odd {
                // Node is duplicated - no sibling consumed from proof
                (&computed, &computed)
            } else if position.is_multiple_of(2) {
                // Even position: sibling is to the right
                let sibling = sibling_iter.next().ok_or(Error::UnalignedProof)?;
                (&computed, sibling)
            } else {
                // Odd position: sibling is to the left
                let sibling = sibling_iter.next().ok_or(Error::UnalignedProof)?;
                (sibling, &computed)
            };

            // Compute the parent digest
            hasher.update(left_node);
            hasher.update(right_node);
            computed = hasher.finalize();

            // Move up the tree
            position /= 2;
            level_size = level_size.div_ceil(2);
        }

        // Ensure all siblings were consumed
        if sibling_iter.next().is_some() {
            return Err(Error::UnalignedProof);
        }

        // Finalize the root by incorporating the leaf count: H(leaf_count || tree_root)
        // This binds the proof to the specific tree size, preventing malleability attacks.
        hasher.update(&self.leaf_count.to_be_bytes());
        hasher.update(&computed);
        let finalized = hasher.finalize();

        if finalized == *root {
            Ok(())
        } else {
            Err(Error::InvalidProof(finalized.to_string(), root.to_string()))
        }
    }

    /// Verifies that the given `elements` at their respective positions are included
    /// in a Binary Merkle Tree with `root`.
    ///
    /// Elements can be provided in any order; positions are sorted internally.
    /// Duplicate positions will cause verification to fail.
    ///
    /// The `leaf_count` stored in the proof is incorporated into the finalized root
    /// computation, so any modification to it will cause verification to fail.
    pub fn verify_multi_inclusion<H: Hasher<Digest = D>>(
        &self,
        hasher: &mut H,
        elements: &[(D, u32)],
        root: &D,
    ) -> Result<(), Error> {
        // Handle empty case
        if elements.is_empty() {
            if self.leaf_count == 0 && self.siblings.is_empty() {
                // Compute finalized empty root: H(0 || empty_tree_root)
                let empty_tree_root = hasher.finalize();
                hasher.update(&0u32.to_be_bytes());
                hasher.update(&empty_tree_root);
                let finalized = hasher.finalize();
                if finalized == *root {
                    return Ok(());
                } else {
                    return Err(Error::InvalidProof(finalized.to_string(), root.to_string()));
                }
            }
            return Err(Error::NoLeaves);
        }

        // 1. Sort elements by position and check for duplicates/bounds
        let mut sorted: Vec<(u32, D)> = Vec::with_capacity(elements.len());
        for (leaf, position) in elements {
            if *position >= self.leaf_count {
                return Err(Error::InvalidPosition(*position));
            }
            hasher.update(&position.to_be_bytes());
            hasher.update(leaf);
            sorted.push((*position, hasher.finalize()));
        }
        sorted.sort_unstable_by_key(|(pos, _)| *pos);

        // Check for duplicates (adjacent elements with same position after sorting)
        for i in 1..sorted.len() {
            if sorted[i - 1].0 == sorted[i].0 {
                return Err(Error::DuplicatePosition(sorted[i].0));
            }
        }

        // 2. Iterate up the tree
        // Since we process left-to-right and parent_pos = pos/2, next_level stays sorted.
        let levels = levels_in_tree(self.leaf_count);
        let mut level_size = self.leaf_count;
        let mut sibling_iter = self.siblings.iter();
        let mut current = sorted;
        let mut next_level: Vec<(u32, D)> = Vec::with_capacity(current.len());

        for _ in 0..levels - 1 {
            let mut idx = 0;
            while idx < current.len() {
                let (pos, digest) = current[idx];
                let parent_pos = pos / 2;

                // Determine if we have the left or right child
                let (left, right) = if pos.is_multiple_of(2) {
                    // We are the LEFT child
                    let left = digest;

                    // Check if we have the right child in our current set
                    let right = if idx + 1 < current.len() && current[idx + 1].0 == pos + 1 {
                        idx += 1;
                        current[idx].1
                    } else if pos + 1 >= level_size {
                        // If no right child exists in tree, duplicate left
                        left
                    } else {
                        // Otherwise, must consume a sibling
                        *sibling_iter.next().ok_or(Error::UnalignedProof)?
                    };
                    (left, right)
                } else {
                    // We are the RIGHT child
                    // This implies the LEFT child was missing from 'current', so it must be a sibling.
                    let right = digest;
                    let left = *sibling_iter.next().ok_or(Error::UnalignedProof)?;
                    (left, right)
                };

                // Hash parent
                hasher.update(&left);
                hasher.update(&right);
                next_level.push((parent_pos, hasher.finalize()));

                idx += 1;
            }

            // Prepare for next level
            core::mem::swap(&mut current, &mut next_level);
            next_level.clear();
            level_size = level_size.div_ceil(2);
        }

        // 3. Verify root
        if sibling_iter.next().is_some() {
            return Err(Error::UnalignedProof);
        }

        if current.len() != 1 {
            return Err(Error::UnalignedProof);
        }

        // Finalize the root by incorporating the leaf count: H(leaf_count || tree_root)
        // This binds the proof to the specific tree size, preventing malleability attacks.
        let tree_root = current[0].1;
        hasher.update(&self.leaf_count.to_be_bytes());
        hasher.update(&tree_root);
        let finalized = hasher.finalize();

        if finalized == *root {
            Ok(())
        } else {
            Err(Error::InvalidProof(finalized.to_string(), root.to_string()))
        }
    }

    /// Verifies that a contiguous range of `leaves` starting at `position` are included
    /// in a Binary Merkle Tree with `root`.
    ///
    /// This is a convenience method for verifying range proofs. The leaves must be
    /// in order starting from `position`.
    ///
    /// The `leaf_count` stored in the proof is incorporated into the finalized root
    /// computation, so any modification to it will cause verification to fail.
    pub fn verify_range_inclusion<H: Hasher<Digest = D>>(
        &self,
        hasher: &mut H,
        position: u32,
        leaves: &[D],
        root: &D,
    ) -> Result<(), Error> {
        // For empty trees, only position 0 with empty leaves is valid
        if leaves.is_empty() && position != 0 {
            return Err(Error::InvalidPosition(position));
        }
        if !leaves.is_empty() {
            let leaves_len =
                u32::try_from(leaves.len()).map_err(|_| Error::InvalidPosition(position))?;
            let end = position
                .checked_add(leaves_len - 1)
                .ok_or(Error::InvalidPosition(position))?;
            if end >= self.leaf_count {
                return Err(Error::InvalidPosition(end));
            }
        }

        // Convert to format expected by verify_multi_inclusion
        let elements: Vec<(D, u32)> = leaves
            .iter()
            .enumerate()
            .map(|(i, leaf)| (*leaf, position + i as u32))
            .collect();
        self.verify_multi_inclusion(hasher, &elements, root)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use commonware_codec::{Decode, Encode};
    use commonware_cryptography::sha256::{Digest, Sha256};
    use rstest::rstest;

    /// Regression test for https://github.com/commonwarexyz/monorepo/issues/2837
    ///
    /// Before the fix, two proofs with identical siblings but different leaf_count
    /// values would both verify successfully against the same root, enabling
    /// proof malleability attacks.
    #[test]
    fn issue_2837_regression() {
        // Create a tree with 255 leaves (as in the issue report)
        let digests: Vec<Digest> = (0..255u32)
            .map(|i| Sha256::hash(&i.to_be_bytes()))
            .collect();

        let mut builder = Builder::<Sha256>::new(255);
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get a valid proof for position 0
        let original_proof = tree.proof(0).unwrap();
        assert_eq!(original_proof.leaf_count, 255);

        // Original proof should verify
        let mut hasher = Sha256::default();
        assert!(
            original_proof
                .verify_element_inclusion(&mut hasher, &digests[0], 0, &root)
                .is_ok(),
            "Original proof should verify"
        );

        // Create a malleated proof with leaf_count=254 but same siblings
        // (This is the exact attack from issue #2837)
        let malleated_proof = Proof {
            leaf_count: 254,
            siblings: original_proof.siblings.clone(),
        };

        // Malleated proof should NOT verify because the root now incorporates
        // the leaf_count: root = H(leaf_count || tree_root)
        let result = malleated_proof.verify_element_inclusion(&mut hasher, &digests[0], 0, &root);
        assert!(
            result.is_err(),
            "Malleated proof with wrong leaf_count must fail verification"
        );
    }

    #[test]
    fn test_tampered_proof_no_siblings() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();
        let element = &digests[0];

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Build proof
        let mut proof = tree.proof(0).unwrap();

        // Tamper with proof
        proof.siblings = Vec::new();

        // Fail verification with an empty proof.
        let mut hasher = Sha256::default();
        assert!(proof
            .verify_element_inclusion(&mut hasher, element, 0, &root)
            .is_err());
    }

    #[test]
    fn test_tampered_proof_extra_sibling() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();
        let element = &digests[0];

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Build proof
        let mut proof = tree.proof(0).unwrap();

        // Tamper with proof
        proof.siblings.push(*element);

        // Fail verification with extra sibling
        let mut hasher = Sha256::default();
        assert!(proof
            .verify_element_inclusion(&mut hasher, element, 0, &root)
            .is_err());
    }

    #[test]
    fn test_invalid_proof_wrong_element() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Generate a valid proof for leaf at index 2.
        let proof = tree.proof(2).unwrap();

        // Use a wrong element (e.g. hash of a different transaction).
        let mut hasher = Sha256::default();
        let wrong_leaf = Sha256::hash(b"wrong_tx");
        assert!(proof
            .verify_element_inclusion(&mut hasher, &wrong_leaf, 2, &root)
            .is_err());
    }

    #[test]
    fn test_invalid_proof_wrong_index() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Generate a valid proof for leaf at index 1.
        let proof = tree.proof(1).unwrap();

        // Use an incorrect index (e.g. 2 instead of 1).
        let mut hasher = Sha256::default();
        assert!(proof
            .verify_element_inclusion(&mut hasher, &digests[1], 2, &root)
            .is_err());
    }

    #[test]
    fn test_invalid_proof_wrong_root() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Generate a valid proof for leaf at index 0.
        let proof = tree.proof(0).unwrap();

        // Use a wrong root (hash of a different input).
        let mut hasher = Sha256::default();
        let wrong_root = Sha256::hash(b"wrong_root");
        assert!(proof
            .verify_element_inclusion(&mut hasher, &digests[0], 0, &wrong_root)
            .is_err());
    }

    #[test]
    fn test_invalid_proof_serialization_truncated() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Generate a valid proof for leaf at index 1.
        let proof = tree.proof(1).unwrap();
        let mut serialized = proof.encode();

        // Truncate one byte.
        serialized.truncate(serialized.len() - 1);
        assert!(Proof::<Digest>::decode_cfg(&mut serialized, &1).is_err());
    }

    #[test]
    fn test_invalid_proof_serialization_extra() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Generate a valid proof for leaf at index 1.
        let proof = tree.proof(1).unwrap();
        let mut serialized = proof.encode_mut();

        // Append an extra byte.
        serialized.extend_from_slice(&[0u8]);
        assert!(Proof::<Digest>::decode_cfg(&mut serialized, &1).is_err());
    }

    #[test]
    fn test_invalid_proof_modified_hash() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3", b"tx4"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Generate a valid proof for leaf at index 2.
        let mut proof = tree.proof(2).unwrap();

        // Modify the first hash in the proof.
        let mut hasher = Sha256::default();
        proof.siblings[0] = Sha256::hash(b"modified");
        assert!(proof
            .verify_element_inclusion(&mut hasher, &digests[2], 2, &root)
            .is_err());
    }

    #[test]
    fn test_odd_tree_duplicate_index_proof() {
        // Create transactions and digests
        let txs = [b"tx1", b"tx2", b"tx3"];
        let digests: Vec<Digest> = txs.iter().map(|tx| Sha256::hash(*tx)).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(txs.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // The tree was built with 3 leaves; index 2 is the last valid index.
        let proof = tree.proof(2).unwrap();

        // Verification should succeed for the proper index 2.
        let mut hasher = Sha256::default();
        assert!(proof
            .verify_element_inclusion(&mut hasher, &digests[2], 2, &root)
            .is_ok());

        // Should not be able to generate a proof for an out-of-range index (e.g. 3).
        assert!(tree.proof(3).is_err());

        // Attempting to verify using an out-of-range index (e.g. 3, which would correspond
        // to a duplicate leaf that doesn't actually exist) should fail.
        assert!(proof
            .verify_element_inclusion(&mut hasher, &digests[2], 3, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_basic() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Test range proof for elements 2-5
        let range_proof = tree.range_proof(2, 5).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..6];

        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_ok());

        // Serialize and deserialize
        let mut serialized = range_proof.encode();
        let deserialized = Proof::<Digest>::decode_cfg(&mut serialized, &4).unwrap();
        assert!(deserialized
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_ok());
    }

    #[test]
    fn test_range_proof_single_element() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Test single element range proof
        for (i, digest) in digests.iter().enumerate() {
            let range_proof = tree.range_proof(i as u32, i as u32).unwrap();
            let mut hasher = Sha256::default();

            let result =
                range_proof.verify_range_inclusion(&mut hasher, i as u32, &[*digest], &root);
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_range_proof_full_tree() {
        // Create test data
        let digests: Vec<Digest> = (0..7u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Test full tree range proof
        let range_proof = tree.range_proof(0, (digests.len() - 1) as u32).unwrap();
        let mut hasher = Sha256::default();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 0, &digests, &root)
            .is_ok());
    }

    #[test]
    fn test_range_proof_edge_cases() {
        // Create test data
        let digests: Vec<Digest> = (0..15u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test first half
        let range_proof = tree.range_proof(0, 7).unwrap();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 0, &digests[0..8], &root)
            .is_ok());

        // Test second half
        let range_proof = tree.range_proof(8, 14).unwrap();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 8, &digests[8..15], &root)
            .is_ok());

        // Test last elements
        let range_proof = tree.range_proof(13, 14).unwrap();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 13, &digests[13..15], &root)
            .is_ok());
    }

    #[test]
    fn test_range_proof_invalid_range() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Test invalid ranges
        assert!(tree.range_proof(8, 8).is_err()); // Start out of bounds
        assert!(tree.range_proof(0, 8).is_err()); // End out of bounds
        assert!(tree.range_proof(5, 8).is_err()); // End out of bounds
        assert!(tree.range_proof(2, 1).is_err()); // Start > end
    }

    #[test]
    fn test_range_proof_tampering() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof
        let range_proof = tree.range_proof(2, 4).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..5];

        // Test with wrong leaves
        let wrong_leaves = vec![
            Sha256::hash(b"wrong1"),
            Sha256::hash(b"wrong2"),
            Sha256::hash(b"wrong3"),
        ];
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, &wrong_leaves, &root)
            .is_err());

        // Test with wrong number of leaves
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, &digests[2..4], &root)
            .is_err());

        // Test with tampered proof
        let mut tampered_proof = range_proof.clone();
        assert!(!tampered_proof.siblings.is_empty());
        // Tamper with the first sibling
        tampered_proof.siblings[0] = Sha256::hash(b"tampered");
        assert!(tampered_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_err());

        // Test with wrong root
        let wrong_root = Sha256::hash(b"wrong_root");
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &wrong_root)
            .is_err());
    }

    #[test]
    fn test_range_proof_various_sizes() {
        // Test range proofs for trees of various sizes
        for tree_size in [1, 2, 3, 4, 5, 7, 8, 15, 16, 31, 32, 63, 64] {
            let digests: Vec<Digest> = (0..tree_size as u32)
                .map(|i| Sha256::hash(&i.to_be_bytes()))
                .collect();

            // Build tree
            let mut builder = Builder::<Sha256>::new(digests.len());
            for digest in &digests {
                builder.add(digest);
            }
            let tree = builder.build();
            let root = tree.root();
            let mut hasher = Sha256::default();

            // Test various range sizes
            for range_size in 1..=tree_size.min(8) {
                for start in 0..=(tree_size - range_size) {
                    let range_proof = tree
                        .range_proof(start as u32, (start + range_size - 1) as u32)
                        .unwrap();
                    let end = start + range_size;
                    assert!(
                        range_proof
                            .verify_range_inclusion(
                                &mut hasher,
                                start as u32,
                                &digests[start..end],
                                &root
                            )
                            .is_ok(),
                        "Failed for tree_size={tree_size}, start={start}, range_size={range_size}"
                    );
                }
            }
        }
    }

    #[test]
    fn test_range_proof_malicious_wrong_position() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof for position 2 to 4
        let range_proof = tree.range_proof(2, 4).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..5];

        // Try to verify with wrong position
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 3, range_leaves, &root)
            .is_err());
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 1, range_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_malicious_reordered_leaves() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof for position 2 to 4
        let range_proof = tree.range_proof(2, 4).unwrap();
        let mut hasher = Sha256::default();

        // Try to verify with reordered leaves
        let reordered_leaves = vec![digests[3], digests[2], digests[4]];
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, &reordered_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_malicious_extra_siblings() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof
        let mut range_proof = tree.range_proof(2, 3).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..4];

        // Tamper by adding extra siblings
        range_proof.siblings.push(Sha256::hash(b"extra"));
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_malicious_missing_siblings() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof for a single element (which needs siblings)
        let mut range_proof = tree.range_proof(2, 2).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..3];

        // The proof should have siblings
        assert!(!range_proof.siblings.is_empty());

        // Remove a sibling
        range_proof.siblings.pop();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_integer_overflow_protection() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Test overflow in range_proof generation
        assert!(tree.range_proof(u32::MAX, u32::MAX).is_err());
        assert!(tree.range_proof(u32::MAX - 1, u32::MAX).is_err());
        assert!(tree.range_proof(7, u32::MAX).is_err());
    }

    #[test]
    fn test_range_proof_malicious_wrong_tree_structure() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Get valid range proof
        let mut range_proof = tree.range_proof(2, 3).unwrap();
        let mut hasher = Sha256::default();
        let range_leaves = &digests[2..4];

        // Add extra sibling (simulating proof from different tree structure)
        range_proof.siblings.push(Sha256::hash(b"fake_level"));
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_err());

        // Remove a sibling
        let mut range_proof = tree.range_proof(2, 2).unwrap();
        let range_leaves = &digests[2..3];
        assert!(!range_proof.siblings.is_empty());
        range_proof.siblings.pop();
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 2, range_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_range_proof_boundary_conditions() {
        // Test various power-of-2 boundary conditions
        for tree_size in [1, 2, 4, 8, 16, 32] {
            let digests: Vec<Digest> = (0..tree_size as u32)
                .map(|i| Sha256::hash(&i.to_be_bytes()))
                .collect();

            // Build tree
            let mut builder = Builder::<Sha256>::new(digests.len());
            for digest in &digests {
                builder.add(digest);
            }
            let tree = builder.build();
            let root = tree.root();
            let mut hasher = Sha256::default();

            // Test edge cases
            // First element only
            let proof = tree.range_proof(0, 0).unwrap();
            assert!(proof
                .verify_range_inclusion(&mut hasher, 0, &digests[0..1], &root)
                .is_ok());

            // Last element only
            let last_idx = tree_size - 1;
            let proof = tree.range_proof(last_idx as u32, last_idx as u32).unwrap();
            assert!(proof
                .verify_range_inclusion(
                    &mut hasher,
                    last_idx as u32,
                    &digests[last_idx..tree_size],
                    &root
                )
                .is_ok());

            // Full tree
            let proof = tree.range_proof(0, (tree_size - 1) as u32).unwrap();
            assert!(proof
                .verify_range_inclusion(&mut hasher, 0, &digests, &root)
                .is_ok());
        }
    }

    #[test]
    fn test_empty_tree_proof() {
        // Build an empty tree
        let builder = Builder::<Sha256>::new(0);
        let tree = builder.build();

        // Empty tree should fail for any position since there are no elements
        assert!(tree.proof(0).is_err());
        assert!(tree.proof(1).is_err());
        assert!(tree.proof(100).is_err());
    }

    #[test]
    fn test_empty_tree_range_proof() {
        // Build an empty tree
        let builder = Builder::<Sha256>::new(0);
        let tree = builder.build();
        let root = tree.root();

        // Empty tree should return default proof only for (0, 0)
        let range_proof = tree.range_proof(0, 0).unwrap();
        assert!(range_proof.siblings.is_empty());
        assert_eq!(range_proof, Proof::default());

        // All other combinations should fail
        let invalid_ranges = vec![
            (0, 1),
            (0, 10),
            (1, 1),
            (1, 2),
            (5, 5),
            (10, 10),
            (0, u32::MAX),
            (u32::MAX, u32::MAX),
        ];
        for (start, end) in invalid_ranges {
            assert!(tree.range_proof(start, end).is_err());
        }

        // Verify empty range proof against empty tree root
        let mut hasher = Sha256::default();
        let empty_leaves: &[Digest] = &[];
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 0, empty_leaves, &root)
            .is_ok());

        // Should fail with non-empty leaves
        let non_empty_leaves = vec![Sha256::hash(b"leaf")];
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 0, &non_empty_leaves, &root)
            .is_err());

        // Should fail with wrong root
        let wrong_root = Sha256::hash(b"wrong");
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 0, empty_leaves, &wrong_root)
            .is_err());

        // Should fail with wrong position
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, 1, empty_leaves, &root)
            .is_err());
    }

    #[test]
    fn test_empty_range_proof_serialization() {
        let proof = Proof::<Digest>::default();
        let mut serialized = proof.encode();
        let deserialized = Proof::<Digest>::decode_cfg(&mut serialized, &0).unwrap();
        assert_eq!(proof, deserialized);
    }

    #[test]
    fn test_empty_tree_root_consistency() {
        // Create multiple empty trees and verify they have the same root
        let mut roots = Vec::new();
        for _ in 0..5 {
            let builder = Builder::<Sha256>::new(0);
            let tree = builder.build();
            roots.push(tree.root());
        }

        // All empty trees should have the same root
        for i in 1..roots.len() {
            assert_eq!(roots[0], roots[i]);
        }

        // The root should be the hash of empty data
        let mut hasher = Sha256::default();
        hasher.update(0u32.to_be_bytes().as_slice());
        hasher.update(Sha256::hash(b"").as_ref());
        let expected_root = hasher.finalize();
        assert_eq!(roots[0], expected_root);
    }

    #[rstest]
    #[case::need_left_sibling(1, 2)] // Range starting at odd index (needs left sibling)
    #[case::need_right_sibling(4, 4)] // Range starting at even index
    #[case::full_tree(0, 16)] // Full tree (no siblings needed at leaf level)
    fn test_range_proof_siblings_usage(#[case] start: u32, #[case] count: u32) {
        // This test ensures that all siblings in a range proof are actually used during verification
        let digests: Vec<Digest> = (0..16u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        let range_proof = tree.range_proof(start, start + count - 1).unwrap();
        let end = start as usize + count as usize;

        // Verify the proof works
        assert!(range_proof
            .verify_range_inclusion(&mut hasher, start, &digests[start as usize..end], &root)
            .is_ok());

        // For each sibling, try tampering with it and verify the proof fails
        for sibling_idx in 0..range_proof.siblings.len() {
            let mut tampered_proof = range_proof.clone();
            tampered_proof.siblings[sibling_idx] = Sha256::hash(b"tampered");
            assert!(tampered_proof
                .verify_range_inclusion(&mut hasher, start, &digests[start as usize..end], &root)
                .is_err());
        }
    }

    // Test trees with odd sizes that require duplicate nodes
    #[rstest]
    fn test_range_proof_duplicate_node_edge_cases(
        #[values(3, 5, 7, 9, 11, 13, 15)] tree_size: usize,
    ) {
        let digests: Vec<Digest> = (0..tree_size as u32)
            .map(|i| Sha256::hash(&i.to_be_bytes()))
            .collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test range including the last element (which may require duplicate handling)
        let start = tree_size - 2;
        let proof = tree
            .range_proof(start as u32, (tree_size - 1) as u32)
            .unwrap();
        assert!(proof
            .verify_range_inclusion(&mut hasher, start as u32, &digests[start..tree_size], &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_basic() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();

        // Test multi-proof for non-contiguous positions [0, 3, 5]
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();
        let mut hasher = Sha256::default();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_single_element() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test single element multi-proof for each position
        for (i, digest) in digests.iter().enumerate() {
            let multi_proof = tree.multi_proof([i as u32]).unwrap();
            let elements = [(*digest, i as u32)];
            assert!(
                multi_proof
                    .verify_multi_inclusion(&mut hasher, &elements, &root)
                    .is_ok(),
                "Failed for position {i}"
            );
        }
    }

    #[test]
    fn test_multi_proof_all_elements() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test multi-proof for all elements
        let positions: Vec<u32> = (0..digests.len() as u32).collect();
        let multi_proof = tree.multi_proof(&positions).unwrap();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_ok());

        // When proving all elements, we shouldn't need any siblings (all can be computed)
        assert!(multi_proof.siblings.is_empty());
    }

    #[test]
    fn test_multi_proof_adjacent_elements() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test adjacent positions (should deduplicate shared siblings)
        let positions = [2, 3];
        let multi_proof = tree.multi_proof(positions).unwrap();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_sparse_positions() {
        // Create test data
        let digests: Vec<Digest> = (0..16u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test widely separated positions
        let positions = [0, 7, 8, 15];
        let multi_proof = tree.multi_proof(positions).unwrap();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_empty_tree() {
        // Build empty tree
        let builder = Builder::<Sha256>::new(0);
        let tree = builder.build();

        // Empty tree with empty positions should return NoLeaves error
        // (we can't prove zero elements)
        assert!(matches!(
            tree.multi_proof(std::iter::empty::<u32>()),
            Err(Error::NoLeaves)
        ));

        // Empty tree with any position should fail with InvalidPosition
        assert!(matches!(
            tree.multi_proof([0]),
            Err(Error::InvalidPosition(0))
        ));
    }

    #[test]
    fn test_multi_proof_empty_positions() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Empty positions should return error
        assert!(matches!(
            tree.multi_proof(std::iter::empty::<u32>()),
            Err(Error::NoLeaves)
        ));
    }

    #[test]
    fn test_multi_proof_duplicate_positions_error() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Duplicate positions should return error
        assert!(matches!(
            tree.multi_proof([1, 1]),
            Err(Error::DuplicatePosition(1))
        ));
        assert!(matches!(
            tree.multi_proof([0, 2, 2, 5]),
            Err(Error::DuplicatePosition(2))
        ));
    }

    #[test]
    fn test_multi_proof_unsorted_input() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Test with unsorted positions (should work - internal sorting)
        let positions = [5, 0, 3];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Verify with unsorted elements (should work - internal sorting)
        let unsorted_elements = [(digests[5], 5), (digests[0], 0), (digests[3], 3)];
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &unsorted_elements, &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_various_sizes() {
        // Test multi-proofs for trees of various sizes
        for tree_size in [1, 2, 3, 4, 5, 7, 8, 15, 16, 31, 32] {
            let digests: Vec<Digest> = (0..tree_size as u32)
                .map(|i| Sha256::hash(&i.to_be_bytes()))
                .collect();

            // Build tree
            let mut builder = Builder::<Sha256>::new(digests.len());
            for digest in &digests {
                builder.add(digest);
            }
            let tree = builder.build();
            let root = tree.root();
            let mut hasher = Sha256::default();

            // Test various position combinations
            // First and last
            if tree_size >= 2 {
                let positions = [0, (tree_size - 1) as u32];
                let multi_proof = tree.multi_proof(positions).unwrap();
                let elements: Vec<(Digest, u32)> = positions
                    .iter()
                    .map(|&p| (digests[p as usize], p))
                    .collect();
                assert!(
                    multi_proof
                        .verify_multi_inclusion(&mut hasher, &elements, &root)
                        .is_ok(),
                    "Failed for tree_size={tree_size}, positions=[0, {}]",
                    tree_size - 1
                );
            }

            // Every other element
            if tree_size >= 4 {
                let positions: Vec<u32> = (0..tree_size as u32).step_by(2).collect();
                let multi_proof = tree.multi_proof(&positions).unwrap();
                let elements: Vec<(Digest, u32)> = positions
                    .iter()
                    .map(|&p| (digests[p as usize], p))
                    .collect();
                assert!(
                    multi_proof
                        .verify_multi_inclusion(&mut hasher, &elements, &root)
                        .is_ok(),
                    "Failed for tree_size={tree_size}, every other element"
                );
            }
        }
    }

    #[test]
    fn test_multi_proof_wrong_elements() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Verify with wrong elements
        let wrong_elements = [
            (Sha256::hash(b"wrong1"), 0),
            (digests[3], 3),
            (digests[5], 5),
        ];
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &wrong_elements, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_wrong_positions() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Verify with wrong positions (same elements, different positions)
        let wrong_positions = [
            (digests[0], 1), // wrong position
            (digests[3], 3),
            (digests[5], 5),
        ];
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &wrong_positions, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_wrong_root() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // Verify with wrong root
        let wrong_root = Sha256::hash(b"wrong_root");
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &wrong_root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_tampering() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // Tamper with sibling
        assert!(!multi_proof.siblings.is_empty());
        let mut modified = multi_proof.clone();
        modified.siblings[0] = Sha256::hash(b"tampered");
        assert!(modified
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_err());

        // Add extra sibling
        let mut extra = multi_proof.clone();
        extra.siblings.push(Sha256::hash(b"extra"));
        assert!(extra
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_err());

        // Remove a sibling
        let mut missing = multi_proof;
        missing.siblings.pop();
        assert!(missing
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_deduplication() {
        // Create test data
        let digests: Vec<Digest> = (0..16u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Get individual proofs
        let individual_siblings: usize = [0u32, 1, 8, 9]
            .iter()
            .map(|&p| tree.proof(p).unwrap().siblings.len())
            .sum();

        // Get multi-proof for same positions
        let multi_proof = tree.multi_proof([0, 1, 8, 9]).unwrap();

        // Multi-proof should have fewer siblings due to deduplication
        assert!(
            multi_proof.siblings.len() < individual_siblings,
            "Multi-proof ({}) should have fewer siblings than sum of individual proofs ({})",
            multi_proof.siblings.len(),
            individual_siblings
        );
    }

    #[test]
    fn test_multi_proof_serialization() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Serialize and deserialize
        let serialized = multi_proof.encode();
        let deserialized = Proof::<Digest>::decode_cfg(serialized, &positions.len()).unwrap();

        assert_eq!(multi_proof, deserialized);

        // Verify deserialized proof works
        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();
        assert!(deserialized
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_ok());
    }

    #[test]
    fn test_multi_proof_serialization_truncated() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Generate proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Serialize and truncate
        let mut serialized = multi_proof.encode();
        serialized.truncate(serialized.len() - 1);

        // Should fail to deserialize
        assert!(Proof::<Digest>::decode_cfg(&mut serialized, &positions.len()).is_err());
    }

    #[test]
    fn test_multi_proof_serialization_extra() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Generate proof
        let positions = [0, 3, 5];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Serialize and add extra byte
        let mut serialized = multi_proof.encode_mut();
        serialized.extend_from_slice(&[0u8]);

        // Should fail to deserialize
        assert!(Proof::<Digest>::decode_cfg(&mut serialized, &positions.len()).is_err());
    }

    #[test]
    fn test_multi_proof_decode_insufficient_data() {
        let mut serialized = Vec::new();
        serialized.extend_from_slice(&8u32.encode()); // leaf_count
        serialized.extend_from_slice(&1usize.encode()); // claims 1 sibling but no data follows

        // Should fail because the buffer claims 1 sibling but doesn't have the data
        let err = Proof::<Digest>::decode_cfg(serialized.as_slice(), &1).unwrap_err();
        assert!(matches!(err, commonware_codec::Error::EndOfBuffer));
    }

    #[test]
    fn test_multi_proof_invalid_position() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();

        // Test out of bounds position
        assert!(matches!(
            tree.multi_proof([0, 8]),
            Err(Error::InvalidPosition(8))
        ));
        assert!(matches!(
            tree.multi_proof([100]),
            Err(Error::InvalidPosition(100))
        ));
    }

    #[test]
    fn test_multi_proof_verify_invalid_position() {
        // Create test data
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        // Build tree
        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 3];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Try to verify with out of bounds position
        let invalid_elements = [(digests[0], 0), (digests[3], 100)];
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &invalid_elements, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_odd_tree_sizes() {
        // Test odd-sized trees that require node duplication
        for tree_size in [3, 5, 7, 9, 11, 13, 15] {
            let digests: Vec<Digest> = (0..tree_size as u32)
                .map(|i| Sha256::hash(&i.to_be_bytes()))
                .collect();

            // Build tree
            let mut builder = Builder::<Sha256>::new(digests.len());
            for digest in &digests {
                builder.add(digest);
            }
            let tree = builder.build();
            let root = tree.root();
            let mut hasher = Sha256::default();

            // Test with positions including the last element
            let positions = [0, (tree_size - 1) as u32];
            let multi_proof = tree.multi_proof(positions).unwrap();

            let elements: Vec<(Digest, u32)> = positions
                .iter()
                .map(|&p| (digests[p as usize], p))
                .collect();
            assert!(
                multi_proof
                    .verify_multi_inclusion(&mut hasher, &elements, &root)
                    .is_ok(),
                "Failed for tree_size={tree_size}"
            );
        }
    }

    #[test]
    fn test_multi_proof_verify_empty_elements() {
        // Create a valid proof and try to verify with empty elements
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 3];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Try to verify with empty elements
        let empty_elements: &[(Digest, u32)] = &[];
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, empty_elements, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_default_verify() {
        // Default (empty) proof should only verify against empty tree
        let mut hasher = Sha256::default();
        let default_proof = Proof::<Digest>::default();

        // Empty elements against default proof
        let empty_elements: &[(Digest, u32)] = &[];

        // Build empty tree to get the empty root
        let builder = Builder::<Sha256>::new(0);
        let empty_tree = builder.build();
        let empty_root = empty_tree.root();

        assert!(default_proof
            .verify_multi_inclusion(&mut hasher, empty_elements, &empty_root)
            .is_ok());

        // Should fail with wrong root
        let wrong_root = Sha256::hash(b"not_empty");
        assert!(default_proof
            .verify_multi_inclusion(&mut hasher, empty_elements, &wrong_root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_single_leaf_tree() {
        // Edge case: tree with exactly one leaf
        let digest = Sha256::hash(b"only_leaf");

        // Build single-leaf tree
        let mut builder = Builder::<Sha256>::new(1);
        builder.add(&digest);
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate multi-proof for the only leaf
        let multi_proof = tree.multi_proof([0]).unwrap();

        // Single leaf tree: leaf_count should be 1
        assert_eq!(multi_proof.leaf_count, 1);

        // Single leaf tree: no siblings needed (leaf is the root after position hashing)
        assert!(
            multi_proof.siblings.is_empty(),
            "Single leaf tree should have no siblings"
        );

        // Verify the proof
        let elements = [(digest, 0u32)];
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &elements, &root)
                .is_ok(),
            "Single leaf multi-proof verification failed"
        );

        // Verify with wrong digest fails
        let wrong_digest = Sha256::hash(b"wrong");
        let wrong_elements = [(wrong_digest, 0u32)];
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &wrong_elements, &root)
                .is_err(),
            "Should fail with wrong digest"
        );

        // Verify with wrong position fails
        let wrong_position_elements = [(digest, 1u32)];
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &wrong_position_elements, &root)
                .is_err(),
            "Should fail with invalid position"
        );
    }

    #[test]
    fn test_multi_proof_malicious_leaf_count_zero() {
        // Attacker sets leaf_count = 0 but provides siblings
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof and tamper with leaf_count
        let positions = [0, 3];
        let mut multi_proof = tree.multi_proof(positions).unwrap();
        multi_proof.leaf_count = 0;

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // Should fail - leaf_count=0 but we have elements
        assert!(multi_proof
            .verify_multi_inclusion(&mut hasher, &elements, &root)
            .is_err());
    }

    #[test]
    fn test_multi_proof_malicious_leaf_count_larger() {
        // Attacker inflates leaf_count to claim proof is for larger tree
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof and inflate leaf_count
        let positions = [0, 3];
        let mut multi_proof = tree.multi_proof(positions).unwrap();
        let original_leaf_count = multi_proof.leaf_count;
        multi_proof.leaf_count = 1000;

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // Should fail - inflated leaf_count changes required siblings
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &elements, &root)
                .is_err(),
            "Should reject proof with inflated leaf_count ({} -> {})",
            original_leaf_count,
            multi_proof.leaf_count
        );
    }

    #[test]
    fn test_multi_proof_malicious_leaf_count_smaller() {
        // Attacker deflates leaf_count to claim proof is for smaller tree
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof and deflate leaf_count
        let positions = [0, 3];
        let mut multi_proof = tree.multi_proof(positions).unwrap();
        multi_proof.leaf_count = 4; // Smaller than actual tree

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // Should fail - deflated leaf_count changes tree structure
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &elements, &root)
                .is_err(),
            "Should reject proof with deflated leaf_count"
        );
    }

    #[test]
    fn test_multi_proof_mismatched_element_count() {
        // Provide more or fewer elements than the proof was generated for
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate proof for 2 positions
        let positions = [0, 3];
        let multi_proof = tree.multi_proof(positions).unwrap();

        // Try to verify with only 1 element (too few)
        let too_few = [(digests[0], 0u32)];
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &too_few, &root)
                .is_err(),
            "Should reject when fewer elements provided than proof was generated for"
        );

        // Try to verify with 3 elements (too many)
        let too_many = [(digests[0], 0u32), (digests[3], 3), (digests[5], 5)];
        assert!(
            multi_proof
                .verify_multi_inclusion(&mut hasher, &too_many, &root)
                .is_err(),
            "Should reject when more elements provided than proof was generated for"
        );
    }

    #[test]
    fn test_multi_proof_swapped_siblings() {
        // Swap the order of siblings in the proof
        let digests: Vec<Digest> = (0..8u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof with multiple siblings
        let positions = [0, 5];
        let mut multi_proof = tree.multi_proof(positions).unwrap();

        // Ensure we have at least 2 siblings to swap
        if multi_proof.siblings.len() >= 2 {
            // Swap first two siblings
            multi_proof.siblings.swap(0, 1);

            let elements: Vec<(Digest, u32)> = positions
                .iter()
                .map(|&p| (digests[p as usize], p))
                .collect();

            assert!(
                multi_proof
                    .verify_multi_inclusion(&mut hasher, &elements, &root)
                    .is_err(),
                "Should reject proof with swapped siblings"
            );
        }
    }

    #[test]
    fn test_multi_proof_dos_large_leaf_count() {
        // Attacker sets massive leaf_count trying to cause DoS via memory allocation
        // The verify function should NOT allocate proportional to leaf_count
        let digests: Vec<Digest> = (0..4u32).map(|i| Sha256::hash(&i.to_be_bytes())).collect();

        let mut builder = Builder::<Sha256>::new(digests.len());
        for digest in &digests {
            builder.add(digest);
        }
        let tree = builder.build();
        let root = tree.root();
        let mut hasher = Sha256::default();

        // Generate valid proof
        let positions = [0, 2];
        let mut multi_proof = tree.multi_proof(positions).unwrap();

        // Set massive leaf_count (attacker trying to exhaust memory)
        multi_proof.leaf_count = u32::MAX;

        let elements: Vec<(Digest, u32)> = positions
            .iter()
            .map(|&p| (digests[p as usize], p))
            .collect();

        // This should fail quickly without allocating massive memory
        // The function is O(elements * levels), not O(leaf_count)
        let result = multi_proof.verify_multi_inclusion(&mut hasher, &elements, &root);
        assert!(result.is_err(), "Should reject malicious large leaf_count");
    }

    #[cfg(feature = "arbitrary")]
    mod conformance {
        use super::*;
        use commonware_codec::conformance::CodecConformance;
        use commonware_conformance::Conformance;
        use commonware_cryptography::sha256::Digest as Sha256Digest;

        fn test_merkle_tree(n: usize) -> Digest {
            // Build tree
            let mut digests = Vec::with_capacity(n);
            let mut builder = Builder::<Sha256>::new(n);
            for i in 0..n {
                let digest = Sha256::hash(&i.to_be_bytes());
                builder.add(&digest);
                digests.push(digest);
            }
            let tree = builder.build();
            let root = tree.root();

            // For each leaf, generate and verify its proof
            let mut hasher = Sha256::default();
            for (i, leaf) in digests.iter().enumerate() {
                // Generate proof
                let proof = tree.proof(i as u32).unwrap();
                assert!(
                    proof
                        .verify_element_inclusion(&mut hasher, leaf, i as u32, &root)
                        .is_ok(),
                    "correct fail for size={n} leaf={i}"
                );

                // Serialize and deserialize the proof
                let serialized = proof.encode();
                let deserialized = Proof::<Digest>::decode_cfg(serialized, &1).unwrap();
                assert!(
                    deserialized
                        .verify_element_inclusion(&mut hasher, leaf, i as u32, &root)
                        .is_ok(),
                    "deserialize fail for size={n} leaf={i}"
                );

                // Modify a sibling hash and ensure the proof fails
                if !proof.siblings.is_empty() {
                    let mut update_tamper = proof.clone();
                    update_tamper.siblings[0] = Sha256::hash(b"tampered");
                    assert!(
                        update_tamper
                            .verify_element_inclusion(&mut hasher, leaf, i as u32, &root)
                            .is_err(),
                        "modify fail for size={n} leaf={i}"
                    );
                }

                // Add a sibling hash and ensure the proof fails
                let mut add_tamper = proof.clone();
                add_tamper.siblings.push(Sha256::hash(b"tampered"));
                assert!(
                    add_tamper
                        .verify_element_inclusion(&mut hasher, leaf, i as u32, &root)
                        .is_err(),
                    "add fail for size={n} leaf={i}"
                );

                // Remove a sibling hash and ensure the proof fails
                if !proof.siblings.is_empty() {
                    let mut remove_tamper = proof.clone();
                    remove_tamper.siblings.pop();
                    assert!(
                        remove_tamper
                            .verify_element_inclusion(&mut hasher, leaf, i as u32, &root)
                            .is_err(),
                        "remove fail for size={n} leaf={i}"
                    );
                }
            }

            // Test proof for larger than size
            assert!(tree.proof(n as u32).is_err());

            // Return the root so we can ensure we don't silently change.
            root
        }

        struct RootConformance;

        impl Conformance for RootConformance {
            async fn commit(seed: u64) -> Vec<u8> {
                let root = test_merkle_tree(seed as usize);
                root.to_vec()
            }
        }

        commonware_conformance::conformance_tests! {
            CodecConformance<Proof<Sha256Digest>>,
            RootConformance => 200
        }
    }
}