zisk-common 1.3.0-alpha

Common utilities and shared types for the ZisK zkVM
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
use crate::error::{CommonError, Result};
use proofman::{verify_snark_proof, SnarkProof, SnarkProtocol};
use proofman_verifier::VadcopFinalProof;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::File;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};

pub use zisk_verifier::{
    program_publics, GOLDILOCKS_ORDER, IS_VADCOP_FINAL_PROOF, PROGRAM_VK_LEN,
    VADCOP_FINAL_FLAG_LEN, ZISK_PUBLICS,
};

use crate::HashMode;

/// The canonical representative of a Goldilocks element: the unique value in
/// `[0, p)` congruent to `word`. One subtraction suffices — `p > 2^63`, so every
/// u64 is below `2p`.
#[inline]
fn canonical(word: u64) -> u64 {
    if word >= GOLDILOCKS_ORDER {
        word - GOLDILOCKS_ORDER
    } else {
        word
    }
}

/// Canonicality plus the exact shape a *stored* body must have.
///
/// Length: a short vector would panic the fixed-offset slicing in `snark_publics_hash` /
/// `snark_inputs_bytes`, turning an untrusted proof into a crash rather than an `Err`.
/// `Vadcop` storage is flag-free by construction — `stark_publics` re-adds the flag at
/// verify time, so a 69-word body would reach the STARK verifier with 70 publics. `Plonk`
/// bodies from older builds may still carry the flag, so that shape stays accepted.
fn ensure_stored_publics(body: &ProofBody) -> Result<()> {
    let flag_free = PROGRAM_VK_LEN + ZISK_PUBLICS;
    let (publics_full, flagged_ok) = match body {
        ProofBody::Vadcop { publics_full, .. } => (publics_full.as_slice(), false),
        ProofBody::Plonk { publics_full, .. } => (publics_full.as_slice(), true),
    };
    let ok = publics_full.len() == flag_free
        || (flagged_ok && publics_full.len() == VADCOP_FINAL_FLAG_LEN + flag_free);
    if !ok {
        return Err(CommonError::InvalidProof(format!(
            "stored publics have {} field elements, expected {flag_free}",
            publics_full.len()
        )));
    }
    ensure_canonical_publics(publics_full)
}

/// Without this a proof holder could rewrite a stored public — `x` and `x + p` are one
/// field element to the STARK verifier but two different reported outputs.
fn ensure_canonical_publics(publics_full: &[u64]) -> Result<()> {
    let normalized = program_publics(publics_full);
    if normalized.len() != PROGRAM_VK_LEN + ZISK_PUBLICS {
        return Err(CommonError::InvalidProof(format!(
            "committed publics have {} field elements (after flag strip), expected {}",
            normalized.len(),
            PROGRAM_VK_LEN + ZISK_PUBLICS
        )));
    }
    if let Some(i) = publics_full.iter().position(|&w| w >= GOLDILOCKS_ORDER) {
        return Err(CommonError::InvalidProof(format!(
            "public {i} is not a canonical Goldilocks element: {} >= {GOLDILOCKS_ORDER}",
            publics_full[i]
        )));
    }
    Ok(())
}

/// The committed publics with the program-VK limbs replaced by `vk`.
///
/// Splicing keeps every other slot at full u64 width; rebuilding from the u32
/// [`PublicValues`] view would truncate a recurser proof's inputs.
fn splice_program_vk(publics_full: &[u64], vk: &[u64]) -> Result<Vec<u64>> {
    if publics_full.len() < PROGRAM_VK_LEN {
        return Err(CommonError::InvalidProof(format!(
            "committed publics too short to hold a program VK: {} < {PROGRAM_VK_LEN}",
            publics_full.len()
        )));
    }
    // Normalize first: a raw vadcop_final vector carries the flag at index 0, and
    // splicing over it would shift the rest of the statement by one.
    let mut out = program_publics(publics_full).to_vec();
    out[..PROGRAM_VK_LEN].copy_from_slice(vk);
    Ok(out)
}

/// Cache key for a built setup (per program + build flavor).
///
/// `hash_mode` is intentionally NOT part of the key: a worker/prover is started
/// against a single proving key whose hash family is fixed for the process
/// lifetime, so a given `hash_id` only ever resolves to one `hash_mode` within
/// a cache. Adding the mode would be dead discriminator. (If proving keys ever
/// become hot-swappable per process, revisit this.)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SetupKey {
    /// Hash identifier for the program, used to select the appropriate proving key and verification key.
    pub hash_id: String,
    /// Indicates whether the proof includes hints, which may require a different proving key.
    pub with_hints: bool,
    /// Indicates whether the proof is intended for emulator-only verification.
    pub emulator_only: bool,
}

impl SetupKey {
    /// Creates a new `SetupKey` instance.
    pub fn new(hash_id: impl Into<String>, with_hints: bool, emulator_only: bool) -> Self {
        Self { hash_id: hash_id.into(), with_hints, emulator_only }
    }
}

/// The `ProgramVK` struct represents the verification key for a program, consisting of a vector of u64 values.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ProgramVK {
    /// Verification key values for the program.
    pub vk: Vec<u64>,
    /// Hash mode.
    pub hash_mode: HashMode,
}

impl ProgramVK {
    /// Build from the first `PROGRAM_VK_LEN` u64 elements of a publics blob,
    /// recording the [`HashMode`] the verkey was produced under.
    ///
    /// # Panics
    ///
    /// Panics if `publics` has fewer than `PROGRAM_VK_LEN` elements.
    pub fn new_from_publics_with_mode(publics: &[u64], hash_mode: HashMode) -> Self {
        // Strip the recursion-layer `is_vadcop_final_proof` flag (present on a
        // full 69-wide vadcop_final publics vector) so the VK is read from the
        // flag-free `[vk | inputs]` view rather than `[flag | vk | inputs]`.
        let publics = program_publics(publics);
        assert!(
            publics.len() >= PROGRAM_VK_LEN,
            "Not enough u64 publics to extract program VK (expected at least {})",
            PROGRAM_VK_LEN
        );

        Self { vk: publics[..PROGRAM_VK_LEN].to_vec(), hash_mode }
    }

    /// Build from publics using the default [`HashMode`].
    pub fn new_from_publics(publics: &[u64]) -> Self {
        Self::new_from_publics_with_mode(publics, HashMode::default())
    }

    /// Creates a new `ProgramVK` instance with an empty verification key (filled with zeros).
    pub fn new_empty() -> Self {
        Self { vk: vec![0u64; PROGRAM_VK_LEN], hash_mode: HashMode::default() }
    }
}

/// Which flavor of Vadcop proof a [`ProofBody::Vadcop`] holds. This is the axis
/// that used to be a `minimal: bool`, split out so the `is_vadcop_final_proof`
/// public flag (present at index 0 of a full-width publics vector) has a single,
/// unambiguous value per variant instead of being guessed from the vector length:
///
/// | Variant    | publics layout                    | flag @0 |
/// |------------|-----------------------------------|---------|
/// | `Final`    | `[flag=1 \| vk(4) \| inputs(64)]` (69) | 1 (raw ZisK leaf) |
/// | `Recurser` | `[flag=0 \| vk(4) \| inputs(64)]` (69) | 0 (aggregator output) |
/// | `Minimal`  | `[vk(4) \| inputs(64)]` (68)          | none (compressed strips it) |
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum VadcopKind {
    /// Raw ZisK vadcop_final proof — a recursion-tree leaf. Flag = 1.
    #[default]
    Final,
    /// Output of a recurser fold (aggregated proof). Same wire shape as `Final`
    /// but the flag is 0. Kept distinct so re-verification / re-folding stamps
    /// the correct flag value.
    Recurser,
    /// Minimal (compressed) proof: the `final_compressed` circuit strips the flag,
    /// so its publics are the flag-free `[vk | inputs]`.
    Minimal,
}

impl VadcopKind {
    /// The `is_vadcop_final_proof` value at public index 0, or `None` when the
    /// flavor carries no flag (minimal/compressed).
    pub fn flag(self) -> Option<u64> {
        match self {
            VadcopKind::Final => Some(IS_VADCOP_FINAL_PROOF),
            // An aggregator output forces the flag to 0 (see the recurser circuit).
            VadcopKind::Recurser => Some(0),
            VadcopKind::Minimal => None,
        }
    }

    /// Whether this is the minimal (compressed) proof — the STARK verifier and
    /// setup lookups that previously took a `minimal: bool` use this.
    pub fn is_minimal(self) -> bool {
        matches!(self, VadcopKind::Minimal)
    }

    /// Classify a RAW publics vector as it arrives from the prover/wire (before
    /// normalization): `Minimal` when flag-free (`PROGRAM_N_PUBLICS`, 68), else
    /// `Final`/`Recurser` by the `is_vadcop_final_proof` flag at index 0 (69).
    /// Falls back to `Final` for unexpected lengths (callers assert elsewhere).
    /// Used at ingest to capture the flag before it is stripped from
    /// `publics_full`.
    /// Best-effort classification by shape. Every non-zero flag reads as `Final`, so
    /// untrusted input must pin the flag itself rather than rely on this.
    pub fn from_publics_full(publics_full: &[u64]) -> Self {
        if publics_full.len() == VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS {
            if publics_full[0] == 0 {
                VadcopKind::Recurser
            } else {
                VadcopKind::Final
            }
        } else if publics_full.len() == PROGRAM_VK_LEN + ZISK_PUBLICS {
            VadcopKind::Minimal
        } else {
            VadcopKind::Final
        }
    }

    /// Build the STARK public vector for this proof from the canonical flag-free
    /// `publics_full` (`[program_vk | inputs]`): re-adds the
    /// `is_vadcop_final_proof` flag at index 0 for `Final`/`Recurser`, and
    /// returns the flag-free publics unchanged for `Minimal`. This is the exact
    /// vector the STARK verifier / next-layer witness commits to (full u64
    /// width), and the inverse of the ingest strip.
    pub fn stark_publics(self, publics_full: &[u64]) -> Vec<u64> {
        match self.flag() {
            Some(flag) => {
                let mut v = Vec::with_capacity(VADCOP_FINAL_FLAG_LEN + publics_full.len());
                v.push(flag);
                v.extend_from_slice(publics_full);
                v
            }
            None => publics_full.to_vec(),
        }
    }
}

/// Enumeration of supported proof types, used to distinguish between different proof generation and verification logic.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProofKind {
    /// A STARKs proof.
    #[default]
    VadcopFinal,
    /// A minimal STARKs proof variant optimized for size.
    VadcopFinalMinimal,
    /// A Plonk SNARK proof.
    Plonk,
}

impl From<i32> for ProofKind {
    fn from(v: i32) -> Self {
        match v {
            1 => ProofKind::VadcopFinalMinimal,
            2 => ProofKind::Plonk,
            _ => ProofKind::VadcopFinal,
        }
    }
}

impl From<ProofKind> for i32 {
    fn from(k: ProofKind) -> Self {
        match k {
            ProofKind::VadcopFinal => 0,
            ProofKind::VadcopFinalMinimal => 1,
            ProofKind::Plonk => 2,
        }
    }
}

/// The `PlonkVkey` struct represents the verification key for a Plonk proof.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlonkVkey {
    /// Proof system identifier.
    pub protocol: String,
    /// Elliptic curve identifier.
    pub curve: String,
    /// Number of public inputs expected by the proof, which must match the number of public values provided during verification.
    #[serde(rename = "nPublic")]
    pub n_public: u32,
    /// Logâ‚‚ of the evaluation domain size: the circuit is padded to `n = 2^power` constraints.
    pub power: u32,
    /// First coset shift for the permutation argument. The three wire columns are mapped onto the
    /// cosets `H`, `k1·H`, `k2·H`, so `k1` (with `k2`) must yield cosets disjoint from `H` and from each other.
    pub k1: String,
    /// Second coset shift for the permutation argument (see `k1`).
    pub k2: String,
    /// KZG commitment to the multiplication selector polynomial `q_M` (G1 point).
    #[serde(rename = "Qm")]
    pub qm: [String; 3],
    /// KZG commitment to the left-wire selector polynomial `q_L` (G1 point).
    #[serde(rename = "Ql")]
    pub ql: [String; 3],
    /// KZG commitment to the right-wire selector polynomial `q_R` (G1 point).
    #[serde(rename = "Qr")]
    pub qr: [String; 3],
    /// KZG commitment to the output-wire selector polynomial `q_O` (G1 point).
    #[serde(rename = "Qo")]
    pub qo: [String; 3],
    /// KZG commitment to the constant selector polynomial `q_C` (G1 point).
    #[serde(rename = "Qc")]
    pub qc: [String; 3],
    /// KZG commitment to the first permutation polynomial `S_σ1`, encoding the copy constraints
    /// over the first wire column (G1 point).
    #[serde(rename = "S1")]
    pub s1: [String; 3],
    /// KZG commitment to the second permutation polynomial `S_σ2` (G1 point).
    #[serde(rename = "S2")]
    pub s2: [String; 3],
    /// KZG commitment to the third permutation polynomial `S_σ3` (G1 point).
    #[serde(rename = "S3")]
    pub s3: [String; 3],
    /// The SRS element `[x]â‚‚` from the trusted setup, used as the G2 input to the final KZG pairing check.
    /// G2 point in projective coordinates over `Fp2`: 3 coordinates, each an `[c0, c1]` pair.
    #[serde(rename = "X_2")]
    pub x_2: [[String; 2]; 3],
    /// Generator of the evaluation domain `H`: a primitive `n`-th root of unity, with `n = 2^power`.
    pub w: String,
}

impl PlonkVkey {
    /// Load PlonkVkey from a JSON file
    ///
    /// # Errors
    ///
    /// - [`CommonError::Io`] if the file cannot be opened or read.
    /// - [`CommonError::Deserialization`] if the JSON cannot be parsed into a [`PlonkVkey`].
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let file = File::open(path.as_ref()).map_err(|e| {
            CommonError::Io(format!(
                "failed to open file for loading PlonkVkey: {}: {e}",
                path.as_ref().display()
            ))
        })?;
        let vkey: PlonkVkey = serde_json::from_reader(file).map_err(|e| {
            CommonError::Deserialization(format!(
                "failed to parse PlonkVkey JSON from {}: {e}",
                path.as_ref().display()
            ))
        })?;
        Ok(vkey)
    }

    /// Save PlonkVkey to a JSON file
    ///
    /// # Errors
    ///
    /// - [`CommonError::Io`] if the parent directory or the file cannot be created.
    /// - [`CommonError::Serialization`] if the vkey cannot be serialized to JSON.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                CommonError::Io(format!(
                    "failed to create parent directory {}: {e}",
                    parent.display()
                ))
            })?;
        }

        let file = File::create(path).map_err(|e| {
            CommonError::Io(format!(
                "failed to create file for saving PlonkVkey: {}: {e}",
                path.display()
            ))
        })?;

        serde_json::to_writer_pretty(file, self).map_err(|e| {
            CommonError::Serialization(format!("PlonkVkey JSON to {}: {e}", path.display()))
        })?;

        Ok(())
    }
}

/// Verification key for a Plonk proof: the underlying Vadcop vkey plus the structured Plonk vkey.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlonkVkBlob {
    /// Vadcop verification key values.
    pub vadcop_vk: Vec<u64>,
    /// Structured Plonk verification key. This is boxed to avoid bloating the size of the `ProofBody` enum, since Plonk proofs are less common and the vkey is large.
    pub plonk_vkey: PlonkVkey,
}

/// Public values for proof generation and verification.
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PublicValues {
    data: Vec<u8>,
    #[serde(skip)]
    ptr: AtomicUsize,
}

impl Clone for PublicValues {
    fn clone(&self) -> Self {
        Self { data: self.data.clone(), ptr: AtomicUsize::new(self.ptr.load(Ordering::Relaxed)) }
    }
}

impl PublicValues {
    /// Build from the full proof publics byte blob.
    ///
    /// # Panics
    ///
    /// Panics if `publics_bytes` is not exactly `ZISK_PUBLICS * 8 + 32` bytes long.
    pub fn new(publics_bytes: &[u8]) -> Self {
        assert!(
            publics_bytes.len() == ZISK_PUBLICS * 8 + 32,
            "Not enough bytes to fill PublicValues"
        );

        let mut data = [0u8; ZISK_PUBLICS * 4];
        for (i, chunk) in publics_bytes[32..].chunks_exact(8).enumerate() {
            let v32 = u32::from_le_bytes(chunk[0..4].try_into().unwrap());
            data[i * 4..(i + 1) * 4].copy_from_slice(&v32.to_le_bytes());
        }

        Self { data: data.to_vec(), ptr: AtomicUsize::new(0) }
    }

    /// Build from the full proof publics u64 blob: `[program_vk(4)][publics(ZISK_PUBLICS)]`.
    /// Each public u64 is truncated to its low 32 bits (matching `public_u64()`).
    ///
    /// Truncation is only sound because non-canonical encodings are rejected at ingest
    /// (`ensure_canonical_publics`, and the verifier's own check): `x` and `x + p` are
    /// one field element but differ in their low 32 bits, so without that rejection the
    /// reported outputs would not be pinned by the verified statement. Callers must not
    /// treat truncation alone as a security boundary.
    ///
    /// # Panics
    ///
    /// Panics if `publics` does not contain exactly `ZISK_PUBLICS + PROGRAM_VK_LEN` elements.
    pub fn new_from_u64(publics: &[u64]) -> Self {
        // Accept either the flag-free app view (`[vk | inputs]`, 68) or a full
        // vadcop_final vector (`[flag | vk | inputs]`, 69); strip the flag first.
        let publics = program_publics(publics);
        assert!(
            publics.len() == ZISK_PUBLICS + PROGRAM_VK_LEN,
            "Expected {} u64 publics, got {}",
            ZISK_PUBLICS + PROGRAM_VK_LEN,
            publics.len()
        );

        let mut data = [0u8; ZISK_PUBLICS * 4];
        for (i, &val) in publics[PROGRAM_VK_LEN..].iter().enumerate() {
            data[i * 4..(i + 1) * 4].copy_from_slice(&(canonical(val) as u32).to_le_bytes());
        }

        Self { data: data.to_vec(), ptr: AtomicUsize::new(0) }
    }

    /// Creates a new `PublicValues` instance with empty data and a reset pointer.
    pub fn new_empty() -> Self {
        Self { data: [0u8; ZISK_PUBLICS * 4].to_vec(), ptr: AtomicUsize::new(0) }
    }

    /// Create PublicValues from a serializable value.
    /// The value is serialized with bincode and stored in the public outputs as 64-bit chunks.
    ///
    /// # Errors
    ///
    /// - [`CommonError::Serialization`] if the value cannot be serialized with bincode.
    /// - [`CommonError::Invalid`] if the serialized data exceeds `ZISK_PUBLICS * 4` bytes.
    pub fn write<T: serde::Serialize>(value: &T) -> Result<Self> {
        let serialized = bincode::serde::encode_to_vec(value, bincode::config::standard())
            .map_err(|e| CommonError::Serialization(e.to_string()))?;

        if serialized.len() > ZISK_PUBLICS * 4 {
            return Err(CommonError::Invalid(format!(
                "Serialized data too large: {} bytes (max {} bytes)",
                serialized.len(),
                ZISK_PUBLICS * 4
            )));
        }

        let mut data = [0u8; ZISK_PUBLICS * 4];
        // Chunk into 8-byte (u64) values
        for (i, chunk) in serialized.chunks(4).enumerate() {
            // copy chunk into 32-bit slot, padding with zeros if chunk < 4 bytes
            let mut buf = [0u8; 4];
            buf[..chunk.len()].copy_from_slice(chunk);
            data[i * 4..(i + 1) * 4].copy_from_slice(&buf);
        }

        Ok(Self { data: data.to_vec(), ptr: AtomicUsize::new(0) })
    }

    /// Create PublicValues from an ABI-encodable value.
    /// The value is ABI-encoded and stored in the public outputs as 32-bit chunks.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::Invalid`] if the ABI-encoded data exceeds `ZISK_PUBLICS * 4` bytes.
    pub fn write_abi<T: alloy_sol_types::SolValue>(value: &T) -> Result<Self> {
        let encoded = value.abi_encode();

        if encoded.len() > ZISK_PUBLICS * 4 {
            return Err(CommonError::Invalid(format!(
                "ABI encoded data too large: {} bytes (max {} bytes)",
                encoded.len(),
                ZISK_PUBLICS * 4
            )));
        }

        let mut data = [0u8; ZISK_PUBLICS * 4];
        for (i, chunk) in encoded.chunks(4).enumerate() {
            // copy chunk into 32-bit slot, padding with zeros if chunk < 4 bytes
            let mut buf = [0u8; 4];
            buf[..chunk.len()].copy_from_slice(chunk);
            data[i * 4..(i + 1) * 4].copy_from_slice(&buf);
        }

        Ok(Self { data: data.to_vec(), ptr: AtomicUsize::new(0) })
    }

    /// Reset the reading pointer to the beginning.
    pub fn head(&self) {
        self.ptr.store(0, Ordering::Relaxed);
    }

    /// Read raw bytes from public outputs.
    pub fn read_slice(&self, slice: &mut [u8]) {
        let ptr = self.ptr.load(Ordering::Relaxed);
        slice.copy_from_slice(&self.data[ptr..ptr + slice.len()]);
        self.ptr.store(ptr + slice.len(), Ordering::Relaxed);
    }

    /// Deserialize a value from public outputs.
    /// The value must have been previously written with bincode serialization using `commit()`.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::Deserialization`] if the stored bytes cannot be decoded into `T`.
    pub fn read<T: serde::Serialize + serde::de::DeserializeOwned>(&self) -> Result<T> {
        let ptr = self.ptr.load(Ordering::Relaxed);
        let (result, nb_bytes): (T, usize) =
            bincode::serde::decode_from_slice(&self.data[ptr..], bincode::config::standard())
                .map_err(|e| CommonError::Deserialization(e.to_string()))?;
        self.ptr.store(ptr + nb_bytes, Ordering::Relaxed);
        Ok(result)
    }

    /// Decode an ABI-encoded value from public outputs.
    /// The value must have been previously written with ABI encoding using `write_abi()`.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::AbiDecoding`] if the stored bytes cannot be ABI-decoded into `T`.
    pub fn read_abi<T>(&self) -> Result<T>
    where
        T: alloy_sol_types::SolValue + From<<T::SolType as alloy_sol_types::SolType>::RustType>,
    {
        let ptr = self.ptr.load(Ordering::Relaxed);
        let decoded = T::abi_decode(&self.data[ptr..])
            .map_err(|e| CommonError::AbiDecoding(e.to_string()))?;
        let encoded_size = decoded.abi_encode().len();
        self.ptr.store(ptr + encoded_size, Ordering::Relaxed);
        Ok(decoded)
    }

    /// Public values as `ZISK_PUBLICS` u64 elements (each is a u32 widened to u64).
    pub fn public_u64(&self) -> Vec<u64> {
        (0..ZISK_PUBLICS)
            .map(|i| {
                let start = i * 4;
                u32::from_le_bytes([
                    self.data[start],
                    self.data[start + 1],
                    self.data[start + 2],
                    self.data[start + 3],
                ]) as u64
            })
            .collect()
    }

    /// Hash the public values using Solidity-compatible encoding.
    pub fn hash_solidity(&self, program_vk: &ProgramVK, vadcop_verkey: &[u64]) -> Vec<u8> {
        let bytes = self.bytes_solidity(program_vk, vadcop_verkey);

        // SHA-256
        let hash = Sha256::digest(&bytes);

        hash.to_vec()
    }
}

impl PublicValues {
    /// Convert the public values into a byte vector formatted for Solidity hashing.
    pub fn bytes_solidity(&self, program_vk: &ProgramVK, vadcop_verkey: &[u64]) -> Vec<u8> {
        let mut prefix = [0u8; PROGRAM_VK_LEN * 8];
        for (i, val) in program_vk.vk.iter().enumerate() {
            prefix[i * 8..(i + 1) * 8].copy_from_slice(&val.to_be_bytes());
        }

        let mut bytes = prefix.to_vec();
        bytes.extend_from_slice(&self.data);
        let mut suffix = [0u8; PROGRAM_VK_LEN * 8];
        for (i, val) in vadcop_verkey.iter().enumerate() {
            suffix[i * 8..(i + 1) * 8].copy_from_slice(&val.to_be_bytes());
        }
        bytes.extend(&suffix);
        bytes
    }
}

/// The `ZISK_PUBLICS` user publics encoded as the snark circuit's `inputs`
/// section: each field element as 8 little-endian bytes (`ZISK_PUBLICS * 8`
/// bytes total). This is the on-chain `publicValues` byte string the Solidity
/// verifier hashes — NOT the u32 `PublicValues.data`.
///
/// The circuit's per-element bit layout `in[(j\8)*8 + (7 - j%8)]` over the
/// `Num2Bits(64)` (LSB-first) bits is exactly the value's little-endian bytes
/// once SHA-256 reads them MSB-first per byte.
pub fn snark_inputs_bytes(publics_full: &[u64]) -> Vec<u8> {
    // Strip the recursion-layer flag so `inputs` is read from the flag-free view.
    let publics_full = program_publics(publics_full);
    assert!(
        publics_full.len() >= PROGRAM_VK_LEN + ZISK_PUBLICS,
        "publics_full too short for snark inputs"
    );
    publics_full[PROGRAM_VK_LEN..PROGRAM_VK_LEN + ZISK_PUBLICS]
        .iter()
        .flat_map(|v| v.to_le_bytes())
        .collect()
}

/// Compute the snark's committed public-input hash exactly as the recurser's
/// `final.circom getSha256Inputs(publicsProof, rootC)` does, returning the
/// 32-byte big-endian field element snarkjs verifies against.
///
/// The circuit SHA-256s `rom_root ‖ inputs ‖ rootCVadcopFinal`, then reduces the
/// digest mod the BN254 scalar field (`Bits2Num` yields a field element). The
/// per-element byte forms reduce to: verkeys big-endian, user publics
/// little-endian (see [`snark_inputs_bytes`]). The three sections are:
///   - `rom_root`         = the program VK = `publics_full[0..PROGRAM_VK_LEN]`
///   - `inputs`           = the user publics = `publics_full[PROGRAM_VK_LEN..]`
///   - `rootCVadcopFinal` = the verkey STAMPED into the RecursiveF proof — the
///     vadcop_final verkey for a plain proof, the recurser's own verkey for an
///     aggregated proof. NOT generally equal to the program VK, so it is passed
///     in (`rootc`) rather than derived from `publics_full`.
pub fn snark_publics_hash(publics_full: &[u64], rootc: &[u64]) -> Vec<u8> {
    assert!(rootc.len() >= PROGRAM_VK_LEN, "rootc too short for snark hash");
    // Defensive: normalize to the flag-free `[vk | inputs]` view. Stored
    // `publics_full` is already flag-free, but a raw vadcop_final vector (69,
    // flag @0) would otherwise shift rom_root/inputs by one.
    let publics_full = program_publics(publics_full);
    let program_vk = &publics_full[..PROGRAM_VK_LEN];

    let mut preimage = Vec::with_capacity((2 * PROGRAM_VK_LEN + ZISK_PUBLICS) * 8);
    preimage.extend(program_vk.iter().flat_map(|v| v.to_be_bytes())); // rom_root (BE)
    preimage.extend(snark_inputs_bytes(publics_full)); // inputs (LE)
    preimage.extend(rootc[..PROGRAM_VK_LEN].iter().flat_map(|v| v.to_be_bytes())); // rootC (BE)
    let digest = Sha256::digest(&preimage);

    // `Bits2Num` makes the hash a field element: reduce mod the BN254 scalar
    // field, as 32 big-endian bytes.
    let bn254 = num_bigint::BigUint::parse_bytes(
        b"21888242871839275222246405745257275088548364400416034343698204186575808495617",
        10,
    )
    .expect("valid BN254 modulus");
    let reduced = num_bigint::BigUint::from_bytes_be(&digest) % bn254;
    let mut out = reduced.to_bytes_be();
    out.splice(0..0, std::iter::repeat(0u8).take(32 - out.len())); // left-pad to 32
    out
}

/// Kind-tagged proof payload. The Plonk vkey blob is boxed so the enum doesn't
/// carry ~880 bytes of inline vkey on the (common, most-cloned) Vadcop variant.
///
/// Publics are stored as full-width u64 field elements: a recurser proof's
/// publics exceed 32 bits, and the recursion round-trip / snark hash must use
/// the exact committed elements. The u32 `PublicValues` view (guest API,
/// Solidity encoding) is derived on demand via [`Proof::publics`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProofBody {
    /// A recursive (Vadcop) proof.
    Vadcop {
        /// Proof, as a flat vector of field elements.
        proof: Vec<u64>,
        /// ZisK verification key.
        zisk_vk: Vec<u64>,
        /// Which vadcop flavor this is (Final / Recurser / Minimal). Owns the
        /// `is_vadcop_final_proof` flag value (1 / 0 / none); the flag is NOT
        /// stored in `publics_full` — STARK paths re-add it via
        /// [`VadcopKind::stark_publics`].
        kind: VadcopKind,
        /// Hash family the proof was generated with.
        hash: String,
        /// Canonical flag-free program publics `[program_vk(4) | inputs(64)]`
        /// (always 68), at full u64 width. The recursion-layer
        /// `is_vadcop_final_proof` flag lives in `kind`, not here.
        publics_full: Vec<u64>,
    },
    /// A Plonk proof for on-chain verification.
    Plonk {
        /// Serialized proof bytes.
        proof_bytes: Vec<u8>,
        /// Plonk verification key blob.
        plonk_vk: Box<PlonkVkBlob>,
        /// u32 view of the publics, for the Solidity calldata layout.
        publics: PublicValues,
        /// Full-width publics; the snark's `publicsHash` is computed over these
        /// (the u32 `publics` view loses a recurser proof's high bits).
        publics_full: Vec<u64>,
        /// The stamped `rootCVadcopFinal` committed into `publicsHash`:
        /// vadcop_final verkey for a plain proof, recurser verkey for an
        /// aggregated one. Not derivable from `publics_full` (see `Proof::verify`).
        rootc: Vec<u64>,
    },
}

impl Default for ProofBody {
    fn default() -> Self {
        ProofBody::Vadcop {
            proof: Vec::new(),
            zisk_vk: vec![0u64; PROGRAM_VK_LEN],
            kind: VadcopKind::Final,
            hash: String::new(),
            publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
        }
    }
}

/// A struct representing a proof.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Proof {
    /// The data of the proof.
    pub body: ProofBody,
    /// The program verification key.
    pub program_vk: ProgramVK,
}

/// Builder for customizing verification parameters before calling verify.
///
/// This builder allows you to override the publics or program VK
/// that will be used during verification. If not overridden, the values from
/// the proof itself will be used.
///
/// # Examples
///
/// ```ignore
/// // Use default values from proof
/// proof.verify()?;
///
/// // Override publics only
/// proof.with_publics(&custom_publics).verify()?;
///
/// // Override program VK only
/// proof.with_program_vk(&custom_program_vk).verify()?;
///
/// // Override both
/// proof.with_publics(&custom_publics).with_program_vk(&custom_program_vk).verify()?;
/// ```
pub struct ZiskVerifyBuilder<'a> {
    proof_with_values: &'a Proof,
    override_publics: Option<&'a PublicValues>,
    override_program_vk: Option<&'a ProgramVK>,
    trusted_plonk_vk: Option<&'a PlonkVkey>,
    trusted_setup_vk: Option<&'a [u64]>,
}

impl<'a> ZiskVerifyBuilder<'a> {
    fn new(proof_with_values: &'a Proof) -> Self {
        Self {
            proof_with_values,
            override_publics: None,
            override_program_vk: None,
            trusted_plonk_vk: None,
            trusted_setup_vk: None,
        }
    }

    /// Override the publics used for verification.
    pub fn with_publics(mut self, publics: &'a PublicValues) -> Self {
        self.override_publics = Some(publics);
        self
    }

    /// Override the program verification key used for verification.
    pub fn with_program_vk(mut self, program_vk: &'a ProgramVK) -> Self {
        self.override_program_vk = Some(program_vk);
        self
    }

    /// Optional trusted PLONK circuit key; if unset, the proof's embedded key is used.
    pub fn with_plonk_vk(mut self, plonk_vkey: &'a PlonkVkey) -> Self {
        self.trusted_plonk_vk = Some(plonk_vkey);
        self
    }

    /// Optional trusted recursion setup key (4 u64 limbs: `vadcop_final` verkey for
    /// a plain proof, recurser verkey for an aggregated one); if unset, the proof's
    /// embedded value is used.
    pub fn with_setup_vk(mut self, setup_vk: &'a [u64]) -> Self {
        self.trusted_setup_vk = Some(setup_vk);
        self
    }

    /// Verify the proof using the configured parameters.
    ///
    /// This method uses the overridden values if provided, otherwise falls back
    /// to the values stored in the proof.
    ///
    /// # Errors
    ///
    /// - [`CommonError::NotVerified`] if the proof is well-formed but does not verify.
    /// - [`CommonError::InvalidProof`] if the proof is malformed or its hash family
    ///   does not match the verification key.
    /// - [`CommonError::Invalid`] if SNARK proof verification fails (Plonk).
    /// - [`CommonError::Serialization`] / [`CommonError::Io`] if writing the temporary
    ///   PlonkVkey file fails (Plonk).
    pub fn verify(self) -> Result<()> {
        // A successful verify() is the signal callers trust before reading
        // `publics()`, and `Proof::new` builds bodies the ingest checks never see.
        ensure_stored_publics(&self.proof_with_values.body)?;

        let derived_publics = self.proof_with_values.publics();
        let publics = self.override_publics.unwrap_or(&derived_publics);
        let program_vk = self.override_program_vk.unwrap_or(&self.proof_with_values.program_vk);

        // Spliced into the committed publics below, so a short one would shear the rest of
        // the statement out of place (or panic `public_u64`'s fixed-offset reads).
        if let Some(pv) = self.override_program_vk {
            if pv.vk.len() != PROGRAM_VK_LEN {
                return Err(CommonError::InvalidProof(format!(
                    "program vk override must have exactly {PROGRAM_VK_LEN} u64 limbs, got {}",
                    pv.vk.len()
                )));
            }
            // The field verifier reads x and x+p as one element, so a non-canonical limb
            // would match a key it does not equal. Pinning a key means pinning its bytes.
            if !zisk_verifier::publics_are_canonical(&pv.vk) {
                return Err(CommonError::InvalidProof(
                    "program vk override has a non-canonical Goldilocks limb".to_string(),
                ));
            }
        }
        if let Some(vk) = self.trusted_setup_vk {
            if !zisk_verifier::publics_are_canonical(vk) {
                return Err(CommonError::InvalidProof(
                    "setup vk override has a non-canonical Goldilocks limb".to_string(),
                ));
            }
        }
        if let Some(pv) = self.override_publics {
            if pv.data.len() != ZISK_PUBLICS * 4 {
                return Err(CommonError::InvalidProof(format!(
                    "publics override must be {} bytes ({ZISK_PUBLICS} u32 values), got {}",
                    ZISK_PUBLICS * 4,
                    pv.data.len()
                )));
            }
        }

        match &self.proof_with_values.body {
            ProofBody::Plonk { proof_bytes, plonk_vk, publics_full, rootc, .. } => {
                // Caller-provided keys if given, else the proof's own.
                let plonk_vkey = self.trusted_plonk_vk.unwrap_or(&plonk_vk.plonk_vkey);
                let rootc = self.trusted_setup_vk.unwrap_or(rootc.as_slice());
                if rootc.len() != PROGRAM_VK_LEN {
                    return Err(CommonError::InvalidProof(format!(
                        "setup vk (`rootc`) must have exactly {PROGRAM_VK_LEN} u64 limbs, got {}",
                        rootc.len()
                    )));
                }

                // Statement to verify: the committed publics with any override applied.
                // Only an explicit publics override takes the u32-lossy `[vk | inputs]`
                // rebuild. snarkjs uses only these bytes; `public_bytes` is unused.
                let public_snark_bytes = match (self.override_publics, self.override_program_vk) {
                    (None, None) => snark_publics_hash(publics_full, rootc),
                    (None, Some(pv)) => {
                        snark_publics_hash(&splice_program_vk(publics_full, &pv.vk)?, rootc)
                    }
                    (Some(_), _) => {
                        // Committed vk unless overridden — never the stored copy.
                        let committed = program_publics(publics_full);
                        let vk_limbs: &[u64] = match self.override_program_vk {
                            Some(pv) => &pv.vk,
                            None => &committed[..PROGRAM_VK_LEN],
                        };
                        let mut pf = vk_limbs.to_vec();
                        pf.extend(publics.public_u64());
                        snark_publics_hash(&pf, rootc)
                    }
                };

                let snark_proof = SnarkProof {
                    proof_bytes: proof_bytes.clone(),
                    public_bytes: Vec::new(),
                    public_snark_bytes,
                    protocol_id: SnarkProtocol::Plonk.protocol_id(),
                };

                let temp_dir = std::env::temp_dir();
                // Concurrent verify() calls in one process otherwise race on the tempfile.
                let unique_id = format!(
                    "{}_{}",
                    std::process::id(),
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_nanos())
                        .unwrap_or(0)
                );
                let temp_file = temp_dir.join(format!("plonk_vkey_{}.json", unique_id));

                let plonk_vkey_json = serde_json::to_vec(plonk_vkey)
                    .map_err(|e| CommonError::Serialization(format!("PlonkVkey to JSON: {e}")))?;
                std::fs::write(&temp_file, &plonk_vkey_json).map_err(|e| {
                    CommonError::Io(format!(
                        "Failed to write PlonkVkey to temporary file: {}: {e}",
                        temp_file.display()
                    ))
                })?;

                let result = verify_snark_proof(&snark_proof, &temp_file);

                if temp_file.exists() {
                    std::fs::remove_file(&temp_file).map_err(|e| {
                        CommonError::Io(format!(
                            "Failed to delete temporary file: {}: {e}",
                            temp_file.display()
                        ))
                    })?;
                }

                result.map_err(|e| {
                    CommonError::Invalid(format!("snark proof verification failed: {e}"))
                })?;
                Ok(())
            }
            ProofBody::Vadcop { proof, zisk_vk, kind, hash, publics_full } => {
                let kind = *kind;

                // A pinned PLONK key can't gate a non-PLONK proof; the Vadcop path would
                // ignore it, so reject rather than silently verify as if it were pinned.
                if self.trusted_plonk_vk.is_some() {
                    return Err(CommonError::InvalidProof(
                        "a PLONK verification key was pinned (with_plonk_vk) for a non-PLONK proof"
                            .to_string(),
                    ));
                }

                if program_vk.hash_mode.as_str() != hash {
                    return Err(CommonError::InvalidProof(format!(
                        "verkey hash mode {} does not match proof hash family {hash:?}",
                        program_vk.hash_mode.as_str()
                    )));
                }

                // `root_c` for the STARK verifier: caller's key if given, else the proof's.
                let setup_vk = self.trusted_setup_vk.unwrap_or(zisk_vk.as_slice());
                if setup_vk.len() != PROGRAM_VK_LEN {
                    return Err(CommonError::InvalidProof(format!(
                        "setup vk must have exactly {PROGRAM_VK_LEN} u64 limbs, got {}",
                        setup_vk.len()
                    )));
                }

                // A fold skips the leaf allow-list for an aggregated child and verifies it
                // under the root that child declares, so a genuine recurser output can
                // carry a subtree from another recurser. Requiring the declared domain to
                // equal the key the STARK is checked under makes the allow-list transitive
                // over the fold tree; honest folds already satisfy it. `Recurser` only — a
                // leaf declares its ROM root against the shared vadcop_final key.
                if kind == VadcopKind::Recurser {
                    // The domain the *verified statement* declares, not the committed one:
                    // an override is spliced into the publics below, so checking the stored
                    // limbs would guard a statement that is never verified.
                    let declared: &[u64] = match self.override_program_vk {
                        Some(pv) => &pv.vk,
                        None => &program_publics(publics_full)[..PROGRAM_VK_LEN],
                    };
                    if declared != setup_vk {
                        return Err(CommonError::InvalidProof(format!(
                            "recurser proof declares recursion domain {declared:?} but verifies \
                             under {setup_vk:?}; its subtree was not produced by this recurser"
                        )));
                    }
                }

                // `None` means no such (family, stage) exists — an unknown family, or a
                // compressed blake3 proof, whose proving keys never build that stage.
                // That is a malformed shape, not an unverifiable statement, so it must
                // not fall through to the verifier and come back as `NotVerified`.
                let Some(expected_len) =
                    zisk_verifier::expected_proof_bytes(hash, kind.is_minimal())
                else {
                    return Err(CommonError::InvalidProof(format!(
                        "no {:?} stage exists for hash family {hash:?}",
                        self.proof_with_values.kind()
                    )));
                };
                if proof.len() * 8 != expected_len {
                    return Err(CommonError::InvalidProof(format!(
                        "Malformed proof: expected {} bytes for {:?}, got {}",
                        expected_len,
                        self.proof_with_values.kind(),
                        proof.len() * 8
                    )));
                }

                // The STARK verifier's Fiat-Shamir transcript is over the full
                // `[flag? | program_vk | inputs]` at FULL u64 width. Splicing keeps that
                // width; only an explicit publics override falls back to the u32-lossy
                // `PublicValues` view, which is meant for proofs whose publics fit in 32
                // bits. A program-VK-only override must NOT truncate a recurser proof's
                // publics, so it splices instead.
                let pubs_u64 = match (self.override_publics, self.override_program_vk) {
                    (None, None) => kind.stark_publics(publics_full),
                    (None, Some(pv)) => {
                        kind.stark_publics(&splice_program_vk(publics_full, &pv.vk)?)
                    }
                    (Some(_), _) => {
                        // Committed vk unless overridden — never the stored copy.
                        let committed = program_publics(publics_full);
                        let vk_limbs: &[u64] = match self.override_program_vk {
                            Some(pv) => &pv.vk,
                            None => &committed[..PROGRAM_VK_LEN],
                        };
                        let mut v = Vec::with_capacity(
                            kind.flag().map_or(0, |_| VADCOP_FINAL_FLAG_LEN)
                                + PROGRAM_VK_LEN
                                + ZISK_PUBLICS,
                        );
                        if let Some(flag) = kind.flag() {
                            v.push(flag);
                        }
                        v.extend_from_slice(vk_limbs);
                        v.extend(publics.public_u64());
                        v
                    }
                };
                let vadcop_final_proof =
                    VadcopFinalProof::new(proof.clone(), pubs_u64, kind.is_minimal(), hash.clone());

                let is_valid = zisk_verifier::verify_vadcop_final(&vadcop_final_proof, setup_vk);

                if !is_valid {
                    Err(CommonError::NotVerified)
                } else {
                    Ok(())
                }
            }
        }
    }
}

impl Proof {
    /// Creates a new `Proof` from a body and program verification key.
    pub fn new(body: ProofBody, program_vk: ProgramVK) -> Self {
        Self { body, program_vk }
    }

    /// The u32 `PublicValues` view, derived from the body's native publics.
    ///
    /// Truncates each full-width public to its low 32 bits (the guest/Solidity ABI).
    ///
    /// Derived from `publics_full` for both flavors. The stored `Plonk.publics` copy is
    /// deserialized independently of the statement `verify()` actually hashes, so
    /// returning it would let a modified proof verify while reporting other outputs.
    ///
    /// **Only meaningful on a proof that passed [`Proof::load`] or [`Proof::verify`].**
    /// A misshapen body has no committed statement to report, and what comes back is
    /// zero-filled — indistinguishable from a proof whose outputs really are zero. It is
    /// not evidence of anything. Reach for [`Proof::try_publics`] whenever the proof's
    /// provenance is unknown; it rejects such a body instead of answering.
    ///
    /// The buffer stays full width rather than empty so that `public_u64`, `read` and
    /// `read_slice` keep their fixed-offset reads in bounds.
    pub fn publics(&self) -> PublicValues {
        let committed = program_publics(self.committed_publics());
        if committed.len() == PROGRAM_VK_LEN + ZISK_PUBLICS {
            return PublicValues::new_from_u64(committed);
        }
        let mut data = [0u8; ZISK_PUBLICS * 4];
        for (i, &val) in committed.iter().skip(PROGRAM_VK_LEN).take(ZISK_PUBLICS).enumerate() {
            data[i * 4..(i + 1) * 4].copy_from_slice(&(canonical(val) as u32).to_le_bytes());
        }
        PublicValues { data: data.to_vec(), ptr: AtomicUsize::new(0) }
    }

    /// [`Proof::publics`], but rejects a body whose committed publics are not a
    /// well-formed, canonical `[program_vk(4) | inputs(ZISK_PUBLICS)]` vector.
    ///
    /// `Proof::new` and the raw bincode decode paths build bodies the ingest checks never
    /// see, so this is the accessor to reach for when the proof's provenance is unknown.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::InvalidProof`] if the committed publics are the wrong
    /// length or hold a non-canonical Goldilocks element.
    pub fn try_publics(&self) -> Result<PublicValues> {
        let committed = self.committed_publics();
        ensure_canonical_publics(committed)?;
        Ok(PublicValues::new_from_u64(committed))
    }

    /// The full-width (u64) publics `[program_vk(4)][user(ZISK_PUBLICS)]` for a
    /// Vadcop proof — the untruncated field elements the proof committed to.
    /// Used by the recursion round-trip; `None` for Plonk (no u64 form exists).
    pub fn publics_full(&self) -> Option<&[u64]> {
        match &self.body {
            ProofBody::Vadcop { publics_full, .. } => Some(publics_full),
            ProofBody::Plonk { .. } => None,
        }
    }

    /// Derive the `ProofKind` from the body discriminant.
    pub fn kind(&self) -> ProofKind {
        match &self.body {
            ProofBody::Vadcop { kind: VadcopKind::Minimal, .. } => ProofKind::VadcopFinalMinimal,
            ProofBody::Vadcop { .. } => ProofKind::VadcopFinal,
            ProofBody::Plonk { .. } => ProofKind::Plonk,
        }
    }

    /// Whether the underlying proof payload is empty (used to detect non-prove flows).
    pub fn is_empty(&self) -> bool {
        match &self.body {
            ProofBody::Vadcop { proof, .. } => proof.is_empty(),
            ProofBody::Plonk { proof_bytes, .. } => proof_bytes.is_empty(),
        }
    }

    /// Save the proof to a file using bincode serialization.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::Io`] if the parent directory or file cannot be created,
    /// or if serializing the proof to the file fails.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                CommonError::Io(format!(
                    "failed to create parent directory {}: {e}",
                    parent.display()
                ))
            })?;
        }

        let mut file = File::create(path).map_err(|e| {
            CommonError::Io(format!(
                "failed to create file for saving proof: {}: {e}",
                path.display()
            ))
        })?;
        bincode::serde::encode_into_std_write(self, &mut file, bincode::config::standard())
            .map(|_| ())
            .map_err(|e| CommonError::Io(format!("Failed to save proof: {}", e)))
    }

    /// Load a proof from a file using bincode deserialization.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::Io`] if the file cannot be opened or its contents
    /// cannot be deserialized into a [`Proof`].
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let mut file = File::open(path.as_ref()).map_err(|e| {
            CommonError::Io(format!(
                "failed to open file for loading proof: {}: {e}",
                path.as_ref().display()
            ))
        })?;
        let proof: Proof =
            bincode::serde::decode_from_std_read(&mut file, bincode::config::standard())
                .map_err(|e| CommonError::Io(format!("Failed to load proof: {}", e)))?;
        // bincode will happily decode a non-canonical or misshapen `publics_full`.
        ensure_stored_publics(&proof.body)?;
        Ok(proof)
    }

    /// The committed `publics_full` (`[program_vk | inputs]`) for either flavor —
    /// the single source of truth the getters and verification derive from.
    fn committed_publics(&self) -> &[u64] {
        match &self.body {
            ProofBody::Vadcop { publics_full, .. } | ProofBody::Plonk { publics_full, .. } => {
                publics_full
            }
        }
    }

    /// Extract a `VadcopFinalProof` from the proof body.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::InvalidProof`] if the proof is not a Vadcop final proof.
    pub fn get_vadcop_final_proof(&self) -> Result<VadcopFinalProof> {
        match &self.body {
            ProofBody::Vadcop { proof, kind, hash, publics_full, .. } => {
                // `stark_publics` re-adds the flag, so a stored vector that already
                // carries one would come back 70 wide. Vadcop storage is flag-free by
                // construction, but `Proof::new` and raw deserialization never check
                // that, and this conversion feeds proofman directly.
                ensure_stored_publics(&self.body)?;

                // The STARK layer commits to the full-width publics INCLUDING the
                // is_vadcop_final_proof flag; `kind.stark_publics` re-adds it to
                // the canonical flag-free `publics_full` (full u64 width — the
                // truncated u32 view would break re-verification).
                Ok(VadcopFinalProof::new(
                    proof.clone(),
                    kind.stark_publics(publics_full),
                    kind.is_minimal(),
                    hash.clone(),
                ))
            }
            ProofBody::Plonk { .. } => {
                Err(CommonError::InvalidProof("Proof is not a Vadcop final proof".to_string()))
            }
        }
    }

    /// The `VadcopFinalProof` to fold into a recursion step.
    ///
    /// Refuses a compressed proof. `FinalCompressed` strips the `is_vadcop_final_proof`
    /// flag, so the recurser — which reads slot 0 as that flag and expects the 69-word
    /// layout — would take the first program-VK limb for the flag and shift the whole
    /// statement by one. A limb of 0 or 1 makes that misread silent. Compression is a
    /// terminal step, not a foldable one.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::InvalidProof`] if the proof is compressed, or is not a
    /// Vadcop final proof.
    pub fn get_vadcop_final_proof_to_aggregate(&self) -> Result<VadcopFinalProof> {
        if let ProofBody::Vadcop { kind, .. } = &self.body {
            if kind.is_minimal() {
                return Err(CommonError::InvalidProof(
                    "a compressed (minimal) proof cannot be aggregated: compression strips \
                     the is_vadcop_final_proof flag the aggregator reads at public slot 0, \
                     and it cannot be recovered. Produce the leaf uncompressed \
                     (ProofKind::VadcopFinal) if you intend to fold it — note the embedded \
                     client defaults to ProofKind::VadcopFinalMinimal"
                        .to_string(),
                ));
            }
        }
        self.get_vadcop_final_proof()
    }

    /// Get the proof data as a vector of u64 values.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::InvalidProof`] if the program or Zisk verification key
    /// has an unexpected length, or if the proof is not a Vadcop proof.
    pub fn get_proof_u64(&self) -> Result<Vec<u64>> {
        match &self.body {
            ProofBody::Vadcop { proof, zisk_vk, kind, hash, publics_full } => {
                if self.program_vk.vk.len() != PROGRAM_VK_LEN {
                    return Err(CommonError::InvalidProof(format!(
                        "Invalid program_vk length: expected {}, got {}",
                        PROGRAM_VK_LEN,
                        self.program_vk.vk.len()
                    )));
                }
                if zisk_vk.len() != PROGRAM_VK_LEN {
                    return Err(CommonError::InvalidProof(format!(
                        "Invalid zisk_vk length: expected {}, got {}",
                        PROGRAM_VK_LEN,
                        zisk_vk.len()
                    )));
                }

                // The serialized STARK public vector must carry the
                // is_vadcop_final_proof flag (its Fiat-Shamir transcript is over
                // the full [flag? | vk | inputs]); `kind.stark_publics` re-adds it
                // to the canonical flag-free `publics_full`, at full u64 width (no
                // u32 truncation). Minimal proofs stay flag-free (68).
                let stark_publics = kind.stark_publics(publics_full);
                let n_publics = stark_publics.len();

                // The family travels with the proof so a reader needs no side channel to
                // learn which verifier to run. Routing metadata, not authority: a wrong
                // tag fails against the reader's expected verification key.
                let tag = zisk_verifier::hash_tag(hash).ok_or_else(|| {
                    CommonError::InvalidProof(format!("unrecognized proof hash family {hash:?}"))
                })?;

                // Format: [minimal(1)][n_publics(1)][flag?|vk|inputs][proof][zisk_vk(4)][tag(1)]
                let mut words =
                    Vec::with_capacity(2 + n_publics + proof.len() + zisk_vk.len() + 1);
                words.push(kind.is_minimal() as u64);
                words.push(n_publics as u64);
                words.extend_from_slice(&stark_publics);
                words.extend_from_slice(proof);
                words.extend_from_slice(zisk_vk);
                words.push(tag);

                Ok(words)
            }
            ProofBody::Plonk { .. } => Err(CommonError::InvalidProof(
                "Proof not suitable for get_proof_u64. Only VadcopFinal and VadcopFinalMinimal proofs are supported.".to_string()
            )),
        }
    }

    /// Get the proof data as a vector of bytes.
    ///
    /// # Errors
    ///
    /// Returns [`CommonError::InvalidProof`] under the same conditions as
    /// [`get_proof_u64`](Self::get_proof_u64), which this method builds upon.
    pub fn get_proof_bytes(&self) -> Result<Vec<u8>> {
        let words = self.get_proof_u64()?;
        let mut bytes = Vec::with_capacity(words.len() * 8);
        for w in &words {
            bytes.extend_from_slice(&w.to_le_bytes());
        }
        Ok(bytes)
    }

    /// Returns the u32 `PublicValues` view of this proof's publics.
    pub fn get_publics(&self) -> PublicValues {
        self.publics()
    }

    /// The program verification key committed by this proof.
    ///
    /// Derived from the committed `publics_full` (the ROM-root limbs, reduced to canonical
    /// representatives) rather than the stored `program_vk` copy, which is untrusted
    /// metadata. `hash_mode` is carried through unchanged.
    pub fn get_program_vk(&self) -> ProgramVK {
        // `take` rather than `[..PROGRAM_VK_LEN]`: this getter is reachable on an
        // unverified proof (verify()/load() enforce the length, but a hand-built `Proof`
        // bypasses them), so a short committed vector must not panic.
        ProgramVK {
            vk: program_publics(self.committed_publics())
                .iter()
                .take(PROGRAM_VK_LEN)
                .map(|&w| canonical(w))
                .collect(),
            hash_mode: self.program_vk.hash_mode,
        }
    }

    /// Create Proof directly from a Vadcop proof u64 array.
    ///
    /// This method parses the proof format (n_publics, publics..., proof...) and extracts
    /// the public values and program VK directly, without creating an intermediate VadcopFinalProof.
    ///
    /// # Parameters
    ///
    /// * `proof` - The proof as a slice of u64 values
    /// * `minimal` - Whether the proof is minimal
    /// * `zisk_vk` - The Vadcop verification key (4 u64s)
    /// * `hash` - Hash family the proof was generated with (e.g. "Poseidon1" / "Poseidon2")
    ///
    /// # Returns
    ///
    /// A Proof containing the parsed proof, publics, and program VK
    ///
    /// # Errors
    ///
    /// - [`CommonError::InvalidProof`] if `zisk_vk` has an unexpected length or the
    ///   proof bytes cannot be parsed.
    /// - [`CommonError::Invalid`] if `hash` is not a recognized proof hash family.
    pub fn new_from_vadcop_proof(
        proof: &[u64],
        minimal: bool,
        zisk_vk: Vec<u64>,
        hash: String,
    ) -> Result<Self> {
        if zisk_vk.len() != PROGRAM_VK_LEN {
            return Err(CommonError::InvalidProof(format!(
                "Invalid zisk_vk length: expected {}, got {}",
                PROGRAM_VK_LEN,
                zisk_vk.len()
            )));
        }

        // `from_str` is case-insensitive; downstream comparison and dispatch are exact
        // string matches, so keep the canonical spelling rather than the caller's.
        let hash_mode = hash.parse::<HashMode>().map_err(|e| {
            CommonError::Invalid(format!("unrecognized proof hash family {hash:?}: {e}"))
        })?;
        let hash = hash_mode.as_str().to_string();

        // `new_from_proof` accepts any count that fits the slice, and a short one then
        // trips `ProgramVK::new_from_publics_with_mode`'s assert. Pin the stage's exact
        // width first so malformed input is an `InvalidProof`, not a panic.
        let expected_n_publics = zisk_verifier::expected_n_publics(minimal);
        match proof.first() {
            Some(&n) if n == expected_n_publics as u64 => {}
            Some(&n) => {
                return Err(CommonError::InvalidProof(format!(
                    "proof declares {n} publics, expected {expected_n_publics} for this stage"
                )))
            }
            None => {
                return Err(CommonError::InvalidProof(
                    "Vadcop proof is empty, cannot read its public count".to_string(),
                ))
            }
        }

        let vadcop_proof =
            VadcopFinalProof::new_from_proof(proof, minimal, hash.clone()).map_err(|e| {
                CommonError::InvalidProof(format!("Failed to parse Vadcop proof: {}", e))
            })?;

        ensure_canonical_publics(&vadcop_proof.public_values)?;

        let program_vk =
            ProgramVK::new_from_publics_with_mode(&vadcop_proof.public_values, hash_mode);

        // Classify by the raw publics, then normalize ONCE to the flag-free
        // `[vk | inputs]` view. A minimal proof is already flag-free; a
        // Final/Recurser proof carries the `is_vadcop_final_proof` flag at index
        // 0, which is captured in `kind` and stripped from stored `publics_full`.
        let kind = if minimal {
            VadcopKind::Minimal
        } else {
            // Not `from_publics_full`: it maps every non-zero flag to `Final`, so a flag
            // of 2 would be accepted and silently change the committed statement.
            match vadcop_proof.public_values[0] {
                0 => VadcopKind::Recurser,
                IS_VADCOP_FINAL_PROOF => VadcopKind::Final,
                other => {
                    return Err(CommonError::InvalidProof(format!(
                        "is_vadcop_final_proof must be 0 or {IS_VADCOP_FINAL_PROOF}, got {other}"
                    )))
                }
            }
        };
        let publics_full = program_publics(&vadcop_proof.public_values).to_vec();

        Ok(Self {
            body: ProofBody::Vadcop {
                proof: vadcop_proof.proof,
                zisk_vk,
                kind,
                hash,
                // Canonical flag-free `[program_vk(4) | inputs(64)]` (68), full
                // u64 width. The flag lives in `kind`; STARK/serialization paths
                // re-add it via `kind.flag()`.
                publics_full,
            },
            program_vk,
        })
    }

    /// Verify the proof using the default values stored in this instance.
    ///
    /// For custom verification with overridden values, use the builder methods:
    /// - `with_publics()` to override public values
    /// - `with_program_vk()` to override program verification key
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Default verification
    /// proof.verify()?;
    ///
    /// // Custom verification with overridden publics
    /// proof.with_publics(&custom_publics).verify()?;
    ///
    /// // Custom verification with multiple overrides
    /// proof.with_publics(&custom_publics).with_program_vk(&custom_program_vk).verify()?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`ZiskVerifyBuilder::verify`], which this method delegates to.
    pub fn verify(&self) -> Result<()> {
        ZiskVerifyBuilder::new(self).verify()
    }

    /// Start a custom verification with no overrides applied yet.
    pub fn verify_builder(&self) -> ZiskVerifyBuilder<'_> {
        ZiskVerifyBuilder::new(self)
    }

    /// Start building a custom verification by overriding the public values.
    ///
    /// Returns a builder that allows chaining additional overrides before calling `verify()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// proof.with_publics(&custom_publics).verify()?;
    /// proof.with_publics(&custom_publics).with_program_vk(&custom_program_vk).verify()?;
    /// ```
    pub fn with_publics<'a>(&'a self, publics: &'a PublicValues) -> ZiskVerifyBuilder<'a> {
        ZiskVerifyBuilder::new(self).with_publics(publics)
    }

    /// Start building a custom verification by overriding the program verification key.
    ///
    /// Returns a builder that allows chaining additional overrides before calling `verify()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// proof.with_program_vk(&custom_program_vk).verify()?;
    /// proof.with_program_vk(&custom_program_vk).with_publics(&custom_publics).verify()?;
    /// ```
    pub fn with_program_vk<'a>(&'a self, program_vk: &'a ProgramVK) -> ZiskVerifyBuilder<'a> {
        ZiskVerifyBuilder::new(self).with_program_vk(program_vk)
    }

    /// Start a custom verification with the trusted PLONK circuit key. See
    /// [`ZiskVerifyBuilder::with_plonk_vk`].
    pub fn with_plonk_vk<'a>(&'a self, plonk_vkey: &'a PlonkVkey) -> ZiskVerifyBuilder<'a> {
        ZiskVerifyBuilder::new(self).with_plonk_vk(plonk_vkey)
    }

    /// Start a custom verification with the trusted recursion setup key. See
    /// [`ZiskVerifyBuilder::with_setup_vk`].
    pub fn with_setup_vk<'a>(&'a self, setup_vk: &'a [u64]) -> ZiskVerifyBuilder<'a> {
        ZiskVerifyBuilder::new(self).with_setup_vk(setup_vk)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn verify_returns_err_for_malformed_vadcop_final_minimal() {
        let result = Proof::new(
            ProofBody::Vadcop {
                proof: vec![],
                zisk_vk: vec![0u64; PROGRAM_VK_LEN],
                kind: VadcopKind::Minimal,
                hash: "Poseidon2".to_string(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
            },
            ProgramVK::new_empty(),
        )
        .verify();

        assert!(result.is_err(), "expected Err for malformed proof, got {:?}", result);
    }

    #[test]
    fn verify_returns_err_for_malformed_vadcop_final() {
        let result = Proof::new(
            ProofBody::Vadcop {
                proof: vec![],
                zisk_vk: vec![0u64; PROGRAM_VK_LEN],
                kind: VadcopKind::Final,
                hash: "Poseidon2".to_string(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
            },
            ProgramVK::new_empty(),
        )
        .verify();

        assert!(result.is_err(), "expected Err for malformed proof, got {:?}", result);
    }

    /// `[n_publics][publics][proof]`, the layout `new_from_vadcop_proof` ingests.
    fn serialized_vadcop(publics: &[u64]) -> Vec<u64> {
        let mut v = vec![publics.len() as u64];
        v.extend_from_slice(publics);
        v.extend_from_slice(&[0u64; 8]);
        v
    }

    /// A short count would otherwise reach `ProgramVK::new_from_publics_with_mode`,
    /// whose assert panics instead of returning the documented `InvalidProof`.
    #[test]
    fn new_from_vadcop_proof_rejects_a_wrong_public_count() {
        let err = Proof::new_from_vadcop_proof(
            &serialized_vadcop(&[1, 2]),
            false,
            vec![1, 2, 3, 4],
            "Poseidon2".to_string(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("declares 2 publics"), "got: {err}");
    }

    /// `from_publics_full` maps every non-zero flag to `Final`; an out-of-range flag must
    /// be refused rather than silently reinterpreted.
    #[test]
    fn new_from_vadcop_proof_rejects_an_out_of_range_flag() {
        let mut publics = vec![0u64; VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS];
        publics[0] = 2;
        let err = Proof::new_from_vadcop_proof(
            &serialized_vadcop(&publics),
            false,
            vec![1, 2, 3, 4],
            "Poseidon2".to_string(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("is_vadcop_final_proof"), "got: {err}");
    }

    #[test]
    fn new_from_vadcop_proof_rejects_a_non_canonical_public() {
        let mut publics = vec![0u64; VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS];
        publics[0] = IS_VADCOP_FINAL_PROOF;
        publics[VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN] = GOLDILOCKS_ORDER;
        let err = Proof::new_from_vadcop_proof(
            &serialized_vadcop(&publics),
            false,
            vec![1, 2, 3, 4],
            "Poseidon2".to_string(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("canonical"), "got: {err}");
    }

    /// `verify()` hashes `publics_full`, so the reported view must come from there and
    /// not from the independently deserialized `Plonk.publics` copy.
    #[test]
    fn plonk_publics_come_from_the_committed_vector() {
        let mut publics_full = vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS];
        publics_full[PROGRAM_VK_LEN] = 0xAABB;

        // A stored copy that disagrees with the committed statement.
        let mut lying = PublicValues::new_empty();
        lying.data[0..4].copy_from_slice(&0xDEADu32.to_le_bytes());

        let proof = Proof::new(
            ProofBody::Plonk {
                proof_bytes: vec![],
                plonk_vk: Box::new(PlonkVkBlob {
                    vadcop_vk: vec![0u64; PROGRAM_VK_LEN],
                    plonk_vkey: dummy_plonk_vkey(),
                }),
                publics: lying,
                publics_full,
                rootc: vec![0u64; PROGRAM_VK_LEN],
            },
            ProgramVK::new_empty(),
        );

        assert_eq!(&proof.publics().data[0..4], &0xAABBu32.to_le_bytes());
    }

    /// An override is spliced into the verified statement, so the domain guard must read
    /// the overridden VK — otherwise it guards limbs nothing is verified against.
    #[test]
    fn recurser_domain_check_follows_the_program_vk_override() {
        let proof = vadcop_proof(VadcopKind::Recurser, flag_free_publics([1, 2, 3, 4]));
        let foreign = ProgramVK { vk: vec![9, 9, 9, 9], hash_mode: HashMode::Poseidon2 };
        let err =
            proof.with_program_vk(&foreign).with_setup_vk(&[1, 2, 3, 4]).verify().unwrap_err();
        assert!(err.to_string().contains("recursion domain"), "got: {err}");
    }

    /// Compression strips the flag the recurser reads at slot 0, so folding a compressed
    /// proof would take the first VK limb for the flag and shift the statement by one.
    #[test]
    fn a_compressed_proof_cannot_be_aggregated() {
        let minimal = vadcop_proof(VadcopKind::Minimal, flag_free_publics([1, 2, 3, 4]));
        let err = minimal.get_vadcop_final_proof_to_aggregate().unwrap_err();
        assert!(err.to_string().contains("cannot be aggregated"), "got: {err}");

        // The uncompressed flavors still fold, carrying the 69-word layout.
        for kind in [VadcopKind::Final, VadcopKind::Recurser] {
            let p = vadcop_proof(kind, flag_free_publics([1, 2, 3, 4]));
            let vfp = p.get_vadcop_final_proof_to_aggregate().unwrap();
            assert_eq!(
                vfp.public_values.len(),
                VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS
            );
        }
    }

    /// `publics()` must stay in bounds for a body that never passed load/verify, and
    /// `try_publics()` must refuse to answer for it at all.
    #[test]
    fn try_publics_rejects_what_publics_can_only_guess() {
        let misshapen = Proof::new(
            ProofBody::Plonk {
                proof_bytes: vec![],
                plonk_vk: Box::new(PlonkVkBlob {
                    vadcop_vk: vec![0u64; PROGRAM_VK_LEN],
                    plonk_vkey: dummy_plonk_vkey(),
                }),
                publics: PublicValues::new_empty(),
                publics_full: vec![1, 2],
                rootc: vec![0u64; PROGRAM_VK_LEN],
            },
            ProgramVK::new_empty(),
        );
        assert!(misshapen.try_publics().is_err());
        // Still safe to call, and its fixed-offset reads stay in bounds.
        assert_eq!(misshapen.publics().public_u64().len(), ZISK_PUBLICS);

        let ok = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        assert_eq!(ok.try_publics().unwrap().data, ok.publics().data);
    }

    /// A stage the proving key never builds is a malformed shape, not a failed
    /// statement, so it must not come back as `NotVerified`.
    #[test]
    fn verify_reports_a_nonexistent_stage_as_malformed() {
        let mut proof = vadcop_proof(VadcopKind::Minimal, flag_free_publics([1, 2, 3, 4]));
        if let ProofBody::Vadcop { hash, .. } = &mut proof.body {
            *hash = "blake3".to_string();
        }
        proof.program_vk.hash_mode = HashMode::Blake3;

        let err = proof.verify().unwrap_err();
        assert!(matches!(err, CommonError::InvalidProof(_)), "got: {err:?}");
        assert!(err.to_string().contains("no "), "got: {err}");
    }

    /// `stark_publics` re-adds the flag, so a stored vector that already carries one
    /// would reach proofman 70 wide. `Proof::new` bypasses the ingest checks.
    #[test]
    fn get_vadcop_final_proof_rejects_an_already_flagged_body() {
        let mut flagged = vec![0u64; VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS];
        flagged[0] = IS_VADCOP_FINAL_PROOF;
        let proof = vadcop_proof(VadcopKind::Final, flagged);

        let err = proof.get_vadcop_final_proof().unwrap_err();
        assert!(matches!(err, CommonError::InvalidProof(_)), "got: {err:?}");

        // A short vector must not reach proofman either.
        let short = vadcop_proof(VadcopKind::Final, vec![0u64; 3]);
        assert!(short.get_vadcop_final_proof().is_err());

        // The well-formed flag-free body still converts, and gains the flag exactly once.
        let ok = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        let vfp = ok.get_vadcop_final_proof().unwrap();
        assert_eq!(vfp.public_values.len(), VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS);
        assert_eq!(vfp.public_values[0], IS_VADCOP_FINAL_PROOF);
    }

    /// `ensure_stored_publics` still accepts the legacy flagged 69-word Plonk body, so
    /// pin that both accessors strip the flag rather than shifting the view by a word.
    /// `new_from_u64` normalizes internally; this guards anyone "simplifying" that away.
    #[test]
    fn a_flagged_plonk_body_is_not_shifted_by_a_word() {
        let mut flagged = vec![0u64; VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS];
        flagged[0] = IS_VADCOP_FINAL_PROOF;
        flagged[VADCOP_FINAL_FLAG_LEN..VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN]
            .copy_from_slice(&[11, 12, 13, 14]);
        flagged[VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN] = 0xAABB;

        let proof = Proof::new(
            ProofBody::Plonk {
                proof_bytes: vec![],
                plonk_vk: Box::new(PlonkVkBlob {
                    vadcop_vk: vec![0u64; PROGRAM_VK_LEN],
                    plonk_vkey: dummy_plonk_vkey(),
                }),
                publics: PublicValues::new_empty(),
                publics_full: flagged,
                rootc: vec![0u64; PROGRAM_VK_LEN],
            },
            ProgramVK::new_empty(),
        );

        // The first user input, not the last VK limb and not the flag.
        assert_eq!(&proof.publics().data[0..4], &0xAABBu32.to_le_bytes());
        assert_eq!(&proof.try_publics().unwrap().data[0..4], &0xAABBu32.to_le_bytes());
        assert_eq!(proof.get_program_vk().vk, vec![11, 12, 13, 14]);
    }

    /// A structurally valid (not cryptographically meaningful) PLONK vkey.
    fn dummy_plonk_vkey() -> PlonkVkey {
        let g1 = || ["0".to_string(), "0".to_string(), "1".to_string()];
        let g2 = || {
            [
                ["0".to_string(), "0".to_string()],
                ["0".to_string(), "0".to_string()],
                ["1".to_string(), "0".to_string()],
            ]
        };
        PlonkVkey {
            protocol: "plonk".to_string(),
            curve: "bn128".to_string(),
            n_public: 1,
            power: 1,
            k1: "2".to_string(),
            k2: "3".to_string(),
            qm: g1(),
            ql: g1(),
            qr: g1(),
            qo: g1(),
            qc: g1(),
            s1: g1(),
            s2: g1(),
            s3: g1(),
            x_2: g2(),
            w: "1".to_string(),
        }
    }

    /// A flag-free Vadcop proof whose publics are well-shaped, for the guard tests.
    fn vadcop_proof(kind: VadcopKind, publics_full: Vec<u64>) -> Proof {
        Proof::new(
            ProofBody::Vadcop {
                proof: vec![0u64; 8],
                zisk_vk: vec![1, 2, 3, 4],
                kind,
                hash: "Poseidon2".to_string(),
                publics_full,
            },
            ProgramVK::new_from_publics_with_mode(&[1, 2, 3, 4], HashMode::Poseidon2),
        )
    }

    fn flag_free_publics(vk: [u64; PROGRAM_VK_LEN]) -> Vec<u64> {
        let mut p = vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS];
        p[..PROGRAM_VK_LEN].copy_from_slice(&vk);
        p
    }

    /// The Vadcop path ignores a PLONK key, so pinning one must be refused rather than
    /// silently verified as if the pin had applied.
    #[test]
    fn verify_rejects_a_plonk_key_pinned_on_a_vadcop_proof() {
        let proof = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        let vkey = dummy_plonk_vkey();
        let err = proof.with_plonk_vk(&vkey).verify().unwrap_err();
        assert!(err.to_string().contains("PLONK verification key was pinned"), "got: {err}");
    }

    /// The field verifier reads x and x+p as one element, so a non-canonical override
    /// would pin a key by value it does not equal byte-for-byte.
    #[test]
    fn verify_rejects_non_canonical_program_vk_override() {
        let proof = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        let shifted =
            ProgramVK { vk: vec![1 + GOLDILOCKS_ORDER, 2, 3, 4], hash_mode: HashMode::Poseidon2 };
        let err = proof.with_program_vk(&shifted).verify().unwrap_err();
        assert!(err.to_string().contains("non-canonical"), "got: {err}");
    }

    #[test]
    fn verify_rejects_non_canonical_setup_vk_override() {
        let proof = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        let err = proof.with_setup_vk(&[1 + GOLDILOCKS_ORDER, 2, 3, 4]).verify().unwrap_err();
        assert!(err.to_string().contains("non-canonical"), "got: {err}");
    }

    /// A fold must verify under the domain it declares, or a subtree from another
    /// recurser rides through.
    #[test]
    fn verify_rejects_a_recurser_proof_verifying_outside_its_domain() {
        let proof = vadcop_proof(VadcopKind::Recurser, flag_free_publics([9, 9, 9, 9]));
        let err = proof.with_setup_vk(&[1, 2, 3, 4]).verify().unwrap_err();
        assert!(err.to_string().contains("recursion domain"), "got: {err}");
    }

    /// bincode decodes a non-canonical word happily; `load` must not.
    #[test]
    fn load_rejects_a_non_canonical_stored_public() {
        let tmp = std::env::temp_dir().join(format!("proof_noncanon_{}.bin", std::process::id()));
        let mut publics = flag_free_publics([1, 2, 3, 4]);
        publics[PROGRAM_VK_LEN] = GOLDILOCKS_ORDER;
        vadcop_proof(VadcopKind::Final, publics).save(&tmp).unwrap();

        let err = Proof::load(&tmp).unwrap_err();
        std::fs::remove_file(&tmp).ok();
        assert!(err.to_string().contains("canonical"), "got: {err}");
    }

    /// The guest reads the family off the tail, so the tag must be the last word.
    #[test]
    fn serialized_proof_carries_the_hash_tag_last() {
        let proof = vadcop_proof(VadcopKind::Final, flag_free_publics([1, 2, 3, 4]));
        let words = proof.get_proof_u64().unwrap();
        assert_eq!(words.last().copied(), zisk_verifier::hash_tag("Poseidon2"));
    }

    /// Splicing a VK must keep every other slot at full u64 width — rebuilding from the
    /// u32 `PublicValues` view would truncate a recurser proof's inputs.
    #[test]
    fn splice_program_vk_preserves_wide_publics() {
        let mut publics = flag_free_publics([1, 2, 3, 4]);
        publics[PROGRAM_VK_LEN] = 1 << 40;

        let spliced = splice_program_vk(&publics, &[9, 9, 9, 9]).unwrap();

        assert_eq!(&spliced[..PROGRAM_VK_LEN], &[9, 9, 9, 9]);
        assert_eq!(spliced[PROGRAM_VK_LEN], 1 << 40, "wide public must not be truncated");
    }

    /// A raw vadcop_final vector carries the flag at index 0; splicing over it would
    /// shift the whole statement by one.
    #[test]
    fn splice_program_vk_normalizes_a_flagged_publics_vector() {
        let mut flagged = vec![0u64; VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN + ZISK_PUBLICS];
        flagged[0] = IS_VADCOP_FINAL_PROOF;
        flagged[VADCOP_FINAL_FLAG_LEN..VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN]
            .copy_from_slice(&[11, 12, 13, 14]);
        flagged[VADCOP_FINAL_FLAG_LEN + PROGRAM_VK_LEN] = 77;

        let spliced = splice_program_vk(&flagged, &[91, 92, 93, 94]).unwrap();

        assert_eq!(spliced.len(), PROGRAM_VK_LEN + ZISK_PUBLICS, "flag must be stripped");
        assert_eq!(&spliced[..PROGRAM_VK_LEN], &[91, 92, 93, 94], "vk must be replaced");
        assert_eq!(spliced[PROGRAM_VK_LEN], 77, "inputs must not shift");
    }

    /// A wrong-length `setup_vk` must return an error, not panic in
    /// `snark_publics_hash` (which slices on `PROGRAM_VK_LEN`).
    #[test]
    fn plonk_verify_rejects_wrong_len_setup_vk() {
        let vkey = dummy_plonk_vkey();
        let proof = Proof::new(
            ProofBody::Plonk {
                proof_bytes: vec![],
                plonk_vk: Box::new(PlonkVkBlob {
                    vadcop_vk: vec![0u64; PROGRAM_VK_LEN],
                    plonk_vkey: vkey,
                }),
                publics: PublicValues::new_empty(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
                rootc: vec![0u64; PROGRAM_VK_LEN],
            },
            ProgramVK::new_empty(),
        );
        // 3 limbs instead of PROGRAM_VK_LEN (4).
        let err = proof.with_setup_vk(&[1u64, 2, 3]).verify().unwrap_err();
        assert!(
            matches!(err, CommonError::InvalidProof(_)),
            "expected InvalidProof for wrong-length setup vk, got {err:?}"
        );
    }

    #[test]
    fn proof_save_load_roundtrip_vadcop() {
        let tmp = std::env::temp_dir().join(format!("proof_roundtrip_{}.bin", std::process::id()));
        let original = Proof::new(
            ProofBody::Vadcop {
                proof: vec![1, 2, 3, 4],
                zisk_vk: vec![10, 20, 30, 40],
                kind: VadcopKind::Minimal,
                hash: "Poseidon2".to_string(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
            },
            ProgramVK::new_from_publics(&[7, 8, 9, 10]),
        );

        original.save(&tmp).unwrap();
        let loaded = Proof::load(&tmp).unwrap();
        std::fs::remove_file(&tmp).ok();

        assert_eq!(loaded.kind(), ProofKind::VadcopFinalMinimal);
        match loaded.body {
            ProofBody::Vadcop { proof, zisk_vk, kind, hash, .. } => {
                assert_eq!(proof, vec![1, 2, 3, 4]);
                assert_eq!(zisk_vk, vec![10, 20, 30, 40]);
                assert_eq!(kind, VadcopKind::Minimal);
                assert_eq!(hash, "Poseidon2");
            }
            ProofBody::Plonk { .. } => panic!("expected Vadcop body after roundtrip"),
        }
        assert_eq!(loaded.program_vk.vk, vec![7, 8, 9, 10]);
    }

    #[test]
    fn proof_kind_derivation() {
        let vadcop = Proof::new(
            ProofBody::Vadcop {
                proof: vec![],
                zisk_vk: vec![],
                kind: VadcopKind::Final,
                hash: "Poseidon2".to_string(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
            },
            ProgramVK::new_empty(),
        );
        assert_eq!(vadcop.kind(), ProofKind::VadcopFinal);
        assert!(vadcop.is_empty());

        let minimal = Proof::new(
            ProofBody::Vadcop {
                proof: vec![1],
                zisk_vk: vec![],
                kind: VadcopKind::Minimal,
                hash: "Poseidon2".to_string(),
                publics_full: vec![0u64; PROGRAM_VK_LEN + ZISK_PUBLICS],
            },
            ProgramVK::new_empty(),
        );
        assert_eq!(minimal.kind(), ProofKind::VadcopFinalMinimal);
        assert!(!minimal.is_empty());
    }
}