world-id-primitives 0.9.0

Contains the raw base primitives (without implementations) for the World ID Protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
//! Module containing all the functionality to handle requests from Relying Parties (RPs) to Authenticators.
//!
//! Enables an RP to create a Proof request or a Session Proof request, and provides base functionality
//! for Authenticators to handle such requests.
mod constraints;
pub use constraints::{ConstraintExpr, ConstraintKind, ConstraintNode, MAX_CONSTRAINT_NODES};

use crate::{
    FieldElement, Nullifier, PrimitiveError, SessionId, SessionNullifier, ZeroKnowledgeProof,
    rp::RpId,
};
use serde::{Deserialize, Serialize, de::Error as _};
use std::collections::HashSet;
use taceo_oprf::types::OprfKeyId;
// The uuid crate is needed for wasm compatibility
use uuid as _;

/// Protocol schema version for proof requests and responses.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestVersion {
    /// Version 1
    V1 = 1,
}

impl serde::Serialize for RequestVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let v = *self as u8;
        serializer.serialize_u8(v)
    }
}

impl<'de> serde::Deserialize<'de> for RequestVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let v = u8::deserialize(deserializer)?;
        match v {
            1 => Ok(Self::V1),
            _ => Err(serde::de::Error::custom("unsupported version")),
        }
    }
}

/// A proof request from a Relying Party (RP) for an Authenticator.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProofRequest {
    /// Unique identifier for this request.
    pub id: String,
    /// Version of the request.
    pub version: RequestVersion,
    /// Unix timestamp (seconds) when the request was created.
    pub created_at: u64,
    /// Unix timestamp (seconds) when the request expires.
    pub expires_at: u64,
    /// Registered RP identifier from the `RpRegistry`.
    pub rp_id: RpId,
    /// `OprfKeyId` of the RP.
    pub oprf_key_id: OprfKeyId,
    /// Session identifier that links proofs for the same user/RP pair across requests.
    ///
    /// If provided, a Session Proof will be generated instead of a Uniqueness Proof.
    /// The proof will only be valid if the session ID is meant for this context and this
    /// particular World ID holder.
    pub session_id: Option<SessionId>,
    /// An RP-defined context that scopes what the user is proving uniqueness on.
    ///
    /// This parameter expects a field element. When dealing with strings or bytes,
    /// hash with a byte-friendly hash function like keccak256 or SHA256 and reduce to the field.
    pub action: Option<FieldElement>,
    /// The RP's ECDSA signature over the request.
    #[serde(with = "crate::serde_utils::hex_signature")]
    pub signature: alloy::signers::Signature,
    /// Unique nonce for this request provided by the RP.
    pub nonce: FieldElement,
    /// Specific credential requests. This defines which credentials to ask for.
    #[serde(rename = "proof_requests")]
    pub requests: Vec<RequestItem>,
    /// Constraint expression (all/any/enumerate) optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraints: Option<ConstraintExpr<'static>>,
}

/// Per-credential request payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequestItem {
    /// An RP-defined identifier for this request item used to match against constraints and responses.
    ///
    /// Example: `orb`, `document`.
    pub identifier: String,

    /// Unique identifier for the credential schema and issuer pair.
    ///
    /// Registered in the `CredentialSchemaIssuerRegistry`.
    pub issuer_schema_id: u64,

    /// Arbitrary data provided by the RP that gets cryptographically bound into the proof.
    ///
    /// When present, the Authenticator hashes this via `signal_hash` and commits it into the
    /// proof circuit so the RP can tie the proof to a particular context.
    ///
    /// The reason why the signal is expected as raw bytes and hashed by the Authenticator instead
    /// of directly as a field element is so that in the future it can be displayed to the user in
    /// a human-readable way.
    ///
    /// Raw bytes provides maximum flexibility because for on-chain use cases any arbitrary set of
    /// inputs can be ABI-encoded to be verified on-chain.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(with = "crate::serde_utils::hex_bytes_opt")]
    pub signal: Option<Vec<u8>>,

    /// Minimum `genesis_issued_at` timestamp that the used Credential must meet.
    ///
    /// If present, the proof will include a constraint that the credential's genesis issued at timestamp
    /// is greater than or equal to this value. Can be set to 0 to skip.
    /// This is useful for migration from previous protocol versions.
    pub genesis_issued_at_min: Option<u64>,

    /// The minimum expiration required for the Credential used in the proof.
    ///
    /// If the constraint is not required, it should use the current time as the minimum expiration.
    /// The Authenticator will normally expose the effective input used in the proof.
    ///
    /// This is particularly useful to specify a minimum duration for a Credential proportional to the action
    /// being performed. For example, when claiming a benefit that is once every 6 months, the minimum duration
    /// can be set to 180 days to prevent double claiming in that period in case the Credential is set to expire earlier.
    ///
    /// It is an RP's responsibility to understand the issuer's policies regarding expiration to ensure the request
    /// can be fulfilled.
    ///
    /// If not provided, this will default to the [`ProofRequest::created_at`] attribute.
    pub expires_at_min: Option<u64>,
}

impl RequestItem {
    /// Create a new request item with the given identifier, issuer schema ID and optional signal.
    #[must_use]
    pub const fn new(
        identifier: String,
        issuer_schema_id: u64,
        signal: Option<Vec<u8>>,
        genesis_issued_at_min: Option<u64>,
        expires_at_min: Option<u64>,
    ) -> Self {
        Self {
            identifier,
            issuer_schema_id,
            signal,
            genesis_issued_at_min,
            expires_at_min,
        }
    }

    /// Get the signal hash for the request item.
    #[must_use]
    pub fn signal_hash(&self) -> FieldElement {
        if let Some(signal) = &self.signal {
            FieldElement::from_arbitrary_raw_bytes(signal)
        } else {
            FieldElement::ZERO
        }
    }

    /// Get the effective minimum expiration timestamp for this request item.
    ///
    /// If `expires_at_min` is `Some`, returns that value.
    /// Otherwise, returns the `request_created_at` value (which should be the `ProofRequest::created_at` timestamp).
    #[must_use]
    pub const fn effective_expires_at_min(&self, request_created_at: u64) -> u64 {
        match self.expires_at_min {
            Some(value) => value,
            None => request_created_at,
        }
    }
}

/// Overall response from the Authenticator to the RP
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProofResponse {
    /// The response id references request id
    pub id: String,
    /// Version corresponding to request version
    pub version: RequestVersion,
    /// RP session identifier that links multiple proofs for the same
    /// user/RP pair across requests.
    ///
    /// For an initial request which creates a session, this contains
    /// the newly generated `SessionId`. For subsequent Session Proofs, this
    /// echoes back the `SessionId` from the request for convenience.
    ///
    /// This is optional as it's not provided in Uniqueness Proofs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<SessionId>,
    /// Error message if the entire proof request failed.
    /// When present, the responses array will be empty.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Per-credential results (empty if error is present)
    pub responses: Vec<ResponseItem>,
}

/// Per-credential response item returned by the Authenticator.
///
/// Each entry corresponds to one requested credential with its proof material.
/// If any credential cannot be satisfied, the entire proof response will have
/// an error at the `ProofResponse` level with an empty `responses` array.
///
/// # Nullifier Types
///
/// - **Uniqueness proofs**: Use `nullifier` field (a single `FieldElement`).
///   The contract's `verify()` function takes this as a separate `uint256 nullifier` param.
///
/// - **Session proofs**: Use `session_nullifier` field (contains both nullifier and action).
///   The contract's `verifySession()` function expects `uint256[2] sessionNullifier`.
///
/// Exactly one of `nullifier` or `session_nullifier` should be present.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResponseItem {
    /// An RP-defined identifier for this request item used to match against constraints and responses.
    ///
    /// Example: `orb`, `document`.
    pub identifier: String,

    /// Unique identifier for the credential schema and issuer pair.
    pub issuer_schema_id: u64,

    /// Encoded World ID Proof. See [`ZeroKnowledgeProof`] for more details.
    pub proof: ZeroKnowledgeProof,

    /// A [`Nullifier`] for Uniqueness proofs.
    ///
    /// Present for Uniqueness proofs, absent for Session proofs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nullifier: Option<Nullifier>,

    /// A [`SessionNullifier`] for Session proofs.
    ///
    /// Present for Session proofs, absent for Uniqueness proofs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_nullifier: Option<SessionNullifier>,

    /// The minimum expiration required for the Credential used in the proof.
    ///
    /// This precise value must be used when verifying the proof on-chain.
    pub expires_at_min: u64,
}

impl ProofResponse {
    /// Determine if constraints are satisfied given a constraint expression.
    /// Returns false if the response has an error.
    #[must_use]
    pub fn constraints_satisfied(&self, constraints: &ConstraintExpr<'_>) -> bool {
        // If there's an error, constraints cannot be satisfied
        if self.error.is_some() {
            return false;
        }

        let provided: HashSet<&str> = self
            .responses
            .iter()
            .map(|item| item.identifier.as_str())
            .collect();

        constraints.evaluate(&|t| provided.contains(t))
    }
}

impl ResponseItem {
    /// Create a new response item for a Uniqueness proof.
    #[must_use]
    pub const fn new_uniqueness(
        identifier: String,
        issuer_schema_id: u64,
        proof: ZeroKnowledgeProof,
        nullifier: Nullifier,
        expires_at_min: u64,
    ) -> Self {
        Self {
            identifier,
            issuer_schema_id,
            proof,
            nullifier: Some(nullifier),
            session_nullifier: None,
            expires_at_min,
        }
    }

    /// Create a new response item for a Session proof.
    #[must_use]
    pub const fn new_session(
        identifier: String,
        issuer_schema_id: u64,
        proof: ZeroKnowledgeProof,
        session_nullifier: SessionNullifier,
        expires_at_min: u64,
    ) -> Self {
        Self {
            identifier,
            issuer_schema_id,
            proof,
            nullifier: None,
            session_nullifier: Some(session_nullifier),
            expires_at_min,
        }
    }

    /// Returns true if this is a Session proof response.
    #[must_use]
    pub const fn is_session(&self) -> bool {
        self.session_nullifier.is_some()
    }

    /// Returns true if this is a Uniqueness proof response.
    #[must_use]
    pub const fn is_uniqueness(&self) -> bool {
        self.nullifier.is_some()
    }
}

impl ProofRequest {
    /// Determine which requested credentials to prove given available credentials.
    ///
    /// Returns `None` if constraints (or lack thereof) cannot be satisfied with the available set.
    ///
    /// # Panics
    /// Panics if constraints are present but invalid according to the type invariants
    /// (this should not occur as constraints are provided by trusted request issuer).
    #[must_use]
    pub fn credentials_to_prove(&self, available: &HashSet<u64>) -> Option<Vec<&RequestItem>> {
        // Pre-compute which identifiers have an available issuer_schema_id
        let available_identifiers: HashSet<&str> = self
            .requests
            .iter()
            .filter(|r| available.contains(&r.issuer_schema_id))
            .map(|r| r.identifier.as_str())
            .collect();

        let is_selectable = |identifier: &str| available_identifiers.contains(identifier);

        // If no explicit constraints: require all requested be available
        if self.constraints.is_none() {
            return if self
                .requests
                .iter()
                .all(|r| available.contains(&r.issuer_schema_id))
            {
                Some(self.requests.iter().collect())
            } else {
                None
            };
        }

        // Compute selected identifiers using the constraint expression
        let selected_identifiers = select_expr(self.constraints.as_ref().unwrap(), &is_selectable)?;
        let selected_set: HashSet<&str> = selected_identifiers.into_iter().collect();

        // Return proof_requests in original order filtered by selected identifiers
        let result: Vec<&RequestItem> = self
            .requests
            .iter()
            .filter(|r| selected_set.contains(r.identifier.as_str()))
            .collect();
        Some(result)
    }

    /// Find a request item by issuer schema ID if available
    #[must_use]
    pub fn find_request_by_issuer_schema_id(&self, issuer_schema_id: u64) -> Option<&RequestItem> {
        self.requests
            .iter()
            .find(|r| r.issuer_schema_id == issuer_schema_id)
    }

    /// Returns true if the request is expired relative to now (unix timestamp in seconds)
    #[must_use]
    pub const fn is_expired(&self, now: u64) -> bool {
        now > self.expires_at
    }

    /// Compute the digest hash of this request that should be signed by the RP, which right now
    /// includes the `nonce` and the timestamp of the request.
    ///
    /// # Returns
    /// A 32-byte hash that represents this request and should be signed by the RP.
    ///
    /// # Errors
    /// Returns a `PrimitiveError` if `FieldElement` serialization fails (which should never occur in practice).
    ///
    /// The digest is computed as: `SHA256(version || nonce || created_at || expires_at || action)`.
    /// This mirrors the RP signature message format from `rp::compute_rp_signature_msg`.
    /// Note: the timestamp is encoded as big-endian to mirror the RP-side signing
    /// performed in test fixtures and the OPRF stub.
    pub fn digest_hash(&self) -> Result<[u8; 32], PrimitiveError> {
        use crate::rp::compute_rp_signature_msg;
        use k256::sha2::{Digest, Sha256};

        let msg = compute_rp_signature_msg(
            *self.nonce,
            self.created_at,
            self.expires_at,
            self.action.map(|v| *v),
        );
        let mut hasher = Sha256::new();
        hasher.update(&msg);
        Ok(hasher.finalize().into())
    }

    /// Returns true if this request is for a Session proof (i.e., has a session ID).
    #[must_use]
    pub const fn is_session_proof(&self) -> bool {
        self.session_id.is_some()
    }

    /// Validate that a response satisfies this request: id match and constraints semantics.
    ///
    /// # Errors
    /// Returns a `ValidationError` if the response does not correspond to this request or
    /// does not satisfy the declared constraints.
    pub fn validate_response(&self, response: &ProofResponse) -> Result<(), ValidationError> {
        // Validate id and version match
        if self.id != response.id {
            return Err(ValidationError::RequestIdMismatch);
        }
        if self.version != response.version {
            return Err(ValidationError::VersionMismatch);
        }

        // If response has an error, it failed to satisfy constraints
        if let Some(error) = &response.error {
            return Err(ValidationError::ProofGenerationFailed(error.clone()));
        }

        // Session ID of the response doesn't match the request's session ID (if present)
        if self.session_id.is_some() && self.session_id != response.session_id {
            return Err(ValidationError::SessionIdMismatch);
        }

        // Validate response items correspond to request items and are unique.
        let mut provided: HashSet<&str> = HashSet::new();
        for response_item in &response.responses {
            if !provided.insert(response_item.identifier.as_str()) {
                return Err(ValidationError::DuplicateCredential(
                    response_item.identifier.clone(),
                ));
            }

            let request_item = self
                .requests
                .iter()
                .find(|r| r.identifier == response_item.identifier)
                .ok_or_else(|| {
                    ValidationError::UnexpectedCredential(response_item.identifier.clone())
                })?;

            if self.session_id.is_some() {
                // Session proof: must have session_nullifier
                if response_item.session_nullifier.is_none() {
                    return Err(ValidationError::MissingSessionNullifier(
                        response_item.identifier.clone(),
                    ));
                }
            } else {
                // Uniqueness proof: must have nullifier
                if response_item.nullifier.is_none() {
                    return Err(ValidationError::MissingNullifier(
                        response_item.identifier.clone(),
                    ));
                }
            }

            let expected_expires_at_min = request_item.effective_expires_at_min(self.created_at);
            if response_item.expires_at_min != expected_expires_at_min {
                return Err(ValidationError::ExpiresAtMinMismatch(
                    response_item.identifier.clone(),
                    expected_expires_at_min,
                    response_item.expires_at_min,
                ));
            }
        }

        match &self.constraints {
            // None => all requested credentials (via identifier) are required
            None => {
                for req in &self.requests {
                    if !provided.contains(req.identifier.as_str()) {
                        return Err(ValidationError::MissingCredential(req.identifier.clone()));
                    }
                }
                Ok(())
            }
            Some(expr) => {
                if !expr.validate_max_depth(2) {
                    return Err(ValidationError::ConstraintTooDeep);
                }
                if !expr.validate_max_nodes(MAX_CONSTRAINT_NODES) {
                    return Err(ValidationError::ConstraintTooLarge);
                }
                if expr.evaluate(&|t| provided.contains(t)) {
                    Ok(())
                } else {
                    Err(ValidationError::ConstraintNotSatisfied)
                }
            }
        }
    }

    /// Parse from JSON
    ///
    /// # Errors
    /// Returns an error if the JSON is invalid or contains duplicate issuer schema ids.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        let v: Self = serde_json::from_str(json)?;
        // Enforce unique issuer schema ids within a single request
        let mut seen: HashSet<String> = HashSet::new();
        for r in &v.requests {
            let t = r.issuer_schema_id.to_string();
            if !seen.insert(t.clone()) {
                return Err(serde_json::Error::custom(format!(
                    "duplicate issuer schema id: {t}"
                )));
            }
        }
        Ok(v)
    }

    /// Serialize to JSON
    ///
    /// # Errors
    /// Returns an error if serialization unexpectedly fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Serialize to pretty JSON
    ///
    /// # Errors
    /// Returns an error if serialization unexpectedly fails.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

impl ProofResponse {
    /// Parse from JSON
    ///
    /// # Errors
    /// Returns an error if the JSON does not match the expected response shape.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Serialize to pretty JSON
    ///
    /// # Errors
    /// Returns an error if serialization fails.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Return the list of successful `issuer_schema_id`s in the response.
    /// Returns an empty vec if the response has an error.
    #[must_use]
    pub fn successful_credentials(&self) -> Vec<u64> {
        if self.error.is_some() {
            return vec![];
        }
        self.responses.iter().map(|r| r.issuer_schema_id).collect()
    }
}

/// Validation errors when checking a response against a request
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ValidationError {
    /// The response `id` does not match the request `id`
    #[error("Request ID mismatch")]
    RequestIdMismatch,
    /// The response `version` does not match the request `version`
    #[error("Version mismatch")]
    VersionMismatch,
    /// The proof generation failed (response contains an error)
    #[error("Proof generation failed: {0}")]
    ProofGenerationFailed(String),
    /// A required credential was not provided
    #[error("Missing required credential: {0}")]
    MissingCredential(String),
    /// A credential was returned that was not requested.
    #[error("Unexpected credential in response: {0}")]
    UnexpectedCredential(String),
    /// A credential identifier was returned more than once.
    #[error("Duplicate credential in response: {0}")]
    DuplicateCredential(String),
    /// The provided credentials do not satisfy the request constraints
    #[error("Constraints not satisfied")]
    ConstraintNotSatisfied,
    /// The constraints expression exceeds the supported nesting depth
    #[error("Constraints nesting exceeds maximum allowed depth")]
    ConstraintTooDeep,
    /// The constraints expression exceeds the maximum allowed size/complexity
    #[error("Constraints exceed maximum allowed size")]
    ConstraintTooLarge,
    /// The `expires_at_min` value in the response does not match the expected value from the request
    #[error("Invalid expires_at_min for credential '{0}': expected {1}, got {2}")]
    ExpiresAtMinMismatch(String, u64, u64),
    /// Session ID doesn't match between request and response
    #[error("Session ID doesn't match between request and response")]
    SessionIdMismatch,
    /// Session nullifier missing for credential in session proof
    #[error("Session nullifier missing for credential: {0}")]
    MissingSessionNullifier(String),
    /// Nullifier missing for credential in uniqueness proof
    #[error("Nullifier missing for credential: {0}")]
    MissingNullifier(String),
}

// Helper selection functions for constraint evaluation
fn select_node<'a, F>(node: &'a ConstraintNode<'a>, pred: &F) -> Option<Vec<&'a str>>
where
    F: Fn(&str) -> bool,
{
    match node {
        ConstraintNode::Type(t) => pred(t.as_ref()).then(|| vec![t.as_ref()]),
        ConstraintNode::Expr(e) => select_expr(e, pred),
    }
}

fn select_expr<'a, F>(expr: &'a ConstraintExpr<'a>, pred: &F) -> Option<Vec<&'a str>>
where
    F: Fn(&str) -> bool,
{
    match expr {
        ConstraintExpr::All { all } => {
            let mut seen: std::collections::HashSet<&'a str> = std::collections::HashSet::new();
            let mut out: Vec<&'a str> = Vec::new();
            for n in all {
                let sub = select_node(n, pred)?;
                for s in sub {
                    if seen.insert(s) {
                        out.push(s);
                    }
                }
            }
            Some(out)
        }
        ConstraintExpr::Any { any } => any.iter().find_map(|n| select_node(n, pred)),
        ConstraintExpr::Enumerate { enumerate } => {
            // HashSet deduplicates identifiers, while Vec preserves first-seen output order.
            let mut seen: std::collections::HashSet<&'a str> = std::collections::HashSet::new();
            let mut selected: Vec<&'a str> = Vec::new();

            // Enumerate semantics: collect every satisfiable child; skip unsatisfied children.
            for child in enumerate {
                let Some(child_selection) = select_node(child, pred) else {
                    continue;
                };

                for identifier in child_selection {
                    if seen.insert(identifier) {
                        selected.push(identifier);
                    }
                }
            }

            if selected.is_empty() {
                None
            } else {
                Some(selected)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SessionNullifier;
    use alloy::{
        signers::{SignerSync, local::PrivateKeySigner},
        uint,
    };
    use k256::ecdsa::SigningKey;

    // Test helpers
    fn test_signature() -> alloy::signers::Signature {
        let signer =
            PrivateKeySigner::from_signing_key(SigningKey::from_bytes(&[1u8; 32].into()).unwrap());
        signer.sign_message_sync(b"test").expect("can sign")
    }

    fn test_nonce() -> FieldElement {
        FieldElement::from(1u64)
    }

    fn test_field_element(n: u64) -> FieldElement {
        FieldElement::from(n)
    }

    /// Creates an action with the required `0x02` session prefix
    fn test_action(n: u64) -> FieldElement {
        use ruint::{aliases::U256, uint};
        let v = U256::from(n)
            | uint!(0x0200000000000000000000000000000000000000000000000000000000000000_U256);
        FieldElement::try_from(v).expect("test value fits in field")
    }

    #[test]
    fn constraints_all_any_nested() {
        // Build a response that has test_req_1 and test_req_2 provided
        let response = ProofResponse {
            id: "req_123".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "test_req_1".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    test_field_element(1001).into(),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "test_req_2".into(),
                    2,
                    ZeroKnowledgeProof::default(),
                    test_field_element(1002).into(),
                    1_735_689_600,
                ),
            ],
        };

        // all: [test_req_1, any: [test_req_2, test_req_4]]
        let expr = ConstraintExpr::All {
            all: vec![
                ConstraintNode::Type("test_req_1".into()),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("test_req_2".into()),
                        ConstraintNode::Type("test_req_4".into()),
                    ],
                }),
            ],
        };

        assert!(response.constraints_satisfied(&expr));

        // all: [test_req_1, test_req_3] should fail because test_req_3 is not in response
        let fail_expr = ConstraintExpr::All {
            all: vec![
                ConstraintNode::Type("test_req_1".into()),
                ConstraintNode::Type("test_req_3".into()),
            ],
        };
        assert!(!response.constraints_satisfied(&fail_expr));
    }

    #[test]
    fn constraints_enumerate_partial_and_empty() {
        // Build a response that has orb and passport provided
        let response = ProofResponse {
            id: "req_123".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "passport".into(),
                    2,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    1_735_689_600,
                ),
            ],
        };

        // enumerate: [passport, national_id] should pass due to passport
        let expr = ConstraintExpr::Enumerate {
            enumerate: vec![
                ConstraintNode::Type("passport".into()),
                ConstraintNode::Type("national_id".into()),
            ],
        };
        assert!(response.constraints_satisfied(&expr));

        // enumerate: [national_id, document] should fail due to no matches
        let fail_expr = ConstraintExpr::Enumerate {
            enumerate: vec![
                ConstraintNode::Type("national_id".into()),
                ConstraintNode::Type("document".into()),
            ],
        };
        assert!(!response.constraints_satisfied(&fail_expr));
    }

    #[test]
    fn test_digest_hash() {
        let request = ProofRequest {
            id: "test_request".into(),
            version: RequestVersion::V1,
            created_at: 1_700_000_000,
            expires_at: 1_700_100_000,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(FieldElement::ZERO),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: Some("test_signal".into()),
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        let digest1 = request.digest_hash().unwrap();
        // Verify it returns a 32-byte hash
        assert_eq!(digest1.len(), 32);

        // Verify deterministic: same request produces same hash
        let digest2 = request.digest_hash().unwrap();
        assert_eq!(digest1, digest2);

        // Verify different request nonces produce different hashes
        let request2 = ProofRequest {
            nonce: test_field_element(3),
            ..request
        };
        let digest3 = request2.digest_hash().unwrap();
        assert_ne!(digest1, digest3);
    }

    #[test]
    fn proof_request_signature_serializes_as_hex_string() {
        let request = ProofRequest {
            id: "test".into(),
            version: RequestVersion::V1,
            created_at: 1_700_000_000,
            expires_at: 1_700_100_000,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: None,
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        let json = request.to_json().unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let sig = value["signature"]
            .as_str()
            .expect("signature should be a string");
        assert!(sig.starts_with("0x"));
        assert_eq!(sig.len(), 132);

        let roundtripped = ProofRequest::from_json(&json).unwrap();
        assert_eq!(roundtripped.signature, request.signature);
    }

    #[test]
    fn request_validate_response_none_constraints_means_all() {
        let request = ProofRequest {
            id: "req_1".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600, // 2025-01-01
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(FieldElement::ZERO),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: 1,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "document".into(),
                    issuer_schema_id: 2,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: None,
        };

        let ok = ProofResponse {
            id: "req_1".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "document".into(),
                    2,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    1_735_689_600,
                ),
            ],
        };
        assert!(request.validate_response(&ok).is_ok());

        let missing = ProofResponse {
            id: "req_1".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "orb".into(),
                1,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(1001)),
                1_735_689_600,
            )],
        };
        let err = request.validate_response(&missing).unwrap_err();
        assert!(matches!(err, ValidationError::MissingCredential(_)));

        let unexpected = ProofResponse {
            id: "req_1".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "document".into(),
                    2,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "passport".into(),
                    3,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1003)),
                    1_735_689_600,
                ),
            ],
        };
        let err = request.validate_response(&unexpected).unwrap_err();
        assert!(matches!(
            err,
            ValidationError::UnexpectedCredential(ref id) if id == "passport"
        ));

        let duplicate = ProofResponse {
            id: "req_1".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_735_689_600,
                ),
            ],
        };
        let err = request.validate_response(&duplicate).unwrap_err();
        assert!(matches!(
            err,
            ValidationError::DuplicateCredential(ref id) if id == "orb"
        ));
    }

    #[test]
    fn constraint_depth_enforced() {
        // Root all -> nested any -> nested all (depth 3) should be rejected
        let deep = ConstraintExpr::All {
            all: vec![ConstraintNode::Expr(ConstraintExpr::Any {
                any: vec![ConstraintNode::Expr(ConstraintExpr::All {
                    all: vec![ConstraintNode::Type("orb".into())],
                })],
            })],
        };

        let request = ProofRequest {
            id: "req_2".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: Some(deep),
        };

        let response = ProofResponse {
            id: "req_2".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "orb".into(),
                1,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(1001)),
                1_735_689_600,
            )],
        };

        let err = request.validate_response(&response).unwrap_err();
        assert!(matches!(err, ValidationError::ConstraintTooDeep));
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn constraint_node_limit_boundary_passes() {
        // Root All with: 1 Type + Any(4) + Any(4)
        // Node count = root(1) + type(1) + any(1+4) + any(1+4) = 12

        let expr = ConstraintExpr::All {
            all: vec![
                ConstraintNode::Type("test_req_10".into()),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("test_req_11".into()),
                        ConstraintNode::Type("test_req_12".into()),
                        ConstraintNode::Type("test_req_13".into()),
                        ConstraintNode::Type("test_req_14".into()),
                    ],
                }),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("test_req_15".into()),
                        ConstraintNode::Type("test_req_16".into()),
                        ConstraintNode::Type("test_req_17".into()),
                        ConstraintNode::Type("test_req_18".into()),
                    ],
                }),
            ],
        };

        let request = ProofRequest {
            id: "req_nodes_ok".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(5)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "test_req_10".into(),
                    issuer_schema_id: 10,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_11".into(),
                    issuer_schema_id: 11,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_12".into(),
                    issuer_schema_id: 12,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_13".into(),
                    issuer_schema_id: 13,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_14".into(),
                    issuer_schema_id: 14,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_15".into(),
                    issuer_schema_id: 15,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_16".into(),
                    issuer_schema_id: 16,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_17".into(),
                    issuer_schema_id: 17,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_18".into(),
                    issuer_schema_id: 18,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(expr),
        };

        // Provide just enough to satisfy both any-groups and the single type
        let response = ProofResponse {
            id: "req_nodes_ok".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "test_req_10".into(),
                    10,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1010)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "test_req_11".into(),
                    11,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1011)),
                    1_735_689_600,
                ),
                ResponseItem::new_uniqueness(
                    "test_req_15".into(),
                    15,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1015)),
                    1_735_689_600,
                ),
            ],
        };

        // Should not exceed size and should validate OK
        assert!(request.validate_response(&response).is_ok());
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn constraint_node_limit_exceeded_fails() {
        // Root All with: 1 Type + Any(4) + Any(5)
        // Node count = root(1) + type(1) + any(1+4) + any(1+5) = 13 (> 12)
        let expr = ConstraintExpr::All {
            all: vec![
                ConstraintNode::Type("t0".into()),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("t1".into()),
                        ConstraintNode::Type("t2".into()),
                        ConstraintNode::Type("t3".into()),
                        ConstraintNode::Type("t4".into()),
                    ],
                }),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("t5".into()),
                        ConstraintNode::Type("t6".into()),
                        ConstraintNode::Type("t7".into()),
                        ConstraintNode::Type("t8".into()),
                        ConstraintNode::Type("t9".into()),
                    ],
                }),
            ],
        };

        let request = ProofRequest {
            id: "req_nodes_too_many".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "test_req_20".into(),
                    issuer_schema_id: 20,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_21".into(),
                    issuer_schema_id: 21,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_22".into(),
                    issuer_schema_id: 22,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_23".into(),
                    issuer_schema_id: 23,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_24".into(),
                    issuer_schema_id: 24,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_25".into(),
                    issuer_schema_id: 25,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_26".into(),
                    issuer_schema_id: 26,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_27".into(),
                    issuer_schema_id: 27,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_28".into(),
                    issuer_schema_id: 28,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_29".into(),
                    issuer_schema_id: 29,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(expr),
        };

        // Response content is irrelevant; validation should fail before evaluation due to size
        let response = ProofResponse {
            id: "req_nodes_too_many".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "test_req_20".into(),
                20,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(1020)),
                1_735_689_600,
            )],
        };

        let err = request.validate_response(&response).unwrap_err();
        assert!(matches!(err, ValidationError::ConstraintTooLarge));
    }

    #[test]
    fn request_single_credential_parse_and_validate() {
        let req = ProofRequest {
            id: "req_18c0f7f03e7d".into(),
            version: RequestVersion::V1,
            created_at: 1_725_381_192,
            expires_at: 1_725_381_492,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: Some(SessionId::default()),
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "test_req_1".into(),
                issuer_schema_id: 1,
                signal: Some("abcd-efgh-ijkl".into()),
                genesis_issued_at_min: Some(1_725_381_192),
                expires_at_min: None,
            }],
            constraints: None,
        };

        assert_eq!(req.id, "req_18c0f7f03e7d");
        assert_eq!(req.requests.len(), 1);

        // Build matching successful response (session proof requires session_id and session_nullifier)
        let resp = ProofResponse {
            id: req.id.clone(),
            version: RequestVersion::V1,
            session_id: Some(SessionId::default()),
            error: None,
            responses: vec![ResponseItem::new_session(
                "test_req_1".into(),
                1,
                ZeroKnowledgeProof::default(),
                SessionNullifier::new(test_field_element(1001), test_action(1)).unwrap(),
                1_725_381_192,
            )],
        };
        assert!(req.validate_response(&resp).is_ok());
    }

    #[test]
    fn request_multiple_credentials_all_constraint_and_missing() {
        let req = ProofRequest {
            id: "req_18c0f7f03e7d".into(),
            version: RequestVersion::V1,
            created_at: 1_725_381_192,
            expires_at: 1_725_381_492,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "test_req_1".into(),
                    issuer_schema_id: 1,
                    signal: Some("abcd-efgh-ijkl".into()),
                    genesis_issued_at_min: Some(1_725_381_192),
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_2".into(),
                    issuer_schema_id: 2,
                    signal: Some("abcd-efgh-ijkl".into()),
                    genesis_issued_at_min: Some(1_725_381_192),
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::All {
                all: vec![
                    ConstraintNode::Type("test_req_1".into()),
                    ConstraintNode::Type("test_req_2".into()),
                ],
            }),
        };

        // Build response that fails constraints (test_req_1 is missing)
        let resp = ProofResponse {
            id: req.id.clone(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "test_req_2".into(),
                2,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(1001)),
                1_725_381_192,
            )],
        };

        let err = req.validate_response(&resp).unwrap_err();
        assert!(matches!(err, ValidationError::ConstraintNotSatisfied));
    }

    #[test]
    fn request_more_complex_constraints_nested_success() {
        let req = ProofRequest {
            id: "req_18c0f7f03e7d".into(),
            version: RequestVersion::V1,
            created_at: 1_725_381_192,
            expires_at: 1_725_381_492,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "test_req_1".into(),
                    issuer_schema_id: 1,
                    signal: Some("abcd-efgh-ijkl".into()),
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_2".into(),
                    issuer_schema_id: 2,
                    signal: Some("mnop-qrst-uvwx".into()),
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_3".into(),
                    issuer_schema_id: 3,
                    signal: Some("abcd-efgh-ijkl".into()),
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::All {
                all: vec![
                    ConstraintNode::Type("test_req_3".into()),
                    ConstraintNode::Expr(ConstraintExpr::Any {
                        any: vec![
                            ConstraintNode::Type("test_req_1".into()),
                            ConstraintNode::Type("test_req_2".into()),
                        ],
                    }),
                ],
            }),
        };

        // Satisfy nested any with 0x1 + 0x3
        let resp = ProofResponse {
            id: req.id.clone(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "test_req_3".into(),
                    3,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    1_725_381_192,
                ),
                ResponseItem::new_uniqueness(
                    "test_req_1".into(),
                    1,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    1_725_381_192,
                ),
            ],
        };

        assert!(req.validate_response(&resp).is_ok());
    }

    #[test]
    fn request_validate_response_with_enumerate() {
        let req = ProofRequest {
            id: "req_enum".into(),
            version: RequestVersion::V1,
            created_at: 1_725_381_192,
            expires_at: 1_725_381_492,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "passport".into(),
                    issuer_schema_id: 2,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "national_id".into(),
                    issuer_schema_id: 3,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::Enumerate {
                enumerate: vec![
                    ConstraintNode::Type("passport".into()),
                    ConstraintNode::Type("national_id".into()),
                ],
            }),
        };

        // Satisfies enumerate with passport
        let ok_resp = ProofResponse {
            id: req.id.clone(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "passport".into(),
                2,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(2002)),
                1_725_381_192,
            )],
        };
        assert!(req.validate_response(&ok_resp).is_ok());

        // Fails enumerate because none of the enumerate candidates are present
        let fail_resp = ProofResponse {
            id: req.id.clone(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![],
        };
        let err = req.validate_response(&fail_resp).unwrap_err();
        assert!(matches!(err, ValidationError::ConstraintNotSatisfied));
    }

    #[test]
    fn request_json_parse() {
        // Happy path with signal present
        let with_signal = r#"{
  "id": "req_abc123",
  "version": 1,
  "created_at": 1725381192,
  "expires_at": 1725381492,
  "rp_id": "rp_0000000000000001",
  "oprf_key_id": "0x1",
  "session_id": null,
  "action": "0x000000000000000000000000000000000000000000000000000000000000002a",
  "signature": "0xa1fd06f0d8ceb541f6096fe2e865063eac1ff085c9d2bac2eedcc9ed03804bfc18d956b38c5ac3a8f7e71fde43deff3bda254d369c699f3c7a3f8e6b8477a5f51c",
  "nonce": "0x0000000000000000000000000000000000000000000000000000000000000001",
  "proof_requests": [
    {
      "identifier": "orb",
      "issuer_schema_id": 1,
      "signal": "0xdeadbeef",
      "genesis_issued_at_min": 1725381192,
      "expires_at_min": 1725381492
    }
  ]
}"#;

        let req = ProofRequest::from_json(with_signal).expect("parse with signal");
        assert_eq!(req.id, "req_abc123");
        assert_eq!(req.requests.len(), 1);
        assert_eq!(req.requests[0].signal, Some(b"\xde\xad\xbe\xef".to_vec()));
        assert_eq!(req.requests[0].genesis_issued_at_min, Some(1_725_381_192));
        assert_eq!(req.requests[0].expires_at_min, Some(1_725_381_492));

        let without_signal = r#"{
  "id": "req_abc123",
  "version": 1,
  "created_at": 1725381192,
  "expires_at": 1725381492,
  "rp_id": "rp_0000000000000001",
  "oprf_key_id": "0x1",
  "session_id": null,
  "action": "0x000000000000000000000000000000000000000000000000000000000000002a",
  "signature": "0xa1fd06f0d8ceb541f6096fe2e865063eac1ff085c9d2bac2eedcc9ed03804bfc18d956b38c5ac3a8f7e71fde43deff3bda254d369c699f3c7a3f8e6b8477a5f51c",
  "nonce": "0x0000000000000000000000000000000000000000000000000000000000000001",
  "proof_requests": [
    {
      "identifier": "orb",
      "issuer_schema_id": 1
    }
  ]
}"#;

        let req = ProofRequest::from_json(without_signal).expect("parse without signal");
        assert!(req.requests[0].signal.is_none());
        assert_eq!(req.requests[0].signal_hash(), FieldElement::ZERO);
    }

    #[test]
    fn response_json_parse() {
        // Success OK - Uniqueness nullifier (simple FieldElement)
        let ok_json = r#"{
  "id": "req_18c0f7f03e7d",
  "version": 1,
  "responses": [
    {
      "identifier": "orb",
      "issuer_schema_id": 100,
      "proof": "00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000",
      "nullifier": "nil_00000000000000000000000000000000000000000000000000000000000003e9",
      "expires_at_min": 1725381192
    }
  ]
}"#;

        let ok = ProofResponse::from_json(ok_json).unwrap();
        assert_eq!(ok.successful_credentials(), vec![100]);
        assert!(ok.responses[0].is_uniqueness());

        // Canonical session nullifier representation (prefixed hex bytes).
        let canonical_session_nullifier = serde_json::to_string(
            &SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap(),
        )
        .unwrap();
        let sess_json_canonical = format!(
            r#"{{
  "id": "req_18c0f7f03e7d",
  "version": 1,
  "session_id": "session_00000000000000000000000000000000000000000000000000000000000003ea0100000000000000000000000000000000000000000000000000000000000001",
  "responses": [
    {{
      "identifier": "orb",
      "issuer_schema_id": 100,
      "proof": "00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000",
      "session_nullifier": {canonical_session_nullifier},
      "expires_at_min": 1725381192
    }}
  ]
}}"#
        );
        let sess_canonical = ProofResponse::from_json(&sess_json_canonical).unwrap();
        assert_eq!(sess_canonical.successful_credentials(), vec![100]);
        assert!(sess_canonical.responses[0].is_session());
        assert_eq!(
            sess_canonical.session_id.unwrap().oprf_seed.to_u256(),
            uint!(0x0100000000000000000000000000000000000000000000000000000000000001_U256)
        );
    }
    /// Test duplicate detection by creating a serialized `ProofRequest` with duplicates
    /// and then trying to parse it with `from_json` which should detect the duplicates
    #[test]
    fn request_rejects_duplicate_issuer_schema_ids_on_parse() {
        let req = ProofRequest {
            id: "req_dup".into(),
            version: RequestVersion::V1,
            created_at: 1_725_381_192,
            expires_at: 1_725_381_492,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(5)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "test_req_1".into(),
                    issuer_schema_id: 1,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "test_req_2".into(),
                    issuer_schema_id: 1, // Duplicate!
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: None,
        };

        // Serialize then deserialize to trigger the duplicate check in from_json
        let json = req.to_json().unwrap();
        let err = ProofRequest::from_json(&json).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate issuer schema id"),
            "Expected error message to contain 'duplicate issuer schema id', got: {msg}"
        );
    }

    #[test]
    fn response_with_error_has_empty_responses_and_fails_validation() {
        let request = ProofRequest {
            id: "req_error".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(FieldElement::ZERO),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        // Response with error should have empty responses array
        let error_response = ProofResponse {
            id: "req_error".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: Some("credential_not_available".into()),
            responses: vec![], // Empty when error is present
        };

        // Validation should fail with ProofGenerationFailed
        let err = request.validate_response(&error_response).unwrap_err();
        assert!(matches!(err, ValidationError::ProofGenerationFailed(_)));
        if let ValidationError::ProofGenerationFailed(msg) = err {
            assert_eq!(msg, "credential_not_available");
        }

        // successful_credentials should return empty vec when error is present
        assert_eq!(error_response.successful_credentials(), Vec::<u64>::new());

        // constraints_satisfied should return false when error is present
        let expr = ConstraintExpr::All {
            all: vec![ConstraintNode::Type("orb".into())],
        };
        assert!(!error_response.constraints_satisfied(&expr));
    }

    #[test]
    fn response_error_json_parse() {
        // Error response JSON
        let error_json = r#"{
  "id": "req_error",
  "version": 1,
  "error": "credential_not_available",
  "responses": []
}"#;

        let error_resp = ProofResponse::from_json(error_json).unwrap();
        assert_eq!(error_resp.error, Some("credential_not_available".into()));
        assert_eq!(error_resp.responses.len(), 0);
        assert_eq!(error_resp.successful_credentials(), Vec::<u64>::new());
    }

    #[test]
    fn credentials_to_prove_none_constraints_requires_all_and_drops_if_missing() {
        let req = ProofRequest {
            id: "req".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600, // 2025-01-01 00:00:00 UTC
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(5)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: 100,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "passport".into(),
                    issuer_schema_id: 101,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: None,
        };

        let available_ok: HashSet<u64> = [100, 101].into_iter().collect();
        let sel_ok = req.credentials_to_prove(&available_ok).unwrap();
        assert_eq!(sel_ok.len(), 2);
        assert_eq!(sel_ok[0].issuer_schema_id, 100);
        assert_eq!(sel_ok[1].issuer_schema_id, 101);

        let available_missing: HashSet<u64> = std::iter::once(100).collect();
        assert!(req.credentials_to_prove(&available_missing).is_none());
    }

    #[test]
    fn credentials_to_prove_with_constraints_all_and_any() {
        // proof_requests: orb, passport, national-id
        let orb_id = 100;
        let passport_id = 101;
        let national_id = 102;

        let req = ProofRequest {
            id: "req".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600, // 2025-01-01 00:00:00 UTC
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: orb_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "passport".into(),
                    issuer_schema_id: passport_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "national_id".into(),
                    issuer_schema_id: national_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::All {
                all: vec![
                    ConstraintNode::Type("orb".into()),
                    ConstraintNode::Expr(ConstraintExpr::Any {
                        any: vec![
                            ConstraintNode::Type("passport".into()),
                            ConstraintNode::Type("national_id".into()),
                        ],
                    }),
                ],
            }),
        };

        // Available has orb + passport → should pick [orb, passport]
        let available1: HashSet<u64> = [orb_id, passport_id].into_iter().collect();
        let sel1 = req.credentials_to_prove(&available1).unwrap();
        assert_eq!(sel1.len(), 2);
        assert_eq!(sel1[0].issuer_schema_id, orb_id);
        assert_eq!(sel1[1].issuer_schema_id, passport_id);

        // Available has orb + national-id → should pick [orb, national-id]
        let available2: HashSet<u64> = [orb_id, national_id].into_iter().collect();
        let sel2 = req.credentials_to_prove(&available2).unwrap();
        assert_eq!(sel2.len(), 2);
        assert_eq!(sel2[0].issuer_schema_id, orb_id);
        assert_eq!(sel2[1].issuer_schema_id, national_id);

        // Missing orb → cannot satisfy "all" → None
        let available3: HashSet<u64> = std::iter::once(passport_id).collect();
        assert!(req.credentials_to_prove(&available3).is_none());
    }

    #[test]
    fn credentials_to_prove_with_constraints_enumerate() {
        let orb_id = 100;
        let passport_id = 101;
        let national_id = 102;

        let req = ProofRequest {
            id: "req".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: orb_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "passport".into(),
                    issuer_schema_id: passport_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "national_id".into(),
                    issuer_schema_id: national_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::Enumerate {
                enumerate: vec![
                    ConstraintNode::Type("passport".into()),
                    ConstraintNode::Type("national_id".into()),
                ],
            }),
        };

        // One of enumerate candidates available -> one selected
        let available1: HashSet<u64> = [orb_id, passport_id].into_iter().collect();
        let sel1 = req.credentials_to_prove(&available1).unwrap();
        assert_eq!(sel1.len(), 1);
        assert_eq!(sel1[0].issuer_schema_id, passport_id);

        // Both enumerate candidates available -> both selected in request order
        let available2: HashSet<u64> = [orb_id, passport_id, national_id].into_iter().collect();
        let sel2 = req.credentials_to_prove(&available2).unwrap();
        assert_eq!(sel2.len(), 2);
        assert_eq!(sel2[0].issuer_schema_id, passport_id);
        assert_eq!(sel2[1].issuer_schema_id, national_id);

        // None of enumerate candidates available -> cannot satisfy
        let available3: HashSet<u64> = std::iter::once(orb_id).collect();
        assert!(req.credentials_to_prove(&available3).is_none());
    }

    #[test]
    fn credentials_to_prove_with_constraints_all_and_enumerate() {
        let orb_id = 100;
        let passport_id = 101;
        let national_id = 102;

        let req = ProofRequest {
            id: "req".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_600,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: orb_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "passport".into(),
                    issuer_schema_id: passport_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
                RequestItem {
                    identifier: "national_id".into(),
                    issuer_schema_id: national_id,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None,
                },
            ],
            constraints: Some(ConstraintExpr::All {
                all: vec![
                    ConstraintNode::Type("orb".into()),
                    ConstraintNode::Expr(ConstraintExpr::Enumerate {
                        enumerate: vec![
                            ConstraintNode::Type("passport".into()),
                            ConstraintNode::Type("national_id".into()),
                        ],
                    }),
                ],
            }),
        };

        // orb + passport -> select both
        let available1: HashSet<u64> = [orb_id, passport_id].into_iter().collect();
        let sel1 = req.credentials_to_prove(&available1).unwrap();
        assert_eq!(sel1.len(), 2);
        assert_eq!(sel1[0].issuer_schema_id, orb_id);
        assert_eq!(sel1[1].issuer_schema_id, passport_id);

        // orb + passport + national_id -> select all three
        let available2: HashSet<u64> = [orb_id, passport_id, national_id].into_iter().collect();
        let sel2 = req.credentials_to_prove(&available2).unwrap();
        assert_eq!(sel2.len(), 3);
        assert_eq!(sel2[0].issuer_schema_id, orb_id);
        assert_eq!(sel2[1].issuer_schema_id, passport_id);
        assert_eq!(sel2[2].issuer_schema_id, national_id);

        // orb alone -> enumerate branch unsatisfied
        let available3: HashSet<u64> = std::iter::once(orb_id).collect();
        assert!(req.credentials_to_prove(&available3).is_none());
    }

    #[test]
    fn request_item_effective_expires_at_min_defaults_to_created_at() {
        let request_created_at = 1_735_689_600; // 2025-01-01 00:00:00 UTC
        let custom_expires_at = 1_735_862_400; // 2025-01-03 00:00:00 UTC

        // When expires_at_min is None, should use request_created_at
        let item_with_none = RequestItem {
            identifier: "test".into(),
            issuer_schema_id: 100,
            signal: None,
            genesis_issued_at_min: None,
            expires_at_min: None,
        };
        assert_eq!(
            item_with_none.effective_expires_at_min(request_created_at),
            request_created_at,
            "When expires_at_min is None, should default to request created_at"
        );

        // When expires_at_min is Some, should use that value
        let item_with_custom = RequestItem {
            identifier: "test".into(),
            issuer_schema_id: 100,
            signal: None,
            genesis_issued_at_min: None,
            expires_at_min: Some(custom_expires_at),
        };
        assert_eq!(
            item_with_custom.effective_expires_at_min(request_created_at),
            custom_expires_at,
            "When expires_at_min is Some, should use that explicit value"
        );
    }

    #[test]
    fn validate_response_checks_expires_at_min_matches() {
        let request_created_at = 1_735_689_600; // 2025-01-01 00:00:00 UTC
        let custom_expires_at = 1_735_862_400; // 2025-01-03 00:00:00 UTC

        // Request with one item that has no explicit expires_at_min (defaults to created_at)
        // and one with an explicit expires_at_min
        let request = ProofRequest {
            id: "req_expires_test".into(),
            version: RequestVersion::V1,
            created_at: request_created_at,
            expires_at: request_created_at + 300,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None,
            action: Some(test_field_element(1)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![
                RequestItem {
                    identifier: "orb".into(),
                    issuer_schema_id: 100,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: None, // Should default to request_created_at
                },
                RequestItem {
                    identifier: "document".into(),
                    issuer_schema_id: 101,
                    signal: None,
                    genesis_issued_at_min: None,
                    expires_at_min: Some(custom_expires_at), // Explicit value
                },
            ],
            constraints: None,
        };

        // Valid response with matching expires_at_min values
        let valid_response = ProofResponse {
            id: "req_expires_test".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    100,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    request_created_at, // Matches default
                ),
                ResponseItem::new_uniqueness(
                    "document".into(),
                    101,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    custom_expires_at, // Matches explicit value
                ),
            ],
        };
        assert!(request.validate_response(&valid_response).is_ok());

        // Invalid response with mismatched expires_at_min for first item
        let invalid_response_1 = ProofResponse {
            id: "req_expires_test".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    100,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    custom_expires_at, // Wrong! Should be request_created_at
                ),
                ResponseItem::new_uniqueness(
                    "document".into(),
                    101,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    custom_expires_at,
                ),
            ],
        };
        let err1 = request.validate_response(&invalid_response_1).unwrap_err();
        assert!(matches!(
            err1,
            ValidationError::ExpiresAtMinMismatch(_, _, _)
        ));
        if let ValidationError::ExpiresAtMinMismatch(identifier, expected, got) = err1 {
            assert_eq!(identifier, "orb");
            assert_eq!(expected, request_created_at);
            assert_eq!(got, custom_expires_at);
        }

        // Invalid response with mismatched expires_at_min for second item
        let invalid_response_2 = ProofResponse {
            id: "req_expires_test".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![
                ResponseItem::new_uniqueness(
                    "orb".into(),
                    100,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1001)),
                    request_created_at,
                ),
                ResponseItem::new_uniqueness(
                    "document".into(),
                    101,
                    ZeroKnowledgeProof::default(),
                    Nullifier::from(test_field_element(1002)),
                    request_created_at, // Wrong! Should be custom_expires_at
                ),
            ],
        };
        let err2 = request.validate_response(&invalid_response_2).unwrap_err();
        assert!(matches!(
            err2,
            ValidationError::ExpiresAtMinMismatch(_, _, _)
        ));
        if let ValidationError::ExpiresAtMinMismatch(identifier, expected, got) = err2 {
            assert_eq!(identifier, "document");
            assert_eq!(expected, custom_expires_at);
            assert_eq!(got, request_created_at);
        }
    }

    #[test]
    fn test_validate_response_requires_session_id_in_response() {
        // Request with session_id should require response to also have session_id
        let request = ProofRequest {
            id: "req_session".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_900,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: Some(SessionId::default()), // Session proof
            action: Some(test_field_element(42)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        // Response without session_id should fail validation
        let response_missing_session_id = ProofResponse {
            id: "req_session".into(),
            version: RequestVersion::V1,
            session_id: None, // Missing!
            error: None,
            responses: vec![ResponseItem::new_session(
                "orb".into(),
                1,
                ZeroKnowledgeProof::default(),
                SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap(),
                1_735_689_600,
            )],
        };

        let err = request
            .validate_response(&response_missing_session_id)
            .unwrap_err();
        assert!(matches!(err, ValidationError::SessionIdMismatch));
    }

    #[test]
    fn test_validate_response_requires_session_nullifier_for_session_proof() {
        // Request with session_id requires session_nullifier in each response item
        let request = ProofRequest {
            id: "req_session".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_900,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: Some(SessionId::default()), // Session proof
            action: Some(test_field_element(42)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        // Response with uniqueness nullifier instead of session nullifier should fail
        let response_wrong_nullifier_type = ProofResponse {
            id: "req_session".into(),
            version: RequestVersion::V1,
            session_id: Some(SessionId::default()),
            error: None,
            responses: vec![ResponseItem::new_uniqueness(
                "orb".into(),
                1,
                ZeroKnowledgeProof::default(),
                Nullifier::from(test_field_element(1001)), // Using uniqueness nullifier instead of session!
                1_735_689_600,
            )],
        };

        let err = request
            .validate_response(&response_wrong_nullifier_type)
            .unwrap_err();
        assert!(matches!(
            err,
            ValidationError::MissingSessionNullifier(ref id) if id == "orb"
        ));
    }

    #[test]
    fn test_validate_response_requires_nullifier_for_uniqueness_proof() {
        // Request without session_id requires nullifier in each response item
        let request = ProofRequest {
            id: "req_uniqueness".into(),
            version: RequestVersion::V1,
            created_at: 1_735_689_600,
            expires_at: 1_735_689_900,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(uint!(1_U160)),
            session_id: None, // Uniqueness proof
            action: Some(test_field_element(42)),
            signature: test_signature(),
            nonce: test_nonce(),
            requests: vec![RequestItem {
                identifier: "orb".into(),
                issuer_schema_id: 1,
                signal: None,
                genesis_issued_at_min: None,
                expires_at_min: None,
            }],
            constraints: None,
        };

        // Response with session nullifier instead of uniqueness nullifier should fail
        let response_wrong_nullifier_type = ProofResponse {
            id: "req_uniqueness".into(),
            version: RequestVersion::V1,
            session_id: None,
            error: None,
            responses: vec![ResponseItem::new_session(
                "orb".into(),
                1,
                ZeroKnowledgeProof::default(),
                SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap(), // Using session nullifier instead of uniqueness!
                1_735_689_600,
            )],
        };

        let err = request
            .validate_response(&response_wrong_nullifier_type)
            .unwrap_err();
        assert!(matches!(
            err,
            ValidationError::MissingNullifier(ref id) if id == "orb"
        ));
    }
}