affinidi-data-integrity 0.7.2

W3C Data Integrity Implementation
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
/*!
 * W3C `bbs-2023` transformation primitives (RDF-canonical, interoperable).
 *
 * This is the standards-track replacement for the affinidi-internal statement
 * encoding in [`crate::bbs_2023`]. It implements the
 * [W3C vc-di-bbs](https://www.w3.org/TR/vc-di-bbs/) `bbs-2023` cryptosuite over
 * the conformant RDFC-1.0 canonicalizer in `affinidi-rdf-encoding`.
 *
 * Every step is pinned byte-for-byte against the official `w3c/vc-di-bbs`
 * `TestVectors/` (see the KATs at the bottom). All three roles are implemented
 * and interoperate with the reference implementation end-to-end:
 *
 * - [`create_base_proof_value`] (issuer) — `proofHash`, the HMAC blank-node
 *   label map ([`hmac_canonicalize`]), mandatory/non-mandatory grouping
 *   ([`canonicalize_and_group`]), BBS sign, and the CBOR base `proofValue`
 *   (`0xd95d02`). Matches the W3C base proof exactly.
 * - [`create_derived_proof`] (holder) — selective disclosure: combined
 *   grouping, BBS `proof_gen`, the reveal label map, and the CBOR derived
 *   `proofValue` (`0xd95d03`).
 * - [`verify_derived_proof`] (verifier) — relabel + recompute hashes + BBS
 *   `proof_verify`; accepts the reference derived proof byte-for-byte.
 *
 * Grouping uses the vc-di-ecdsa `selectJsonLd` / `parsePointer` / skolemize
 * algorithms; skolem labels are self-consistent (grouping matches by statement
 * content), so they never leak into the output.
 */

use std::collections::{BTreeMap, BTreeSet};

use affinidi_bbs as bbs;
use affinidi_rdf_encoding::jsonld::context::Context as JsonLdContext;
use affinidi_rdf_encoding::{jsonld, nquads, rdfc1};
use hmac::{Hmac, Mac};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::DataIntegrityError;

type HmacSha256 = Hmac<Sha256>;

/// Skolemization URN prefix (vc-di-ecdsa).
const URN_BNID: &str = "urn:bnid:";

/// CBOR prefix bytes for a `bbs-2023` **base** proof value.
const CBOR_PREFIX_BASE: [u8; 3] = [0xd9, 0x5d, 0x02];

/// Produce a `bbs-2023` **base proof** value (issuer side), per W3C vc-di-bbs.
///
/// Computes `proofHash`, groups statements by `mandatory_pointers`, signs the
/// non-mandatory statements with BBS (header = `proofHash || mandatoryHash`),
/// and serializes the multibase CBOR `proofValue`.
pub fn create_base_proof_value(
    document: &Value,
    proof_config: &Value,
    mandatory_pointers: &[&str],
    sk: &bbs::SecretKey,
    pk: &bbs::PublicKey,
    hmac_key: &[u8],
) -> Result<String, DataIntegrityError> {
    let proof_hash = proof_hash(proof_config)?;
    let grouped = canonicalize_and_group(document, mandatory_pointers, hmac_key)?;

    let mut bbs_header = proof_hash.to_vec();
    bbs_header.extend_from_slice(&grouped.mandatory_hash);

    let non_mandatory = grouped.non_mandatory();
    let messages: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();
    let signature =
        bbs::sign(sk, pk, &bbs_header, &messages).map_err(DataIntegrityError::signing)?;

    serialize_base_proof_value(
        &signature.to_bytes(),
        &bbs_header,
        &pk.to_bytes(),
        hmac_key,
        mandatory_pointers,
    )
}

/// Sign a VC document with a `bbs-2023` **base proof** (issuer side, document
/// API). Builds the proof configuration, signs, and returns the document with a
/// `proof` (cryptosuite `bbs-2023`). `created` is an ISO-8601 timestamp.
///
/// `hmac_key` is a per-credential secret (32 random bytes) that the holder needs
/// to derive presentations; it is carried inside the base `proofValue`.
#[allow(clippy::too_many_arguments)]
pub fn sign_base_document(
    document: &Value,
    mandatory_pointers: &[&str],
    verification_method: &str,
    created: &str,
    sk: &bbs::SecretKey,
    pk: &bbs::PublicKey,
    hmac_key: &[u8],
) -> Result<Value, DataIntegrityError> {
    let conformance = |m: &str| DataIntegrityError::Conformance(m.to_string());
    let context = document
        .get("@context")
        .cloned()
        .ok_or_else(|| conformance("document must have an @context"))?;

    // The proof config (for hashing) carries the document's @context; the proof
    // object attached to the document does NOT (it is re-added at verify time).
    let proof_config = serde_json::json!({
        "type": "DataIntegrityProof",
        "cryptosuite": "bbs-2023",
        "created": created,
        "verificationMethod": verification_method,
        "proofPurpose": "assertionMethod",
        "@context": context,
    });
    let proof_value = create_base_proof_value(
        document,
        &proof_config,
        mandatory_pointers,
        sk,
        pk,
        hmac_key,
    )?;

    let mut proof = proof_config;
    let obj = proof.as_object_mut().expect("proof config is an object");
    obj.remove("@context");
    obj.insert("proofValue".to_string(), Value::String(proof_value));

    let mut base = document.clone();
    base.as_object_mut()
        .ok_or_else(|| conformance("document must be an object"))?
        .insert("proof".to_string(), proof);
    Ok(base)
}

/// `serializeBaseProofValue`: `multibase-base64url-no-pad("u" + 0xd95d02 +
/// CBOR([bbsSignature, bbsHeader, publicKey, hmacKey, mandatoryPointers]))`.
pub fn serialize_base_proof_value(
    bbs_signature: &[u8],
    bbs_header: &[u8],
    public_key: &[u8],
    hmac_key: &[u8],
    mandatory_pointers: &[&str],
) -> Result<String, DataIntegrityError> {
    let components = ciborium::Value::Array(vec![
        ciborium::Value::Bytes(bbs_signature.to_vec()),
        ciborium::Value::Bytes(bbs_header.to_vec()),
        ciborium::Value::Bytes(public_key.to_vec()),
        ciborium::Value::Bytes(hmac_key.to_vec()),
        ciborium::Value::Array(
            mandatory_pointers
                .iter()
                .map(|p| ciborium::Value::Text((*p).to_string()))
                .collect(),
        ),
    ]);

    let mut buf = CBOR_PREFIX_BASE.to_vec();
    ciborium::into_writer(&components, &mut buf)
        .map_err(|e| DataIntegrityError::MalformedProof(format!("CBOR encode: {e}")))?;
    Ok(multibase::encode(multibase::Base::Base64Url, &buf))
}

/// CBOR prefix bytes for a `bbs-2023` **pseudonym base** proof value
/// (`featureOption: pseudonym`).
const CBOR_PREFIX_BASE_PSEUDONYM: [u8; 3] = [0xd9, 0x5d, 0x08];

/// Convert 32 entropy/secret bytes to a BBS scalar.
fn scalar_from_32(bytes: &[u8], what: &str) -> Result<bbs::Scalar, DataIntegrityError> {
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| DataIntegrityError::Conformance(format!("{what} must be 32 bytes")))?;
    bbs::hash::scalar_from_bytes(&arr)
        .ok_or_else(|| DataIntegrityError::Conformance(format!("{what} is not a valid scalar")))
}

/// Produce a `bbs-2023` **pseudonym base proof** value (issuer side), per
/// vc-di-bbs `featureOption: pseudonym`.
///
/// Identical to [`create_base_proof_value`] except the non-mandatory statements
/// are **blind-signed** over the holder's `commitment_with_proof` (from
/// `affinidi_bbs::nym_commit`, committing the holder's `prover_nym`) with the
/// issuer's `signer_nym_entropy` mixed in, and the serialized `proofValue`
/// carries `signer_nym_entropy` under the `0xd95d08` prefix.
#[allow(clippy::too_many_arguments)]
pub fn create_pseudonym_base_proof_value(
    document: &Value,
    proof_config: &Value,
    mandatory_pointers: &[&str],
    sk: &bbs::SecretKey,
    pk: &bbs::PublicKey,
    hmac_key: &[u8],
    commitment_with_proof: &[u8],
    signer_nym_entropy: &[u8],
) -> Result<String, DataIntegrityError> {
    let proof_hash = proof_hash(proof_config)?;
    let grouped = canonicalize_and_group(document, mandatory_pointers, hmac_key)?;

    let mut bbs_header = proof_hash.to_vec();
    bbs_header.extend_from_slice(&grouped.mandatory_hash);

    let non_mandatory = grouped.non_mandatory();
    let messages: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();

    let entropy = scalar_from_32(signer_nym_entropy, "signer_nym_entropy")?;
    let signature = bbs::blind_sign_with_nym(
        sk,
        pk,
        commitment_with_proof,
        entropy,
        &bbs_header,
        &messages,
        bbs::Ciphersuite::default(),
    )
    .map_err(DataIntegrityError::signing)?;

    serialize_pseudonym_base_proof_value(
        &signature.to_bytes(),
        &bbs_header,
        &pk.to_bytes(),
        hmac_key,
        mandatory_pointers,
        signer_nym_entropy,
    )
}

/// `serializeBaseProofValue` (pseudonym): `multibase("u" + 0xd95d08 +
/// CBOR([bbsSignature, bbsHeader, publicKey, hmacKey, mandatoryPointers,
/// signerNymEntropy]))`. `featureOption` is implied by the prefix.
pub fn serialize_pseudonym_base_proof_value(
    bbs_signature: &[u8],
    bbs_header: &[u8],
    public_key: &[u8],
    hmac_key: &[u8],
    mandatory_pointers: &[&str],
    signer_nym_entropy: &[u8],
) -> Result<String, DataIntegrityError> {
    let components = ciborium::Value::Array(vec![
        ciborium::Value::Bytes(bbs_signature.to_vec()),
        ciborium::Value::Bytes(bbs_header.to_vec()),
        ciborium::Value::Bytes(public_key.to_vec()),
        ciborium::Value::Bytes(hmac_key.to_vec()),
        ciborium::Value::Array(
            mandatory_pointers
                .iter()
                .map(|p| ciborium::Value::Text((*p).to_string()))
                .collect(),
        ),
        // signer_nym_entropy is a scalar → CBOR tag 2 (positive bignum).
        ciborium::Value::Tag(
            2,
            Box::new(ciborium::Value::Bytes(signer_nym_entropy.to_vec())),
        ),
    ]);

    let mut buf = CBOR_PREFIX_BASE_PSEUDONYM.to_vec();
    ciborium::into_writer(&components, &mut buf)
        .map_err(|e| DataIntegrityError::MalformedProof(format!("CBOR encode: {e}")))?;
    Ok(multibase::encode(multibase::Base::Base64Url, &buf))
}

/// CBOR prefix bytes for a `bbs-2023` **derived** proof value.
const CBOR_PREFIX_DERIVED: [u8; 3] = [0xd9, 0x5d, 0x03];

/// A parsed derived (`0xd95d03`) proof value.
struct DerivedProofValue {
    bbs_proof: Vec<u8>,
    /// `c14nN → bM` label map (decompressed from the integer→integer CBOR map).
    label_map: BTreeMap<String, String>,
    mandatory_indexes: Vec<usize>,
    selective_indexes: Vec<usize>,
    presentation_header: Vec<u8>,
}

/// `parseDisclosureProofValue`: decode the multibase CBOR derived proof value.
fn parse_derived_proof_value(proof_value: &str) -> Result<DerivedProofValue, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    if !proof_value.starts_with('u') {
        return Err(malformed("proofValue must be multibase base64url ('u')"));
    }
    let (_base, bytes) =
        multibase::decode(proof_value).map_err(|e| malformed(&format!("multibase: {e}")))?;
    if bytes.len() < 3 || bytes[..3] != CBOR_PREFIX_DERIVED {
        return Err(malformed("proofValue is not a bbs-2023 derived proof"));
    }
    let value: ciborium::Value =
        ciborium::from_reader(&bytes[3..]).map_err(|e| malformed(&format!("CBOR: {e}")))?;
    let arr = value
        .as_array()
        .ok_or_else(|| malformed("derived proofValue must be a CBOR array"))?;
    if arr.len() != 5 {
        return Err(malformed("derived proofValue must have 5 elements"));
    }

    let bbs_proof = arr[0]
        .as_bytes()
        .ok_or_else(|| malformed("bbsProof must be bytes"))?
        .clone();

    // compressedLabelMap: CBOR map of integer → integer → c14nN → bM.
    let mut label_map = BTreeMap::new();
    for (k, v) in arr[1]
        .as_map()
        .ok_or_else(|| malformed("labelMap must be a CBOR map"))?
    {
        let n = cbor_int(k).ok_or_else(|| malformed("labelMap key"))?;
        let m = cbor_int(v).ok_or_else(|| malformed("labelMap value"))?;
        label_map.insert(format!("c14n{n}"), format!("b{m}"));
    }

    let mandatory_indexes =
        cbor_index_array(&arr[2]).ok_or_else(|| malformed("mandatoryIndexes"))?;
    let selective_indexes =
        cbor_index_array(&arr[3]).ok_or_else(|| malformed("selectiveIndexes"))?;
    let presentation_header = arr[4]
        .as_bytes()
        .ok_or_else(|| malformed("presentationHeader must be bytes"))?
        .clone();

    Ok(DerivedProofValue {
        bbs_proof,
        label_map,
        mandatory_indexes,
        selective_indexes,
        presentation_header,
    })
}

fn cbor_int(v: &ciborium::Value) -> Option<usize> {
    let i: i128 = v.as_integer()?.into();
    usize::try_from(i).ok()
}

fn cbor_index_array(v: &ciborium::Value) -> Option<Vec<usize>> {
    v.as_array()?.iter().map(cbor_int).collect()
}

/// Verify a `bbs-2023` **derived proof** (verifier side), per W3C vc-di-bbs.
///
/// Reconstructs the verify data from the disclosed `reveal_document` and its
/// derived `proofValue`, then BBS-`proof_verify`s. `pk` is the issuer's BBS
/// public key (resolved from the proof's verification method by the caller).
pub fn verify_derived_proof(
    reveal_document: &Value,
    pk: &bbs::PublicKey,
) -> Result<bool, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    let proof = reveal_document
        .get("proof")
        .ok_or_else(|| malformed("reveal document has no proof"))?;
    let proof_value = proof
        .get("proofValue")
        .and_then(Value::as_str)
        .ok_or_else(|| malformed("proof has no proofValue"))?;
    let parsed = parse_derived_proof_value(proof_value)?;

    // proofHash = SHA-256(RDFC(proofConfig)); proofConfig = proof - proofValue,
    // carrying the document's @context.
    let mut proof_config = proof.clone();
    let cfg = proof_config
        .as_object_mut()
        .ok_or_else(|| malformed("proof must be an object"))?;
    cfg.remove("proofValue");
    if let Some(ctx) = reveal_document.get("@context") {
        cfg.insert("@context".to_string(), ctx.clone());
    }
    let proof_hash = proof_hash(&proof_config)?;

    // Canonicalize the reveal document (minus proof), relabel via the label map.
    let mut doc = reveal_document.clone();
    doc.as_object_mut()
        .ok_or_else(|| malformed("document must be an object"))?
        .remove("proof");
    let dataset = jsonld::expand_and_to_rdf(&doc).map_err(canon_err)?;
    let (canonical_c14n, _) = rdfc1::canonicalize_with_label_map(&dataset).map_err(canon_err)?;
    let labeled = lines_with_newline(&relabel_and_sort(&canonical_c14n, &parsed.label_map));

    // Split mandatory vs disclosed non-mandatory by index.
    let mandatory_set: BTreeSet<usize> = parsed.mandatory_indexes.iter().copied().collect();
    let mut mandatory = Vec::new();
    let mut non_mandatory = Vec::new();
    for (i, nq) in labeled.iter().enumerate() {
        if mandatory_set.contains(&i) {
            mandatory.push(nq.clone());
        } else {
            non_mandatory.push(nq.clone());
        }
    }

    let mut hasher = Sha256::new();
    for m in &mandatory {
        hasher.update(m.as_bytes());
    }
    let mandatory_hash: [u8; 32] = hasher.finalize().into();

    let mut bbs_header = proof_hash.to_vec();
    bbs_header.extend_from_slice(&mandatory_hash);

    let disclosed: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();
    let bbs_proof = bbs::Proof::from_bytes(&parsed.bbs_proof);
    bbs::proof_verify(
        pk,
        &bbs_proof,
        &bbs_header,
        &parsed.presentation_header,
        &disclosed,
        &parsed.selective_indexes,
    )
    .map_err(|e| {
        tracing::debug!("bbs-2023 derived proof verification failed: {e}");
        DataIntegrityError::InvalidSignature {
            suite: crate::crypto_suites::CryptoSuite::Bbs2023,
            reason: crate::error::SignatureFailure::Invalid,
        }
    })
}

/// The result of grouping canonical statements by mandatory pointers.
#[derive(Debug)]
pub struct GroupedStatements {
    /// All HMAC-canonical statements (sorted), one per line including `\n`.
    pub canonical: Vec<String>,
    /// Indices (into `canonical`) of the mandatory statements, ascending.
    pub mandatory_indexes: Vec<usize>,
    /// Indices of the non-mandatory statements, ascending.
    pub non_mandatory_indexes: Vec<usize>,
    /// `mandatoryHash = SHA-256(concat(mandatory statements in index order))`.
    pub mandatory_hash: [u8; 32],
}

impl GroupedStatements {
    /// The mandatory statements (in `mandatory_indexes` order).
    pub fn mandatory(&self) -> Vec<&str> {
        self.mandatory_indexes
            .iter()
            .map(|&i| self.canonical[i].as_str())
            .collect()
    }

    /// The non-mandatory statements — the BBS messages — in index order.
    pub fn non_mandatory(&self) -> Vec<&str> {
        self.non_mandatory_indexes
            .iter()
            .map(|&i| self.canonical[i].as_str())
            .collect()
    }
}

/// A document canonicalized with the HMAC label map, plus everything needed to
/// group its statements by JSON-pointer selection.
struct CanonicalizedHmac {
    /// The document with `urn:bnid:` skolem ids on its node objects.
    skolemized: Value,
    /// Sorted, `bK`-labeled canonical statements (each with trailing `\n`).
    canonical: Vec<String>,
    /// Skolem blank-node id → `bK` label.
    input_to_b: BTreeMap<String, String>,
}

/// `labelReplacementCanonicalizeJsonLd` with the HMAC label map factory.
fn canonicalize_hmac(
    document: &Value,
    hmac_key: &[u8],
) -> Result<CanonicalizedHmac, DataIntegrityError> {
    let skolemized = skolemize_compact(document);
    let deskolemized = to_deskolemized_nquads(&skolemized)?;
    let joined: String = deskolemized.iter().cloned().collect();
    let dataset = nquads::parse(&joined).map_err(canon_err)?;
    let (canonical_c14n, input_to_c14n) =
        rdfc1::canonicalize_with_label_map(&dataset).map_err(canon_err)?;

    let c14n_to_b = hmac_label_map(&canonical_c14n, hmac_key)?;
    let input_to_b: BTreeMap<String, String> = input_to_c14n
        .iter()
        .filter_map(|(input, c14n)| c14n_to_b.get(c14n).map(|b| (input.clone(), b.clone())))
        .collect();
    let canonical = lines_with_newline(&relabel_and_sort(&canonical_c14n, &c14n_to_b));

    Ok(CanonicalizedHmac {
        skolemized,
        canonical,
        input_to_b,
    })
}

/// Indices (into `c.canonical`) of the statements selected by `pointers`.
fn select_indices(
    c: &CanonicalizedHmac,
    pointers: &[&str],
) -> Result<Vec<usize>, DataIntegrityError> {
    if pointers.is_empty() {
        return Ok(Vec::new());
    }
    let selection =
        select_json_ld(&c.skolemized, pointers).ok_or_else(|| canon_err("empty selection"))?;
    let sel_nquads = to_deskolemized_nquads(&selection)?;
    let mut idx = BTreeSet::new();
    for line in &sel_nquads {
        let relabeled = relabel_blank_line(line, &c.input_to_b);
        let pos = c
            .canonical
            .iter()
            .position(|x| *x == relabeled)
            .ok_or_else(|| canon_err(format!("selected statement not found: {relabeled:?}")))?;
        idx.insert(pos);
    }
    Ok(idx.into_iter().collect())
}

/// `canonicalizeAndGroup` for the base proof: split `document`'s HMAC-canonical
/// statements into mandatory (selected by `mandatory_pointers`) and
/// non-mandatory, and compute `mandatoryHash`.
pub fn canonicalize_and_group(
    document: &Value,
    mandatory_pointers: &[&str],
    hmac_key: &[u8],
) -> Result<GroupedStatements, DataIntegrityError> {
    let c = canonicalize_hmac(document, hmac_key)?;
    let mandatory_indexes = select_indices(&c, mandatory_pointers)?;

    let mandatory_set: BTreeSet<usize> = mandatory_indexes.iter().copied().collect();
    let non_mandatory_indexes: Vec<usize> = (0..c.canonical.len())
        .filter(|i| !mandatory_set.contains(i))
        .collect();

    let mut hasher = Sha256::new();
    for &i in &mandatory_indexes {
        hasher.update(c.canonical[i].as_bytes());
    }
    let mandatory_hash: [u8; 32] = hasher.finalize().into();

    Ok(GroupedStatements {
        canonical: c.canonical,
        mandatory_indexes,
        non_mandatory_indexes,
        mandatory_hash,
    })
}

fn canon_err(e: impl std::fmt::Display) -> DataIntegrityError {
    DataIntegrityError::Canonicalization(e.to_string())
}

/// A parsed base (`0xd95d02`) proof value.
struct BaseProofValue {
    bbs_signature: Vec<u8>,
    bbs_header: Vec<u8>,
    hmac_key: Vec<u8>,
    mandatory_pointers: Vec<String>,
}

/// `parseBaseProofValue`: decode the multibase CBOR base proof value.
fn parse_base_proof_value(proof_value: &str) -> Result<BaseProofValue, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    if !proof_value.starts_with('u') {
        return Err(malformed("proofValue must be multibase base64url ('u')"));
    }
    let (_base, bytes) =
        multibase::decode(proof_value).map_err(|e| malformed(&format!("multibase: {e}")))?;
    if bytes.len() < 3 || bytes[..3] != CBOR_PREFIX_BASE {
        return Err(malformed("proofValue is not a bbs-2023 base proof"));
    }
    let value: ciborium::Value =
        ciborium::from_reader(&bytes[3..]).map_err(|e| malformed(&format!("CBOR: {e}")))?;
    let arr = value
        .as_array()
        .ok_or_else(|| malformed("base proofValue must be a CBOR array"))?;
    if arr.len() != 5 {
        return Err(malformed("base proofValue must have 5 elements"));
    }
    let bytes_at = |i: usize, what: &str| {
        arr[i]
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed(&format!("{what} must be bytes")))
    };
    let mandatory_pointers = arr[4]
        .as_array()
        .ok_or_else(|| malformed("mandatoryPointers must be an array"))?
        .iter()
        .map(|p| {
            p.as_text()
                .map(str::to_string)
                .ok_or_else(|| malformed("mandatory pointer must be text"))
        })
        .collect::<Result<_, _>>()?;
    Ok(BaseProofValue {
        bbs_signature: bytes_at(0, "bbsSignature")?,
        bbs_header: bytes_at(1, "bbsHeader")?,
        hmac_key: bytes_at(3, "hmacKey")?,
        mandatory_pointers,
    })
}

/// Create a `bbs-2023` **derived proof** (holder side), selectively disclosing
/// the claims under `selective_pointers` (plus the issuer's mandatory ones).
///
/// `base_document` is the issuer's base-proof VC; `pk` is the issuer's BBS
/// public key; `presentation_header` is the verifier's nonce. Returns the
/// disclosed reveal document with a derived `proof`.
pub fn create_derived_proof(
    base_document: &Value,
    selective_pointers: &[&str],
    presentation_header: &[u8],
    pk: &bbs::PublicKey,
) -> Result<Value, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    let proof = base_document
        .get("proof")
        .ok_or_else(|| malformed("base document has no proof"))?;
    let base = parse_base_proof_value(
        proof
            .get("proofValue")
            .and_then(Value::as_str)
            .ok_or_else(|| malformed("proof has no proofValue"))?,
    )?;

    let mut document = base_document.clone();
    document
        .as_object_mut()
        .ok_or_else(|| malformed("document must be an object"))?
        .remove("proof");

    let mandatory_ptrs: Vec<&str> = base.mandatory_pointers.iter().map(String::as_str).collect();
    let combined_ptrs: Vec<&str> = mandatory_ptrs
        .iter()
        .copied()
        .chain(selective_pointers.iter().copied())
        .collect();

    // Group the full document and compute the index sets.
    let c = canonicalize_hmac(&document, &base.hmac_key)?;
    let mandatory_indexes = select_indices(&c, &mandatory_ptrs)?;
    let selective_indexes = select_indices(&c, selective_pointers)?;
    let combined_indexes = select_indices(&c, &combined_ptrs)?;

    let mandatory_set: BTreeSet<usize> = mandatory_indexes.iter().copied().collect();
    let selective_set: BTreeSet<usize> = selective_indexes.iter().copied().collect();
    let non_mandatory_indexes: Vec<usize> = (0..c.canonical.len())
        .filter(|i| !mandatory_set.contains(i))
        .collect();

    // Mandatory indices relative to the revealed (combined) statement set.
    let adj_mandatory: Vec<usize> = mandatory_indexes
        .iter()
        .map(|m| {
            combined_indexes
                .iter()
                .position(|x| x == m)
                .expect("mandatory ⊆ combined")
        })
        .collect();
    // Selectively-disclosed indices relative to the non-mandatory message list
    // (these are the BBS proof's disclosed indexes).
    let adj_selective: Vec<usize> = non_mandatory_indexes
        .iter()
        .enumerate()
        .filter(|(_, nm)| selective_set.contains(nm))
        .map(|(pos, _)| pos)
        .collect();

    // BBS proof over the non-mandatory messages, disclosing the selective ones.
    let non_mandatory: Vec<&str> = non_mandatory_indexes
        .iter()
        .map(|&i| c.canonical[i].as_str())
        .collect();
    let messages: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();
    let signature = bbs::Signature::from_bytes(&base.bbs_signature)
        .map_err(|e| malformed(&format!("decode bbsSignature: {e}")))?;
    let bbs_proof = bbs::proof_gen(
        pk,
        &signature,
        &base.bbs_header,
        presentation_header,
        &messages,
        &adj_selective,
    )
    .map_err(DataIntegrityError::signing)?;

    // Derived label map: reveal-document c14n labels → original bK labels.
    let label_map = build_derived_label_map(&c, &combined_ptrs)?;

    let proof_value = serialize_derived_proof_value(
        bbs_proof.to_bytes(),
        &label_map,
        &adj_mandatory,
        &adj_selective,
        presentation_header,
    )?;

    // Reveal document = the disclosed sub-document + the derived proof.
    let mut reveal = select_json_ld(&document, &combined_ptrs)
        .ok_or_else(|| malformed("empty reveal selection"))?;
    let mut proof_obj = proof.clone();
    proof_obj
        .as_object_mut()
        .ok_or_else(|| malformed("proof must be an object"))?
        .insert("proofValue".to_string(), Value::String(proof_value));
    reveal
        .as_object_mut()
        .ok_or_else(|| malformed("reveal must be an object"))?
        .insert("proof".to_string(), proof_obj);
    Ok(reveal)
}

/// Build the derived proof's label map (`reveal c14nN → original bM`) by
/// canonicalizing the skolemized reveal selection and composing through the
/// full document's `input → bM` map.
fn build_derived_label_map(
    c: &CanonicalizedHmac,
    combined_ptrs: &[&str],
) -> Result<BTreeMap<String, String>, DataIntegrityError> {
    let selection =
        select_json_ld(&c.skolemized, combined_ptrs).ok_or_else(|| canon_err("empty selection"))?;
    let sel_nquads = to_deskolemized_nquads(&selection)?;
    let joined: String = sel_nquads.concat();
    let dataset = nquads::parse(&joined).map_err(canon_err)?;
    let (_canonical, reveal_input_to_c14n) =
        rdfc1::canonicalize_with_label_map(&dataset).map_err(canon_err)?;

    let mut label_map = BTreeMap::new();
    for (reveal_input, reveal_c14n) in &reveal_input_to_c14n {
        if let Some(b) = c.input_to_b.get(reveal_input) {
            label_map.insert(reveal_c14n.clone(), b.clone());
        }
    }
    Ok(label_map)
}

/// `serializeDisclosureProofValue`: `multibase("u" + 0xd95d03 + CBOR([bbsProof,
/// compressedLabelMap, mandatoryIndexes, selectiveIndexes, presentationHeader]))`.
fn serialize_derived_proof_value(
    bbs_proof: &[u8],
    label_map: &BTreeMap<String, String>,
    mandatory_indexes: &[usize],
    selective_indexes: &[usize],
    presentation_header: &[u8],
) -> Result<String, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    // Compress `c14nN → bM` to a CBOR integer→integer map.
    let mut compressed = Vec::with_capacity(label_map.len());
    for (k, v) in label_map {
        let n: i64 = k
            .strip_prefix("c14n")
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| malformed("label map key"))?;
        let m: i64 = v
            .strip_prefix('b')
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| malformed("label map value"))?;
        compressed.push((
            ciborium::Value::Integer(n.into()),
            ciborium::Value::Integer(m.into()),
        ));
    }
    let index_array = |idx: &[usize]| {
        ciborium::Value::Array(
            idx.iter()
                .map(|&i| ciborium::Value::Integer((i as i64).into()))
                .collect(),
        )
    };
    let payload = ciborium::Value::Array(vec![
        ciborium::Value::Bytes(bbs_proof.to_vec()),
        ciborium::Value::Map(compressed),
        index_array(mandatory_indexes),
        index_array(selective_indexes),
        ciborium::Value::Bytes(presentation_header.to_vec()),
    ]);
    let mut buf = CBOR_PREFIX_DERIVED.to_vec();
    ciborium::into_writer(&payload, &mut buf)
        .map_err(|e| malformed(&format!("CBOR encode: {e}")))?;
    Ok(multibase::encode(multibase::Base::Base64Url, &buf))
}

/// CBOR prefix bytes for a `bbs-2023` **pseudonym derived** proof value.
const CBOR_PREFIX_DERIVED_PSEUDONYM: [u8; 3] = [0xd9, 0x5d, 0x09];

/// Parse a pseudonym base (`0xd95d08`) proof value: returns the common base
/// fields plus the issuer's `signer_nym_entropy` scalar.
fn parse_pseudonym_base_proof_value(
    proof_value: &str,
) -> Result<(BaseProofValue, bbs::Scalar), DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    if !proof_value.starts_with('u') {
        return Err(malformed("proofValue must be multibase base64url ('u')"));
    }
    let (_b, bytes) =
        multibase::decode(proof_value).map_err(|e| malformed(&format!("multibase: {e}")))?;
    if bytes.len() < 3 || bytes[..3] != CBOR_PREFIX_BASE_PSEUDONYM {
        return Err(malformed(
            "proofValue is not a bbs-2023 pseudonym base proof",
        ));
    }
    let value: ciborium::Value =
        ciborium::from_reader(&bytes[3..]).map_err(|e| malformed(&format!("CBOR: {e}")))?;
    let arr = value
        .as_array()
        .ok_or_else(|| malformed("pseudonym base proofValue must be a CBOR array"))?;
    if arr.len() != 6 {
        return Err(malformed("pseudonym base proofValue must have 6 elements"));
    }
    let bytes_at = |i: usize, what: &str| {
        arr[i]
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed(&format!("{what} must be bytes")))
    };
    let mandatory_pointers = arr[4]
        .as_array()
        .ok_or_else(|| malformed("mandatoryPointers must be an array"))?
        .iter()
        .map(|p| {
            p.as_text()
                .map(str::to_string)
                .ok_or_else(|| malformed("mandatory pointer must be text"))
        })
        .collect::<Result<_, _>>()?;
    // signer_nym_entropy is a CBOR bignum (tag 2) wrapping the 32-byte scalar.
    let entropy_bytes = match &arr[5] {
        ciborium::Value::Tag(2, inner) => inner
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed("signerNymEntropy bignum must wrap bytes"))?,
        ciborium::Value::Bytes(b) => b.clone(),
        _ => return Err(malformed("signerNymEntropy must be a bignum")),
    };
    let signer_nym_entropy = scalar_from_32(&entropy_bytes, "signerNymEntropy")?;

    Ok((
        BaseProofValue {
            bbs_signature: bytes_at(0, "bbsSignature")?,
            bbs_header: bytes_at(1, "bbsHeader")?,
            hmac_key: bytes_at(3, "hmacKey")?,
            mandatory_pointers,
        },
        signer_nym_entropy,
    ))
}

/// Create a `bbs-2023` **pseudonym derived proof** (holder side): a
/// selective-disclosure presentation bound to a per-verifier pseudonym derived
/// from `verifier_id`.
///
/// `prover_nym` / `secret_prover_blind` are the holder's secrets from
/// [`crate::bbs_2023_transform::create_pseudonym_base_proof_value`]'s issuance
/// (the `nym_commit` the holder made); `verifier_id` is the verifier's identity
/// (the pseudonym context). Returns the reveal document with a `0xd95d09` proof.
#[allow(clippy::too_many_arguments)]
pub fn create_pseudonym_derived_proof(
    base_document: &Value,
    selective_pointers: &[&str],
    presentation_header: &[u8],
    pk: &bbs::PublicKey,
    prover_nym: &[u8],
    secret_prover_blind: &[u8],
    verifier_id: &str,
) -> Result<Value, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    let proof = base_document
        .get("proof")
        .ok_or_else(|| malformed("base document has no proof"))?;
    let (base, signer_nym_entropy) = parse_pseudonym_base_proof_value(
        proof
            .get("proofValue")
            .and_then(Value::as_str)
            .ok_or_else(|| malformed("proof has no proofValue"))?,
    )?;

    let mut document = base_document.clone();
    document
        .as_object_mut()
        .ok_or_else(|| malformed("document must be an object"))?
        .remove("proof");

    let mandatory_ptrs: Vec<&str> = base.mandatory_pointers.iter().map(String::as_str).collect();
    let combined_ptrs: Vec<&str> = mandatory_ptrs
        .iter()
        .copied()
        .chain(selective_pointers.iter().copied())
        .collect();

    let c = canonicalize_hmac(&document, &base.hmac_key)?;
    let mandatory_indexes = select_indices(&c, &mandatory_ptrs)?;
    let selective_indexes = select_indices(&c, selective_pointers)?;
    let combined_indexes = select_indices(&c, &combined_ptrs)?;

    let mandatory_set: BTreeSet<usize> = mandatory_indexes.iter().copied().collect();
    let selective_set: BTreeSet<usize> = selective_indexes.iter().copied().collect();
    let non_mandatory_indexes: Vec<usize> = (0..c.canonical.len())
        .filter(|i| !mandatory_set.contains(i))
        .collect();

    let adj_mandatory: Vec<usize> = mandatory_indexes
        .iter()
        .map(|m| {
            combined_indexes
                .iter()
                .position(|x| x == m)
                .expect("mandatory ⊆ combined")
        })
        .collect();
    let adj_selective: Vec<usize> = non_mandatory_indexes
        .iter()
        .enumerate()
        .filter(|(_, nm)| selective_set.contains(nm))
        .map(|(pos, _)| pos)
        .collect();

    let non_mandatory: Vec<&str> = non_mandatory_indexes
        .iter()
        .map(|&i| c.canonical[i].as_str())
        .collect();
    let messages: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();
    let length_bbs_messages = messages.len();

    let signature = bbs::Signature::from_bytes(&base.bbs_signature)
        .map_err(|e| malformed(&format!("decode bbsSignature: {e}")))?;
    let nym_secret = scalar_from_32(prover_nym, "prover_nym")? + signer_nym_entropy;
    let spb = scalar_from_32(secret_prover_blind, "secret_prover_blind")?;

    let (bbs_proof, pseudonym) = bbs::proof_gen_with_nym(
        pk,
        &signature,
        &base.bbs_header,
        presentation_header,
        nym_secret,
        verifier_id.as_bytes(),
        &messages,
        &adj_selective,
        &[],
        &[],
        spb,
        bbs::Ciphersuite::default(),
    )
    .map_err(DataIntegrityError::signing)?;

    let label_map = build_derived_label_map(&c, &combined_ptrs)?;

    let proof_value = serialize_pseudonym_derived_proof_value(
        bbs_proof.to_bytes(),
        &label_map,
        &adj_mandatory,
        &adj_selective,
        presentation_header,
        &pseudonym.to_bytes(),
        length_bbs_messages,
    )?;

    let mut reveal = select_json_ld(&document, &combined_ptrs)
        .ok_or_else(|| malformed("empty reveal selection"))?;
    let mut proof_obj = proof.clone();
    proof_obj
        .as_object_mut()
        .ok_or_else(|| malformed("proof must be an object"))?
        .insert("proofValue".to_string(), Value::String(proof_value));
    reveal
        .as_object_mut()
        .ok_or_else(|| malformed("reveal must be an object"))?
        .insert("proof".to_string(), proof_obj);
    Ok(reveal)
}

/// `serializeDisclosureProofValue` (pseudonym): `0xd95d09 + CBOR([bbsProof,
/// compressedLabelMap, mandatoryIndexes, selectiveIndexes, presentationHeader,
/// pseudonym, lengthBBSMessages])`.
#[allow(clippy::too_many_arguments)]
fn serialize_pseudonym_derived_proof_value(
    bbs_proof: &[u8],
    label_map: &BTreeMap<String, String>,
    mandatory_indexes: &[usize],
    selective_indexes: &[usize],
    presentation_header: &[u8],
    pseudonym: &[u8],
    length_bbs_messages: usize,
) -> Result<String, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    let mut compressed = Vec::with_capacity(label_map.len());
    for (k, v) in label_map {
        let n: i64 = k
            .strip_prefix("c14n")
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| malformed("label map key"))?;
        let m: i64 = v
            .strip_prefix('b')
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| malformed("label map value"))?;
        compressed.push((
            ciborium::Value::Integer(n.into()),
            ciborium::Value::Integer(m.into()),
        ));
    }
    let index_array = |idx: &[usize]| {
        ciborium::Value::Array(
            idx.iter()
                .map(|&i| ciborium::Value::Integer((i as i64).into()))
                .collect(),
        )
    };
    let payload = ciborium::Value::Array(vec![
        ciborium::Value::Bytes(bbs_proof.to_vec()),
        ciborium::Value::Map(compressed),
        index_array(mandatory_indexes),
        index_array(selective_indexes),
        ciborium::Value::Bytes(presentation_header.to_vec()),
        ciborium::Value::Bytes(pseudonym.to_vec()),
        ciborium::Value::Integer((length_bbs_messages as i64).into()),
    ]);
    let mut buf = CBOR_PREFIX_DERIVED_PSEUDONYM.to_vec();
    ciborium::into_writer(&payload, &mut buf)
        .map_err(|e| malformed(&format!("CBOR encode: {e}")))?;
    Ok(multibase::encode(multibase::Base::Base64Url, &buf))
}

/// A parsed pseudonym derived (`0xd95d09`) proof value.
struct PseudonymDerivedProofValue {
    bbs_proof: Vec<u8>,
    label_map: BTreeMap<String, String>,
    mandatory_indexes: Vec<usize>,
    selective_indexes: Vec<usize>,
    presentation_header: Vec<u8>,
    pseudonym: Vec<u8>,
    /// Total non-mandatory signer message count `L` (the verifier needs it to
    /// rebuild the BBS generators; the reveal document only carries the disclosed
    /// subset).
    length_bbs_messages: usize,
}

fn parse_pseudonym_derived_proof_value(
    proof_value: &str,
) -> Result<PseudonymDerivedProofValue, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    if !proof_value.starts_with('u') {
        return Err(malformed("proofValue must be multibase base64url ('u')"));
    }
    let (_b, bytes) =
        multibase::decode(proof_value).map_err(|e| malformed(&format!("multibase: {e}")))?;
    if bytes.len() < 3 || bytes[..3] != CBOR_PREFIX_DERIVED_PSEUDONYM {
        return Err(malformed(
            "proofValue is not a bbs-2023 pseudonym derived proof",
        ));
    }
    let value: ciborium::Value =
        ciborium::from_reader(&bytes[3..]).map_err(|e| malformed(&format!("CBOR: {e}")))?;
    let arr = value
        .as_array()
        .ok_or_else(|| malformed("derived proofValue must be a CBOR array"))?;
    if arr.len() != 7 {
        return Err(malformed(
            "pseudonym derived proofValue must have 7 elements",
        ));
    }
    let mut label_map = BTreeMap::new();
    for (k, v) in arr[1]
        .as_map()
        .ok_or_else(|| malformed("labelMap must be a CBOR map"))?
    {
        let n = cbor_int(k).ok_or_else(|| malformed("labelMap key"))?;
        let m = cbor_int(v).ok_or_else(|| malformed("labelMap value"))?;
        label_map.insert(format!("c14n{n}"), format!("b{m}"));
    }
    Ok(PseudonymDerivedProofValue {
        bbs_proof: arr[0]
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed("bbsProof must be bytes"))?,
        label_map,
        mandatory_indexes: cbor_index_array(&arr[2])
            .ok_or_else(|| malformed("mandatoryIndexes"))?,
        selective_indexes: cbor_index_array(&arr[3])
            .ok_or_else(|| malformed("selectiveIndexes"))?,
        presentation_header: arr[4]
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed("presentationHeader must be bytes"))?,
        pseudonym: arr[5]
            .as_bytes()
            .cloned()
            .ok_or_else(|| malformed("pseudonym must be bytes"))?,
        length_bbs_messages: cbor_int(&arr[6])
            .ok_or_else(|| malformed("lengthBBSMessages must be an integer"))?,
    })
}

/// Verify a `bbs-2023` **pseudonym derived proof**: checks the selective
/// disclosure and the per-verifier pseudonym binding. `verifier_id` must match
/// the one used at derivation (the pseudonym context).
pub fn verify_pseudonym_derived_proof(
    reveal_document: &Value,
    pk: &bbs::PublicKey,
    verifier_id: &str,
) -> Result<bool, DataIntegrityError> {
    let malformed = |m: &str| DataIntegrityError::MalformedProof(m.to_string());
    let proof = reveal_document
        .get("proof")
        .ok_or_else(|| malformed("reveal document has no proof"))?;
    let parsed = parse_pseudonym_derived_proof_value(
        proof
            .get("proofValue")
            .and_then(Value::as_str)
            .ok_or_else(|| malformed("proof has no proofValue"))?,
    )?;

    let mut proof_config = proof.clone();
    let cfg = proof_config
        .as_object_mut()
        .ok_or_else(|| malformed("proof must be an object"))?;
    cfg.remove("proofValue");
    if let Some(ctx) = reveal_document.get("@context") {
        cfg.insert("@context".to_string(), ctx.clone());
    }
    let proof_hash = proof_hash(&proof_config)?;

    let mut doc = reveal_document.clone();
    doc.as_object_mut()
        .ok_or_else(|| malformed("document must be an object"))?
        .remove("proof");
    let dataset = jsonld::expand_and_to_rdf(&doc).map_err(canon_err)?;
    let (canonical_c14n, _) = rdfc1::canonicalize_with_label_map(&dataset).map_err(canon_err)?;
    let labeled = lines_with_newline(&relabel_and_sort(&canonical_c14n, &parsed.label_map));

    let mandatory_set: BTreeSet<usize> = parsed.mandatory_indexes.iter().copied().collect();
    let mut mandatory = Vec::new();
    let mut non_mandatory = Vec::new();
    for (i, nq) in labeled.iter().enumerate() {
        if mandatory_set.contains(&i) {
            mandatory.push(nq.clone());
        } else {
            non_mandatory.push(nq.clone());
        }
    }

    let mut hasher = Sha256::new();
    for m in &mandatory {
        hasher.update(m.as_bytes());
    }
    let mandatory_hash: [u8; 32] = hasher.finalize().into();
    let mut bbs_header = proof_hash.to_vec();
    bbs_header.extend_from_slice(&mandatory_hash);

    let pseudonym_bytes: [u8; 48] = parsed
        .pseudonym
        .as_slice()
        .try_into()
        .map_err(|_| malformed("pseudonym must be 48 bytes"))?;
    let pseudonym = bbs::Pseudonym::from_bytes(&pseudonym_bytes)
        .map_err(|e| malformed(&format!("invalid pseudonym: {e}")))?;

    // `l` is the total signer message count at signing time (lengthBBSMessages);
    // the reveal document only carries the disclosed non-mandatory subset.
    let l = parsed.length_bbs_messages;
    let disclosed: Vec<&[u8]> = non_mandatory.iter().map(|s| s.as_bytes()).collect();
    let bbs_proof = bbs::Proof::from_bytes(&parsed.bbs_proof);
    bbs::proof_verify_with_nym(
        pk,
        &bbs_proof,
        &bbs_header,
        &parsed.presentation_header,
        &pseudonym,
        verifier_id.as_bytes(),
        l,
        &disclosed,
        &parsed.selective_indexes,
        &[],
        &[],
        bbs::Ciphersuite::default(),
    )
    .map_err(|e| {
        tracing::debug!("bbs-2023 pseudonym derived proof verification failed: {e}");
        DataIntegrityError::InvalidSignature {
            suite: crate::crypto_suites::CryptoSuite::Bbs2023,
            reason: crate::error::SignatureFailure::Invalid,
        }
    })
}

/// `proofHash = SHA-256(RDFC-1.0(proofConfig))`.
///
/// `proof_config` is the proof options as a JSON-LD object (its `@context` must
/// match the secured document's). Returns the 32-byte hash.
pub fn proof_hash(proof_config: &Value) -> Result<[u8; 32], DataIntegrityError> {
    let dataset = jsonld::expand_and_to_rdf(proof_config).map_err(canon_err)?;
    let canonical = rdfc1::canonicalize(&dataset).map_err(canon_err)?;
    Ok(Sha256::digest(canonical.as_bytes()).into())
}

/// Apply the `bbs-2023` HMAC blank-node label map to a JSON-LD document and
/// return the relabeled, re-sorted canonical N-Quads.
///
/// Algorithm (vc-di-bbs / vc-di-ecdsa `createShuffledIdLabelMapFunction`):
/// 1. RDFC-1.0 canonicalize → `c14n0, c14n1, …` labels.
/// 2. For each canonical label (the bare `c14nN` string), compute
///    `HMAC-SHA-256(hmac_key, label)`.
/// 3. Sort the labels by the multibase-base64url-no-pad encoding of the digest
///    (`u…`), then assign `b0, b1, …` in that order.
/// 4. Relabel the canonical N-Quads and re-sort the lines.
pub fn hmac_canonicalize(document: &Value, hmac_key: &[u8]) -> Result<String, DataIntegrityError> {
    let dataset = jsonld::expand_and_to_rdf(document).map_err(canon_err)?;
    let canonical = rdfc1::canonicalize(&dataset).map_err(canon_err)?;
    let label_map = hmac_label_map(&canonical, hmac_key)?;
    Ok(relabel_and_sort(&canonical, &label_map))
}

/// Build the `c14nN → bM` label map by HMAC-and-sort.
fn hmac_label_map(
    canonical: &str,
    hmac_key: &[u8],
) -> Result<BTreeMap<String, String>, DataIntegrityError> {
    // Distinct canonical labels (`c14n0`, `c14n1`, …) in lexicographic order.
    let labels = distinct_c14n_labels(canonical);

    // HMAC each label; the sort key is the multibase-base64url-no-pad digest.
    let mut keyed: Vec<(String, String)> = labels
        .into_iter()
        .map(|label| {
            let mut mac = HmacSha256::new_from_slice(hmac_key)
                .map_err(|e| canon_err(format!("HMAC key: {e}")))?;
            mac.update(label.as_bytes());
            let digest = mac.finalize().into_bytes();
            let sort_key = multibase::encode(multibase::Base::Base64Url, digest);
            Ok((sort_key, label))
        })
        .collect::<Result<_, DataIntegrityError>>()?;
    keyed.sort();

    Ok(keyed
        .into_iter()
        .enumerate()
        .map(|(i, (_, label))| (label, format!("b{i}")))
        .collect())
}

/// Distinct `c14nN` blank-node labels appearing in canonical N-Quads.
fn distinct_c14n_labels(canonical: &str) -> Vec<String> {
    let mut set = std::collections::BTreeSet::new();
    for line in canonical.lines() {
        let mut rest = line;
        while let Some(pos) = rest.find("_:c14n") {
            let after = &rest[pos + 2..]; // skip "_:"
            let end = after
                .char_indices()
                .find(|(_, c)| !(c.is_ascii_alphanumeric()))
                .map(|(i, _)| i)
                .unwrap_or(after.len());
            set.insert(after[..end].to_string());
            rest = &after[end..];
        }
    }
    set.into_iter().collect()
}

/// Replace each `_:c14nN` with `_:bM` per `label_map`, then re-sort the lines.
fn relabel_and_sort(canonical: &str, label_map: &BTreeMap<String, String>) -> String {
    let mut lines: Vec<String> = canonical
        .lines()
        .map(|line| {
            let mut out = String::with_capacity(line.len() + 1);
            let mut rest = line;
            while let Some(pos) = rest.find("_:c14n") {
                out.push_str(&rest[..pos]);
                let after = &rest[pos + 2..]; // after "_:"
                let end = after
                    .char_indices()
                    .find(|(_, c)| !c.is_ascii_alphanumeric())
                    .map(|(i, _)| i)
                    .unwrap_or(after.len());
                let label = &after[..end];
                out.push_str("_:");
                out.push_str(label_map.get(label).map(String::as_str).unwrap_or(label));
                rest = &after[end..];
            }
            out.push_str(rest);
            out.push('\n');
            out
        })
        .collect();
    lines.sort();
    lines.concat()
}

// --- skolemization, selection, grouping helpers ----------------------------

/// Split a joined N-Quads string into lines, each terminated with `\n`.
fn lines_with_newline(joined: &str) -> Vec<String> {
    joined
        .lines()
        .map(|l| {
            let mut s = l.to_string();
            s.push('\n');
            s
        })
        .collect()
}

/// Skolemize a compact JSON-LD document: give every node object that lacks an
/// id a stable `urn:bnid:` `@id`. Self-consistent labeling is sufficient —
/// grouping matches statements by content against the canonical set, so the
/// exact skolem ids never leak into the output.
fn skolemize_compact(document: &Value) -> Value {
    let mut counter = 0u64;
    let mut out = document.clone();
    // Build the JSON-LD context so `@json`-typed values — which are opaque
    // literals, not nodes — are not skolemized. Adding skolem `@id`s inside a
    // `@json` value would pollute its canonical-JSON serialization (the reference
    // skolemizes the *expanded* form, where `@json` is an opaque `@value` object).
    let mut ctx = JsonLdContext::default();
    if let Some(c) = document.get("@context") {
        let _ = ctx.process(c);
    }
    skolemize_value(&mut out, &mut counter, &ctx);
    out
}

/// Apply the type-scoped contexts of a node's `@type` to `ctx`, so terms defined
/// under a type (e.g. `drivingPrivileges` typed `@json` under the driver's
/// licence type) become visible.
fn apply_type_scoped(ctx: &mut JsonLdContext, map: &Map<String, Value>) {
    let type_val = map.get("@type").or_else(|| {
        map.get("type")
            .filter(|_| ctx.get_term("type").is_some_and(|t| t.iri == "@type"))
    });
    let types: Vec<String> = match type_val {
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(a)) => a
            .iter()
            .filter_map(|x| x.as_str().map(String::from))
            .collect(),
        _ => Vec::new(),
    };
    let scoped: Vec<Value> = types
        .iter()
        .filter_map(|t| ctx.get_term(t).and_then(|td| td.context.clone()))
        .collect();
    for sc in scoped {
        let _ = ctx.process(&sc);
    }
}

fn skolemize_value(v: &mut Value, counter: &mut u64, ctx: &JsonLdContext) {
    match v {
        Value::Object(map) => {
            // Value objects are literals, not nodes.
            if map.contains_key("@value") {
                return;
            }
            // Active context for this node: parent + local @context + type scopes.
            let mut node_ctx = ctx.clone();
            if let Some(c) = map.get("@context") {
                let _ = node_ctx.process(c);
            }
            apply_type_scoped(&mut node_ctx, map);

            for (k, val) in map.iter_mut() {
                // Skip JSON-LD keywords except @list, whose members are nodes.
                if k.starts_with('@') && k != "@list" {
                    continue;
                }
                // Do not descend into `@json`-typed values (opaque literals).
                if node_ctx
                    .get_term(k)
                    .is_some_and(|td| td.type_mapping.as_deref() == Some("@json"))
                {
                    continue;
                }
                // Apply the property's scoped context, if any, while descending.
                let mut prop_ctx = node_ctx.clone();
                if let Some(sc) = node_ctx.get_term(k).and_then(|td| td.context.clone()) {
                    let _ = prop_ctx.process(&sc);
                }
                skolemize_value(val, counter, &prop_ctx);
            }
            if !map.contains_key("@id") && !map.contains_key("id") {
                let id = format!("{URN_BNID}_skolem_{counter}");
                *counter += 1;
                map.insert("@id".to_string(), Value::String(id));
            }
        }
        Value::Array(arr) => {
            for item in arr.iter_mut() {
                skolemize_value(item, counter, ctx);
            }
        }
        _ => {}
    }
}

/// Convert a (skolemized) JSON-LD document to deskolemized N-Quads: expand →
/// RDF → serialize, then map `<urn:bnid:X>` back to blank nodes `_:X`. Each
/// returned line is newline-terminated.
fn to_deskolemized_nquads(document: &Value) -> Result<Vec<String>, DataIntegrityError> {
    let dataset = jsonld::expand_and_to_rdf(document).map_err(canon_err)?;
    let mut lines: Vec<String> = dataset
        .quads()
        .iter()
        .map(|q| {
            let mut line = deskolemize_line(&nquads::serialize_quad(q));
            line.push('\n');
            line
        })
        .collect();
    lines.sort();
    Ok(lines)
}

/// Replace every `<urn:bnid:X>` IRI in an N-Quad line with the blank node `_:X`.
fn deskolemize_line(line: &str) -> String {
    let needle = format!("<{URN_BNID}");
    let mut out = String::with_capacity(line.len());
    let mut rest = line;
    while let Some(pos) = rest.find(&needle) {
        out.push_str(&rest[..pos]);
        let after = &rest[pos + needle.len()..];
        let end = after.find('>').unwrap_or(after.len());
        out.push_str("_:");
        out.push_str(&after[..end]);
        rest = if end < after.len() {
            &after[end + 1..]
        } else {
            ""
        };
    }
    out.push_str(rest);
    out
}

/// Relabel blank nodes `_:X` in an N-Quad line per `label_map` (`X → bK`).
fn relabel_blank_line(line: &str, label_map: &BTreeMap<String, String>) -> String {
    let mut out = String::with_capacity(line.len());
    let mut rest = line;
    while let Some(pos) = rest.find("_:") {
        out.push_str(&rest[..pos]);
        let after = &rest[pos + 2..];
        // A blank-node label runs until whitespace.
        let end = after
            .find(|c: char| c.is_whitespace())
            .unwrap_or(after.len());
        let label = &after[..end];
        out.push_str("_:");
        out.push_str(label_map.get(label).map(String::as_str).unwrap_or(label));
        rest = &after[end..];
    }
    out.push_str(rest);
    out
}

/// Parse an RFC-6901 JSON pointer into path segments (with `~0`/`~1` unescaped).
fn parse_pointer(pointer: &str) -> Vec<String> {
    pointer
        .split('/')
        .skip(1)
        .map(|p| p.replace("~1", "/").replace("~0", "~"))
        .collect()
}

/// `selectJsonLd` (vc-di-ecdsa): build a sub-document containing only the values
/// at `pointers`, always carrying `@context`, non-blank ids, and `type`.
fn select_json_ld(document: &Value, pointers: &[&str]) -> Option<Value> {
    if pointers.is_empty() {
        return None;
    }
    let mut selection = Map::new();
    if let Some(ctx) = document.get("@context") {
        selection.insert("@context".to_string(), ctx.clone());
    }
    init_selection(&mut selection, document);

    let mut selection = Value::Object(selection);
    for pointer in pointers {
        let paths = parse_pointer(pointer);
        if paths.is_empty() {
            return Some(document.clone());
        }
        select_path(document, &paths, &mut selection);
    }
    compact_arrays(&mut selection);
    Some(selection)
}

/// Remove the null placeholders introduced when selecting sparse array indices.
fn compact_arrays(v: &mut Value) {
    match v {
        Value::Array(arr) => {
            arr.retain(|x| !x.is_null());
            arr.iter_mut().for_each(compact_arrays);
        }
        Value::Object(map) => map.values_mut().for_each(compact_arrays),
        _ => {}
    }
}

/// Carry over `@id`/`id` (when not a blank node) and `type`/`@type`.
fn init_selection(selection: &mut Map<String, Value>, source: &Value) {
    for id_key in ["@id", "id"] {
        if let Some(id) = source.get(id_key).and_then(Value::as_str)
            && !id.starts_with("_:")
        {
            selection.insert(id_key.to_string(), Value::String(id.to_string()));
        }
    }
    for type_key in ["@type", "type"] {
        if let Some(t) = source.get(type_key) {
            selection.insert(type_key.to_string(), t.clone());
        }
    }
}

/// Walk one pointer's path (recursively), materializing intermediate node/array
/// selections and copying the targeted leaf value.
fn select_path(source: &Value, paths: &[String], selection: &mut Value) {
    let path = &paths[0];
    let child_source = match index_value(source, path) {
        Some(v) => v,
        None => return, // pointer does not match; skip
    };

    if paths.len() == 1 {
        let new_value = match child_source {
            Value::Object(obj) => {
                // Merge already-selected fields (e.g. id/type) with the value.
                let mut merged = index_value(selection, path)
                    .and_then(Value::as_object)
                    .cloned()
                    .unwrap_or_default();
                for (k, v) in obj {
                    merged.insert(k.clone(), v.clone());
                }
                Value::Object(merged)
            }
            other => other.clone(),
        };
        set_index(selection, path, new_value);
    } else {
        ensure_intermediate(selection, path, child_source);
        let child_sel = index_value_mut(selection, path).expect("intermediate exists");
        select_path(child_source, &paths[1..], child_sel);
    }
}

/// Index a JSON value by an object key or array index path segment.
fn index_value<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
    match value {
        Value::Object(map) => map.get(path),
        Value::Array(arr) => path.parse::<usize>().ok().and_then(|i| arr.get(i)),
        _ => None,
    }
}

fn index_value_mut<'a>(value: &'a mut Value, path: &str) -> Option<&'a mut Value> {
    match value {
        Value::Object(map) => map.get_mut(path),
        Value::Array(arr) => path.parse::<usize>().ok().and_then(|i| arr.get_mut(i)),
        _ => None,
    }
}

/// Set `selected[path] = new_value`, growing arrays with nulls as needed.
fn set_index(selected: &mut Value, path: &str, new_value: Value) {
    match selected {
        Value::Object(map) => {
            map.insert(path.to_string(), new_value);
        }
        Value::Array(arr) => {
            if let Ok(i) = path.parse::<usize>() {
                while arr.len() <= i {
                    arr.push(Value::Null);
                }
                arr[i] = new_value;
            }
        }
        _ => {}
    }
}

/// Ensure `selected[path]` is an initialized container matching `source` (an
/// array placeholder or a node-selection object carrying id/type).
fn ensure_intermediate(selected: &mut Value, path: &str, source: &Value) {
    if index_value(selected, path).is_some() {
        return;
    }
    let init = if source.is_array() {
        Value::Array(Vec::new())
    } else {
        let mut node = Map::new();
        init_selection(&mut node, source);
        Value::Object(node)
    };
    set_index(selected, path, init);
}

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

    fn fixture(name: &str) -> String {
        std::fs::read_to_string(format!(
            "{}/tests/fixtures/vc-di-bbs/{}",
            env!("CARGO_MANIFEST_DIR"),
            name
        ))
        .unwrap()
    }

    fn json(name: &str) -> Value {
        serde_json::from_str(&fixture(name)).unwrap()
    }

    #[test]
    fn proof_hash_matches_w3c_vector() {
        let got = proof_hash(&json("addProofConfig.json")).unwrap();
        let expected = json("addHashData.json")["proofHash"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(hex_lower(&got), expected);
    }

    #[test]
    fn hmac_canonicalize_matches_w3c_vector() {
        let key_hex = json("BBSKeyMaterial.json")["hmacKeyString"]
            .as_str()
            .unwrap()
            .to_string();
        let key = hex_decode(&key_hex);
        let got = hmac_canonicalize(&json("windDoc.json"), &key).unwrap();
        let expected: String =
            serde_json::from_str::<Vec<String>>(&fixture("addBaseDocHMACCanon.json"))
                .unwrap()
                .concat();
        assert_eq!(
            got, expected,
            "HMAC canonicalization diverges from the W3C vc-di-bbs vector"
        );
    }

    #[test]
    fn canonicalize_and_group_matches_w3c_vector() {
        let key = hex_decode(
            json("BBSKeyMaterial.json")["hmacKeyString"]
                .as_str()
                .unwrap(),
        );
        let transform = json("addBaseTransform.json");
        let pointers: Vec<String> = transform["mandatoryPointers"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_string())
            .collect();
        let refs: Vec<&str> = pointers.iter().map(String::as_str).collect();

        let grouped = canonicalize_and_group(&json("windDoc.json"), &refs, &key).unwrap();

        let idxs = |v: &Value| -> Vec<usize> {
            v["value"]
                .as_array()
                .unwrap()
                .iter()
                .map(|e| e[0].as_u64().unwrap() as usize)
                .collect()
        };
        assert_eq!(
            grouped.mandatory_indexes,
            idxs(&transform["mandatory"]),
            "mandatory indices"
        );
        assert_eq!(
            grouped.non_mandatory_indexes,
            idxs(&transform["nonMandatory"]),
            "non-mandatory indices"
        );
        assert_eq!(
            hex_lower(&grouped.mandatory_hash),
            json("addHashData.json")["mandatoryHash"].as_str().unwrap(),
            "mandatoryHash"
        );
    }

    #[test]
    fn create_base_proof_value_matches_w3c_vector() {
        let km = json("BBSKeyMaterial.json");
        let sk_bytes: [u8; 32] = hex_decode(km["privateKeyHex"].as_str().unwrap())
            .try_into()
            .unwrap();
        let pk_bytes: [u8; 96] = hex_decode(km["publicKeyHex"].as_str().unwrap())
            .try_into()
            .unwrap();
        let sk = bbs::SecretKey::from_bytes(&sk_bytes).unwrap();
        let pk = bbs::PublicKey::from_bytes(&pk_bytes).unwrap();
        let hmac_key = hex_decode(km["hmacKeyString"].as_str().unwrap());

        let pointers: Vec<String> = json("addBaseTransform.json")["mandatoryPointers"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_string())
            .collect();
        let refs: Vec<&str> = pointers.iter().map(String::as_str).collect();

        let proof_value = create_base_proof_value(
            &json("windDoc.json"),
            &json("addProofConfig.json"),
            &refs,
            &sk,
            &pk,
            &hmac_key,
        )
        .unwrap();

        let expected = json("addSignedSDBase.json")["proof"]["proofValue"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(
            proof_value, expected,
            "base proofValue diverges from the W3C vc-di-bbs vector"
        );
    }

    #[test]
    fn serialize_pseudonym_base_proof_value_matches_w3c_vector() {
        // Gate the 0xd95d08 framing byte-exact from the published base signature
        // components (independent of the AAMVA-document canonicalization).
        let raw = json("pseudonym/addRawBaseSignatureInfo.json");
        let h = |k: &str| hex_decode(raw[k].as_str().unwrap());
        let pointers: Vec<String> = raw["mandatoryPointers"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_string())
            .collect();
        let refs: Vec<&str> = pointers.iter().map(String::as_str).collect();

        let proof_value = serialize_pseudonym_base_proof_value(
            &h("bbsSignature"),
            &h("bbsHeader"),
            &h("publicKey"),
            &h("hmacKey"),
            &refs,
            &h("signerNymEntropyHex"),
        )
        .unwrap();

        let expected = json("pseudonym/addSignedSDBase.json")["proof"]["proofValue"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(
            proof_value, expected,
            "pseudonym base 0xd95d08 framing diverges from the W3C vc-di-bbs vector"
        );
    }

    #[test]
    fn create_pseudonym_base_proof_value_matches_w3c_vector() {
        let km = json("BBSKeyMaterial.json");
        let sk_bytes: [u8; 32] = hex_decode(km["privateKeyHex"].as_str().unwrap())
            .try_into()
            .unwrap();
        let pk_bytes: [u8; 96] = hex_decode(km["publicKeyHex"].as_str().unwrap())
            .try_into()
            .unwrap();
        let sk = bbs::SecretKey::from_bytes(&sk_bytes).unwrap();
        let pk = bbs::PublicKey::from_bytes(&pk_bytes).unwrap();
        let hmac_key = hex_decode(km["hmacKeyString"].as_str().unwrap());

        let raw = json("pseudonym/addRawBaseSignatureInfo.json");
        let pointers: Vec<String> = raw["mandatoryPointers"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_string())
            .collect();
        let refs: Vec<&str> = pointers.iter().map(String::as_str).collect();

        let commitment_with_proof = hex_decode(
            json("pseudonym/commitmentInfo.json")["commitmentWithProof"]
                .as_str()
                .unwrap(),
        );
        let signer_nym_entropy = hex_decode(
            json("pseudonym/signerNymEntropy.json")["signerNymEntropyHex"]
                .as_str()
                .unwrap(),
        );

        let proof_value = create_pseudonym_base_proof_value(
            &json("pseudonym/license.json"),
            &json("pseudonym/addProofConfig.json"),
            &refs,
            &sk,
            &pk,
            &hmac_key,
            &commitment_with_proof,
            &signer_nym_entropy,
        )
        .unwrap();

        let expected = json("pseudonym/addSignedSDBase.json")["proof"]["proofValue"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(
            proof_value, expected,
            "end-to-end pseudonym base proof diverges from the W3C vc-di-bbs vector"
        );
    }

    fn pseudonym_pk() -> bbs::PublicKey {
        let pk_bytes: [u8; 96] = hex_decode(
            json("BBSKeyMaterial.json")["publicKeyHex"]
                .as_str()
                .unwrap(),
        )
        .try_into()
        .unwrap();
        bbs::PublicKey::from_bytes(&pk_bytes).unwrap()
    }

    const VERIFIER_ID: &str = "https://car.rental.verifier.example/";

    #[test]
    fn verify_pseudonym_derived_proof_accepts_w3c_reference() {
        // The strongest interop gate: our verifier accepts the W3C reference
        // pseudonym derived proof (0xd95d09) byte-for-byte.
        let reveal = json("pseudonym/derivedRevealDocument.json");
        assert!(
            verify_pseudonym_derived_proof(&reveal, &pseudonym_pk(), VERIFIER_ID).unwrap(),
            "failed to verify the W3C reference pseudonym derived proof"
        );
    }

    #[test]
    fn verify_pseudonym_derived_proof_rejects_wrong_verifier() {
        let reveal = json("pseudonym/derivedRevealDocument.json");
        // A different verifier id ⇒ different OP ⇒ pseudonym binding fails to
        // verify (returns false, or errors).
        assert!(
            !verify_pseudonym_derived_proof(&reveal, &pseudonym_pk(), "https://other.example/")
                .unwrap_or(false)
        );
    }

    #[test]
    fn pseudonym_derive_verify_round_trip() {
        let base_doc = json("pseudonym/addSignedSDBase.json");
        let pk = pseudonym_pk();
        let prover_nym = hex_decode(
            json("pseudonym/proverNym.json")["proverNymHex"]
                .as_str()
                .unwrap(),
        );
        let spb = hex_decode(
            json("pseudonym/commitmentInfo.json")["secretProverBlind"]
                .as_str()
                .unwrap(),
        );

        // Holder derives a presentation (disclosing only the issuer-mandatory
        // claims) bound to the verifier's pseudonym.
        let reveal = create_pseudonym_derived_proof(
            &base_doc,
            &[],
            b"test-ph",
            &pk,
            &prover_nym,
            &spb,
            VERIFIER_ID,
        )
        .unwrap();

        assert!(
            verify_pseudonym_derived_proof(&reveal, &pk, VERIFIER_ID).unwrap(),
            "round-trip pseudonym derived proof failed to verify"
        );

        // The pseudonym is deterministic (OP·nym_secret) and must match the W3C
        // vector regardless of the randomized BBS proof.
        let parsed =
            parse_pseudonym_derived_proof_value(reveal["proof"]["proofValue"].as_str().unwrap())
                .unwrap();
        assert_eq!(
            hex_lower(&parsed.pseudonym),
            json("pseudonym/derivedDisclosureData.json")["pseudonym"]
                .as_str()
                .unwrap(),
            "pseudonym diverges from the W3C vc-di-bbs vector"
        );

        // A presentation for a different verifier yields a different pseudonym.
        let reveal2 = create_pseudonym_derived_proof(
            &base_doc,
            &[],
            b"test-ph",
            &pk,
            &prover_nym,
            &spb,
            "https://other.example/",
        )
        .unwrap();
        let parsed2 =
            parse_pseudonym_derived_proof_value(reveal2["proof"]["proofValue"].as_str().unwrap())
                .unwrap();
        assert_ne!(
            parsed.pseudonym, parsed2.pseudonym,
            "pseudonyms must be per-verifier"
        );
    }

    #[test]
    fn verify_derived_proof_accepts_w3c_reference_proof() {
        let pk_bytes: [u8; 96] = hex_decode(
            json("BBSKeyMaterial.json")["publicKeyHex"]
                .as_str()
                .unwrap(),
        )
        .try_into()
        .unwrap();
        let pk = bbs::PublicKey::from_bytes(&pk_bytes).unwrap();

        let reveal = json("derivedRevealDocument.json");
        let ok = verify_derived_proof(&reveal, &pk).unwrap();
        assert!(ok, "must verify the reference-generated derived proof");
    }

    #[test]
    fn verify_derived_proof_rejects_tampered_claim() {
        let pk_bytes: [u8; 96] = hex_decode(
            json("BBSKeyMaterial.json")["publicKeyHex"]
                .as_str()
                .unwrap(),
        )
        .try_into()
        .unwrap();
        let pk = bbs::PublicKey::from_bytes(&pk_bytes).unwrap();

        let mut reveal = json("derivedRevealDocument.json");
        reveal["credentialSubject"]["sailNumber"] = Value::String("Tampered".into());
        let r = verify_derived_proof(&reveal, &pk);
        assert!(
            !matches!(r, Ok(true)),
            "tampered claim must not verify: {r:?}"
        );
    }

    #[test]
    fn create_derived_proof_matches_w3c_structure_and_round_trips() {
        let pk_bytes: [u8; 96] = hex_decode(
            json("BBSKeyMaterial.json")["publicKeyHex"]
                .as_str()
                .unwrap(),
        )
        .try_into()
        .unwrap();
        let pk = bbs::PublicKey::from_bytes(&pk_bytes).unwrap();
        let ph = hex_decode(
            json("BBSDeriveMaterial.json")["presentationHeaderHex"]
                .as_str()
                .unwrap(),
        );
        let selective: Vec<String> = serde_json::from_value(json("windSelective.json")).unwrap();
        let refs: Vec<&str> = selective.iter().map(String::as_str).collect();

        // Derive from the reference base-proof document.
        let reveal = create_derived_proof(&json("addSignedSDBase.json"), &refs, &ph, &pk).unwrap();

        // Round-trip: our own verifier accepts our derived proof.
        assert!(
            verify_derived_proof(&reveal, &pk).unwrap(),
            "round-trip derive→verify must hold"
        );

        // Structural match against the W3C disclosure-data vector (the BBS proof
        // bytes themselves are randomized, so we check the deterministic parts).
        let parsed =
            parse_derived_proof_value(reveal["proof"]["proofValue"].as_str().unwrap()).unwrap();
        let dd = json("derivedDisclosureData.json");

        let exp_label: BTreeMap<String, String> = dd["labelMap"]["value"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| {
                (
                    e[0].as_str().unwrap().to_string(),
                    e[1].as_str().unwrap().to_string(),
                )
            })
            .collect();
        assert_eq!(parsed.label_map, exp_label, "derived label map");

        let usizes = |v: &Value| -> Vec<usize> {
            v.as_array()
                .unwrap()
                .iter()
                .map(|x| x.as_u64().unwrap() as usize)
                .collect()
        };
        assert_eq!(
            parsed.mandatory_indexes,
            usizes(&dd["mandatoryIndexes"]),
            "adjusted mandatory indexes"
        );
        assert_eq!(
            parsed.selective_indexes,
            usizes(&dd["adjSelectiveIndexes"]),
            "adjusted selective indexes"
        );
        assert_eq!(parsed.presentation_header, ph, "presentation header");
    }

    #[test]
    fn end_to_end_sign_derive_verify_round_trip() {
        // Full document-level vc-di-bbs round trip with a fresh HMAC key and
        // arbitrary mandatory/selective pointers (not the vector's), exercising
        // issuer → holder → verifier entirely through our own code.
        let km = json("BBSKeyMaterial.json");
        let sk = bbs::SecretKey::from_bytes(
            &hex_decode(km["privateKeyHex"].as_str().unwrap())
                .try_into()
                .unwrap(),
        )
        .unwrap();
        let pk = bbs::PublicKey::from_bytes(
            &hex_decode(km["publicKeyHex"].as_str().unwrap())
                .try_into()
                .unwrap(),
        )
        .unwrap();
        let hmac_key = [0x42u8; 32];

        let doc = json("windDoc.json");
        let mandatory = ["/issuer", "/credentialSubject/sailNumber"];
        let base = sign_base_document(
            &doc,
            &mandatory,
            "did:key:zHolder#bbs",
            "2024-01-01T00:00:00Z",
            &sk,
            &pk,
            &hmac_key,
        )
        .unwrap();
        assert_eq!(base["proof"]["cryptosuite"], "bbs-2023");

        // Holder discloses one board selectively.
        let reveal =
            create_derived_proof(&base, &["/credentialSubject/boards/0"], b"nonce-xyz", &pk)
                .unwrap();

        // Verifier accepts; mandatory + disclosed present, others hidden.
        assert!(verify_derived_proof(&reveal, &pk).unwrap());
        let cs = &reveal["credentialSubject"];
        assert_eq!(cs["sailNumber"], "Earth101"); // mandatory
        assert!(
            cs["boards"].as_array().unwrap()[0]
                .get("boardName")
                .is_some()
        ); // disclosed
        assert!(
            cs.get("sails").is_none(),
            "undisclosed sails must be absent"
        );

        // Tampering with a disclosed claim fails.
        let mut bad = reveal.clone();
        bad["credentialSubject"]["sailNumber"] = Value::String("Mallory".into());
        assert!(!matches!(verify_derived_proof(&bad, &pk), Ok(true)));
    }

    fn hex_lower(b: &[u8]) -> String {
        b.iter().map(|x| format!("{x:02x}")).collect()
    }

    fn hex_decode(s: &str) -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }
}