vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
//! did:webvh v1.0 resolution, offline (DIF did:webvh v1.0,
//! identity.foundation/didwebvh/v1.0).
//!
//! A did:webvh DID looks like a did:web DID with one extra part, the SCID:
//!
//! ```text
//! did:webvh:QmXhVjFG6EBTosDastaaHMRypm2qSv4SMGctADsx878Yux:example.com
//! ```
//!
//! Its DID document is not one file. It is a log (`did.jsonl`), one signed
//! entry per version, each entry chained to the one before by a hash. The SCID
//! is a hash of the first entry, so the DID itself commits to where its
//! history starts. A resolver reads every entry, checks every hash and
//! signature, and uses the last entry's `state` as the DID document.
//!
//! This is a port of the Python reference (`vouch/did_webvh.py`), and every
//! rule, error code and fixed text is the same. The shared cases are in
//! `test-vectors/did-webvh/vector.json`. The core never fetches: the caller
//! fetches `did.jsonl` from [`log_url`] (https only, no redirects, a size cap,
//! public addresses only) and hands the bytes to [`verify_log`].
//!
//! What is refused, explicitly: witnesses (`unsupported`), a DID that moves
//! (`unsupported`), other method versions (`unsupported`), U-label domains
//! (`unsupported`), DID URLs (`unsupported`), a deactivated DID
//! (`deactivated`), and `null` parameters (`invalidDid`). Watchers are
//! reported in the metadata and never contacted. A did:webvh DID is never
//! treated as the did:web DID at the same location.
//!
//! The order of the checks decides which error a log with several problems
//! reports, so it is the same in every language:
//!
//! 1. The bytes: the size limit, no byte order mark, UTF-8, then the lines
//!    (split on `\n`; one final newline is allowed, no blank line, at most
//!    `max_entries` lines, each at most `max_line_bytes`). Each line, in
//!    order, must be one JSON object: no CRLF, nesting at most 64 levels, no
//!    repeated member name, no number outside +/-(2^53 - 1), no lone
//!    surrogate; exactly the members versionId, versionTime, parameters,
//!    state and proof, of the right types; `proof` a non-empty list of at
//!    most `max_proofs` objects. All lines are read before any entry is
//!    verified.
//! 2. Then each entry, in order: no entry after a deactivated one, or after
//!    `updateKeys` was emptied when pre-rotation is off; the versionId; the
//!    versionTime; the parameters; the pre-rotation commitment; the SCID; the
//!    entry hash; every proof, in order; the state's id.
//! 3. Then the log as a whole: some entry's `state.id` is the DID; the
//!    version seen before is still in the log; the version query; and last,
//!    that the selected version is not the deactivated one.
//!
//! Any failure refuses the whole log. Log proofs are checked with
//! [`crate::data_integrity::hash_data`] and strict Ed25519, never with
//! [`crate::data_integrity::verify_proof`], which also accepts an older
//! signing input.
//!
//! Limits may be lowered, never raised past the reference's caps: 5 MiB, 1000
//! entries, 4 proofs per entry, 32 update keys and 32 next-key hashes.
//!
//! For credential verification ([`crate::credentials::verify_with_did_webvh_log`],
//! and grant issuers in a delegation chain through
//! [`crate::delegation::ChainOptions::grant_logs`]), the caller hands the
//! fetched logs over in a [`LogSet`]. Those logs are checked against the
//! system clock ([`LogClock`]), as the reference resolves them, never against
//! the time the credential is checked at; a fixed log clock is for tests and
//! replays. The core keeps no record of the versions seen: the caller gives
//! the version it saw before for each DID and keeps the latest one the set
//! reports.
//!
//! serde_json keeps the last of two members with the same name, so the log
//! lines are read here by a small reader of their own that refuses a repeated
//! name, a number outside +/-(2^53 - 1) and a lone surrogate, in the same
//! order as the reference's reader.

use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::fmt;

use serde_json::{json, Map, Number, Value};
use sha2::{Digest, Sha256};

use crate::error::{CoreError, Result};
use crate::{jcs, keys, multikey, time};

/// Every did:webvh DID starts with this (the trailing colon included, so a
/// did:web DID never matches it, nor it a did:web prefix check).
pub const PREFIX: &str = "did:webvh:";
/// The one method version this resolver reads.
pub const METHOD: &str = "did:webvh:1.0";
const CRYPTOSUITE: &str = "eddsa-jcs-2022";
const PROOF_TYPE: &str = "DataIntegrityProof";
const PROOF_PURPOSE: &str = "assertionMethod";
const SCID_PLACEHOLDER: &str = "{SCID}";
/// How far ahead of the resolver's clock a versionTime may be, in seconds.
pub const MAX_FUTURE_SECONDS: i64 = 300;
/// The ttl when a log sets none, in seconds.
pub const DEFAULT_TTL: i64 = 3600;
/// The largest ttl, in seconds.
pub const MAX_TTL: i64 = 1 << 31;
/// The largest number every reader holds exactly (JavaScript and Go read JSON
/// numbers as doubles), so a log hashes to the same bytes in every language.
pub const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
/// The largest log any caller may allow (5 MiB).
pub const HARD_MAX_BYTES: usize = 5 * 1024 * 1024;
/// The most entries any caller may allow. Every proof hashes its entry's
/// proof options and every entry is hashed a few times, so this and the three
/// counts below bound the work one log can ask for.
pub const HARD_MAX_ENTRIES: usize = 1000;
/// The most proofs on one entry any caller may allow.
pub const HARD_MAX_PROOFS: usize = 4;
/// The most keys in one `updateKeys` any caller may allow.
pub const HARD_MAX_UPDATE_KEYS: usize = 32;
/// The most hashes in one `nextKeyHashes` any caller may allow.
pub const HARD_MAX_NEXT_KEY_HASHES: usize = 32;
/// How deeply one log line may nest objects and lists.
pub const MAX_LOG_DEPTH: usize = 64;

/// The DID or its log is not valid.
pub const INVALID_DID: &str = "invalidDid";
/// No log, or no version matching a query.
pub const NOT_FOUND: &str = "notFound";
/// A did:webvh feature this resolver does not support.
pub const UNSUPPORTED: &str = "unsupported";
/// The selected version is the deactivated one.
pub const DEACTIVATED: &str = "deactivated";
/// A size or count limit.
pub const TOO_LARGE: &str = "tooLarge";
/// Fetching took too long (the caller's fetch reports it).
pub const TIMEOUT: &str = "timeout";
/// The log could not be fetched (the caller's fetch reports it).
pub const FETCH_FAILED: &str = "fetchFailed";

/// A did:webvh DID, log or resolution was refused: a stable code, a fixed
/// text, and the 1-based log line the problem is in when there is one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DidWebvhError {
    /// One of the error codes above.
    pub code: &'static str,
    /// The fixed text.
    pub text: &'static str,
    /// The 1-based log line, or None.
    pub entry: Option<usize>,
    /// For `deactivated`, the versionId of the log's last entry (the log
    /// itself verified), so a caller can record it; otherwise None.
    pub latest_version_id: Option<String>,
}

impl DidWebvhError {
    fn new(code: &'static str, text: &'static str) -> Self {
        Self {
            code,
            text,
            entry: None,
            latest_version_id: None,
        }
    }

    fn at(code: &'static str, text: &'static str, entry: usize) -> Self {
        Self {
            code,
            text,
            entry: Some(entry),
            latest_version_id: None,
        }
    }

    /// `{"code": ..., "text": ..., "entry": n or null}`. The JSON stays the
    /// shape the shared vectors fix; `latest_version_id` is on the type only.
    pub fn to_json(&self) -> Value {
        json!({"code": self.code, "text": self.text, "entry": self.entry})
    }
}

impl fmt::Display for DidWebvhError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.text)
    }
}

impl std::error::Error for DidWebvhError {}

/// A result whose error is a did:webvh refusal.
pub type Refusal<T> = std::result::Result<T, DidWebvhError>;

fn invalid(text: &'static str) -> DidWebvhError {
    DidWebvhError::new(INVALID_DID, text)
}

// =============================================================================
// The DID: syntax and the DID-to-HTTPS transformation (spec 3.3, 3.4)
// =============================================================================

/// A did:webvh DID, split into its parts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DidWebvh {
    /// The DID, exactly as given.
    pub did: String,
    /// The 46-character SCID.
    pub scid: String,
    /// The domain, percent-decoded once and lower-cased (the A-label form a
    /// TLS certificate names).
    pub host: String,
    /// The port, or None.
    pub port: Option<u16>,
    /// The path segments, each percent-decoded once.
    pub path: Vec<String>,
}

impl DidWebvh {
    /// The HTTPS URL of the DID's log (spec 3.4):
    /// `https://{host}[:{port}]/{path}/did.jsonl`, or
    /// `https://{host}[:{port}]/.well-known/did.jsonl` with no path. Each path
    /// segment is encoded again with uppercase hex.
    pub fn log_url(&self) -> String {
        let authority = match self.port {
            Some(port) => format!("{}:{port}", self.host),
            None => self.host.clone(),
        };
        if self.path.is_empty() {
            return format!("https://{authority}/.well-known/did.jsonl");
        }
        let path: Vec<String> = self.path.iter().map(|s| encode_segment(s)).collect();
        format!("https://{authority}/{}/did.jsonl", path.join("/"))
    }

    /// `{"scid", "host", "port", "path", "url"}`.
    pub fn to_json(&self) -> Value {
        json!({
            "scid": self.scid,
            "host": self.host,
            "port": self.port,
            "path": self.path,
            "url": self.log_url(),
        })
    }
}

fn is_base58_char(c: u8) -> bool {
    matches!(c, b'1'..=b'9' | b'A'..=b'H' | b'J'..=b'N' | b'P'..=b'Z' | b'a'..=b'k' | b'm'..=b'z')
}

fn is_scid(text: &str) -> bool {
    text.len() == 46 && text.bytes().all(is_base58_char)
}

/// One or more of the characters `allowed` lets through or `%XX` escapes.
fn escaped_chars_ok(text: &str, allowed: impl Fn(u8) -> bool) -> bool {
    let b = text.as_bytes();
    if b.is_empty() {
        return false;
    }
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let hex = |j: usize| b.get(j).is_some_and(u8::is_ascii_hexdigit);
            if !(hex(i + 1) && hex(i + 2)) {
                return false;
            }
            i += 3;
        } else if allowed(b[i]) {
            i += 1;
        } else {
            return false;
        }
    }
    true
}

/// Percent-decode `text` exactly once (every `%` already starts a valid
/// two-digit escape).
fn decode_once(text: &str) -> Vec<u8> {
    let b = text.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let hi = (b[i + 1] as char).to_digit(16).unwrap_or(0) as u8;
            let lo = (b[i + 2] as char).to_digit(16).unwrap_or(0) as u8;
            out.push(hi * 16 + lo);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    out
}

/// Unicode White_Space, written out so every language uses the same set.
fn is_listed_whitespace(c: char) -> bool {
    matches!(
        c,
        '\u{09}'..='\u{0D}'
            | ' '
            | '\u{85}'
            | '\u{A0}'
            | '\u{1680}'
            | '\u{2000}'..='\u{200A}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{202F}'
            | '\u{205F}'
            | '\u{3000}'
    )
}

/// The host and port of the domain component (spec 3.3, "webvh-domain").
fn parse_domain(component: &str) -> Refusal<(String, Option<u16>)> {
    if !escaped_chars_ok(component, |c| {
        c.is_ascii_alphanumeric() || c == b'.' || c == b'-'
    }) {
        return Err(invalid(
            "the domain holds a character a did:webvh domain cannot",
        ));
    }
    let b = component.as_bytes();
    let mut colons = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            if b[i + 1..i + 3].eq_ignore_ascii_case(b"3a") {
                colons.push(i);
            }
            i += 3;
        } else {
            i += 1;
        }
    }
    if colons.len() > 1 {
        return Err(invalid("the domain has more than one port separator"));
    }
    let mut host_part = component;
    let mut port = None;
    if let Some(&at) = colons.first() {
        let port_text = &component[at + 3..];
        if port_text.is_empty() || !port_text.bytes().all(|c| c.is_ascii_digit()) {
            return Err(invalid(
                "a percent-encoded colon may only come before the port",
            ));
        }
        let value: u32 = if port_text.len() <= 5 && !port_text.starts_with('0') {
            port_text.parse().unwrap_or(u32::MAX)
        } else {
            u32::MAX
        };
        if value > 65535 {
            return Err(invalid("the port must be 1 to 65535, with no leading zero"));
        }
        port = Some(value as u16);
        host_part = &component[..at];
    }
    if host_part.split('.').any(str::is_empty) {
        return Err(invalid("a did:webvh domain label is empty"));
    }
    if host_part.split('.').count() < 2 {
        return Err(invalid("a did:webvh domain needs at least two labels"));
    }
    let decoded = decode_once(host_part);
    if decoded.iter().any(|c| *c >= 0x80) {
        if std::str::from_utf8(&decoded).is_err() {
            return Err(invalid("the domain does not decode to UTF-8 text"));
        }
        return Err(DidWebvhError::new(
            UNSUPPORTED,
            "internationalized domains must be written in their A-label (xn--) form",
        ));
    }
    // ASCII, so this never fails.
    let host = String::from_utf8(decoded).unwrap_or_default();
    let labels: Vec<&str> = host.split('.').collect();
    if labels.iter().any(|l| l.is_empty()) {
        return Err(invalid("a did:webvh domain label is empty"));
    }
    if !labels.iter().all(|l| crate::did_web::is_ldh_label(l)) {
        return Err(invalid(
            "a domain label must be 1 to 63 letters, digits or hyphens, \
             not starting or ending with a hyphen",
        ));
    }
    if host.len() > 253 {
        return Err(invalid("the domain is longer than 253 characters"));
    }
    let last = labels[labels.len() - 1];
    let hex_label = last.len() >= 2
        && (last.starts_with("0x") || last.starts_with("0X"))
        && last[2..].bytes().all(|c| c.is_ascii_hexdigit());
    if last.bytes().all(|c| c.is_ascii_digit())
        || hex_label
        || crate::did_web::is_inet_aton_address(&host)
    {
        return Err(invalid("the domain is an IP address, not a domain name"));
    }
    if last.eq_ignore_ascii_case("localhost") {
        return Err(invalid("localhost is not a did:webvh domain"));
    }
    Ok((host.to_ascii_lowercase(), port))
}

/// One path segment, percent-decoded once (spec 3.3, "webvh-path-segment").
fn parse_segment(segment: &str) -> Refusal<String> {
    if segment.is_empty() {
        return Err(invalid("a did:webvh path segment is empty"));
    }
    if !escaped_chars_ok(segment, |c| {
        c.is_ascii_alphanumeric() || c == b'.' || c == b'_' || c == b'-'
    }) {
        return Err(invalid(
            "a did:webvh path segment holds a character it cannot",
        ));
    }
    let decoded = String::from_utf8(decode_once(segment))
        .map_err(|_| invalid("a did:webvh path segment does not decode to UTF-8 text"))?;
    if decoded == "." || decoded == ".." {
        return Err(invalid("a did:webvh path segment is . or .."));
    }
    if decoded
        .chars()
        .any(|c| c == '/' || c == '\\' || (c as u32) < 0x20 || c as u32 == 0x7F)
    {
        return Err(invalid(
            "a did:webvh path segment holds /, \\ or a control character",
        ));
    }
    let first = decoded.chars().next().unwrap_or('x');
    let last = decoded.chars().next_back().unwrap_or('x');
    if is_listed_whitespace(first) || is_listed_whitespace(last) {
        return Err(invalid(
            "a did:webvh path segment begins or ends with whitespace",
        ));
    }
    Ok(decoded)
}

/// Split a did:webvh DID into its parts, strictly (spec 3.3).
///
/// The rules, all checked before anything is fetched:
///
/// - the DID starts with `did:webvh:`; the SCID is exactly 46 base58btc
///   characters (so the `{SCID}` placeholder never parses);
/// - the domain is letters, digits, hyphens, dots and `%XX` escapes. A `%3A`
///   (either case) followed by 1 to 5 digits at its end is the port, 1 to
///   65535 with no leading zero; any other `%3A` is refused. It is
///   percent-decoded once, must be ASCII (a U-label is `unsupported`), and
///   must then be two or more LDH labels of 1 to 63 characters, at most 253
///   characters in all, not an IP address in any form `inet_aton` or a URL
///   parser reads, and not `localhost` or a name under it;
/// - every path segment is letters, digits, `.`, `-`, `_` and `%XX` escapes,
///   decoded once to UTF-8 text that is not `.` or `..`, holds no `/`, `\`
///   or control character, and does not begin or end with whitespace;
/// - a DID URL (anything after `/`, `?` or `#`) is refused as `unsupported`,
///   after the DID before it has been checked.
pub fn parse(did: &str) -> Refusal<DidWebvh> {
    if !did.starts_with(PREFIX) {
        return Err(invalid("not a did:webvh DID"));
    }
    let cut = did.find(['/', '?', '#']).unwrap_or(did.len());
    let (bare, suffix) = did.split_at(cut);
    let parts: Vec<&str> = bare[PREFIX.len()..].split(':').collect();
    if !is_scid(parts[0]) {
        return Err(invalid("the SCID is not 46 base58btc characters"));
    }
    if parts.len() < 2 {
        return Err(invalid("a did:webvh DID needs a domain after the SCID"));
    }
    let (host, port) = parse_domain(parts[1])?;
    let path = parts[2..]
        .iter()
        .map(|s| parse_segment(s))
        .collect::<Refusal<Vec<String>>>()?;
    if !suffix.is_empty() {
        return Err(DidWebvhError::new(
            UNSUPPORTED,
            "did:webvh DID URLs (a path, query or fragment) are not supported",
        ));
    }
    Ok(DidWebvh {
        did: bare.to_string(),
        scid: parts[0].to_string(),
        host,
        port,
        path,
    })
}

/// True when `did` starts with `did:webvh:`.
pub fn is_did_webvh(did: &str) -> bool {
    did.starts_with(PREFIX)
}

/// Percent-encode a decoded path segment for a URL (RFC 3986): unreserved
/// characters stay as they are, every other byte becomes uppercase `%XX`.
fn encode_segment(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len());
    for b in segment.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

/// The HTTPS URL of a did:webvh DID's log (spec 3.4); see
/// [`DidWebvh::log_url`].
pub fn log_url(did: &str) -> Refusal<String> {
    Ok(parse(did)?.log_url())
}

// =============================================================================
// Limits, options and results
// =============================================================================

/// Size and count limits for one log. Each may be lowered; none may be
/// raised past its default, except `max_bytes`, which goes up to 5 MiB.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
    max_bytes: usize,
    max_entries: usize,
    max_line_bytes: usize,
    max_proofs: usize,
    max_update_keys: usize,
    max_next_key_hashes: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_bytes: 1024 * 1024,
            max_entries: 1000,
            max_line_bytes: 128 * 1024,
            max_proofs: 4,
            max_update_keys: 32,
            max_next_key_hashes: 32,
        }
    }
}

const LIMIT_NAMES: [&str; 6] = [
    "maxBytes",
    "maxEntries",
    "maxLineBytes",
    "maxProofs",
    "maxUpdateKeys",
    "maxNextKeyHashes",
];

impl Limits {
    /// Limits with every value given: each at least 1, `max_bytes` at most
    /// 5 MiB, `max_entries` at most 1000, `max_proofs` at most 4, and
    /// `max_update_keys` and `max_next_key_hashes` at most 32.
    pub fn new(
        max_bytes: usize,
        max_entries: usize,
        max_line_bytes: usize,
        max_proofs: usize,
        max_update_keys: usize,
        max_next_key_hashes: usize,
    ) -> Result<Self> {
        let values = [
            max_bytes,
            max_entries,
            max_line_bytes,
            max_proofs,
            max_update_keys,
            max_next_key_hashes,
        ];
        for (name, value) in LIMIT_NAMES.iter().zip(values) {
            if value < 1 {
                return Err(CoreError::Json(format!(
                    "{name} must be a positive whole number"
                )));
            }
        }
        if max_bytes > HARD_MAX_BYTES {
            return Err(CoreError::Json(format!(
                "maxBytes may be at most {HARD_MAX_BYTES} (5 MiB)"
            )));
        }
        for (name, value, most) in [
            ("maxEntries", max_entries, HARD_MAX_ENTRIES),
            ("maxProofs", max_proofs, HARD_MAX_PROOFS),
            ("maxUpdateKeys", max_update_keys, HARD_MAX_UPDATE_KEYS),
            (
                "maxNextKeyHashes",
                max_next_key_hashes,
                HARD_MAX_NEXT_KEY_HASHES,
            ),
        ] {
            if value > most {
                return Err(CoreError::Json(format!("{name} may be at most {most}")));
            }
        }
        Ok(Self {
            max_bytes,
            max_entries,
            max_line_bytes,
            max_proofs,
            max_update_keys,
            max_next_key_hashes,
        })
    }

    /// Limits from a JSON object with any of `maxBytes`, `maxEntries`,
    /// `maxLineBytes`, `maxProofs`, `maxUpdateKeys` and `maxNextKeyHashes`;
    /// the rest keep their defaults.
    pub fn from_json(value: &Value) -> Result<Self> {
        let obj = value
            .as_object()
            .ok_or_else(|| CoreError::Json("limits must be a JSON object".into()))?;
        if let Some(name) = obj.keys().find(|k| !LIMIT_NAMES.contains(&k.as_str())) {
            return Err(CoreError::Json(format!(
                "limits holds an unknown member {:?}",
                name.chars().take(40).collect::<String>()
            )));
        }
        let d = Self::default();
        let defaults = [
            d.max_bytes,
            d.max_entries,
            d.max_line_bytes,
            d.max_proofs,
            d.max_update_keys,
            d.max_next_key_hashes,
        ];
        let mut values = [0usize; 6];
        for (i, name) in LIMIT_NAMES.iter().enumerate() {
            values[i] = match obj.get(*name) {
                None => defaults[i],
                Some(v) => v
                    .as_u64()
                    .and_then(|n| usize::try_from(n).ok())
                    .filter(|n| *n >= 1)
                    .ok_or_else(|| {
                        CoreError::Json(format!("{name} must be a positive whole number"))
                    })?,
            };
        }
        Self::new(
            values[0], values[1], values[2], values[3], values[4], values[5],
        )
    }

    /// The largest log, in bytes.
    pub fn max_bytes(&self) -> usize {
        self.max_bytes
    }
    /// The most entries.
    pub fn max_entries(&self) -> usize {
        self.max_entries
    }
    /// The longest line, in bytes, without its newline.
    pub fn max_line_bytes(&self) -> usize {
        self.max_line_bytes
    }
    /// The most proofs on one entry.
    pub fn max_proofs(&self) -> usize {
        self.max_proofs
    }
    /// The most keys in one `updateKeys`.
    pub fn max_update_keys(&self) -> usize {
        self.max_update_keys
    }
    /// The most hashes in one `nextKeyHashes`.
    pub fn max_next_key_hashes(&self) -> usize {
        self.max_next_key_hashes
    }
}

/// Which version of the log to resolve.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Query {
    /// The last entry (what credential verification always uses).
    #[default]
    Latest,
    /// The entry with exactly this versionId.
    VersionId(String),
    /// The entry active at this protocol time: the last entry whose
    /// versionTime is at or before it.
    VersionTime(String),
    /// The entry with this version number (1 is the first).
    VersionNumber(i64),
}

/// The options for [`verify_log`]: a version query, the versionId seen
/// before for this DID, and the limits.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VerifyOptions {
    query: Query,
    seen_version_id: Option<String>,
    limits: Limits,
}

/// The version number of a versionId ("3-Qm..." is 3), when it has one.
fn version_number_of(version_id: &str) -> Option<usize> {
    let (head, _) = version_id.split_once('-')?;
    let b = head.as_bytes();
    if b.is_empty() || b.len() > 9 || !(b'1'..=b'9').contains(&b[0]) {
        return None;
    }
    if !b.iter().all(u8::is_ascii_digit) {
        return None;
    }
    head.parse().ok()
}

impl VerifyOptions {
    /// The latest version, no version seen before, default limits.
    pub fn new() -> Self {
        Self::default()
    }

    /// Resolve the version `query` names.
    pub fn with_query(mut self, query: Query) -> Self {
        self.query = query;
        self
    }

    /// Use these limits.
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// The latest versionId seen for this DID before. The log must still
    /// contain it, so a log rolled back or forked since is refused.
    ///
    /// Errors when `seen` is not a did:webvh versionId.
    pub fn with_seen_version_id(mut self, seen: &str) -> Result<Self> {
        if version_number_of(seen).is_none() {
            return Err(seen_version_id_error());
        }
        self.seen_version_id = Some(seen.to_string());
        Ok(self)
    }

    /// The version query.
    pub fn query(&self) -> &Query {
        &self.query
    }
    /// The versionId seen before, if any.
    pub fn seen_version_id(&self) -> Option<&str> {
        self.seen_version_id.as_deref()
    }
    /// The limits.
    pub fn limits(&self) -> &Limits {
        &self.limits
    }

    /// Options from a JSON object with at most one of `versionId` (a
    /// string), `versionTime` (a string) and `versionNumber` (a whole
    /// number), and optionally `seenVersionId` and `limits` (see
    /// [`Limits::from_json`]). A null member counts as absent.
    pub fn from_json(value: &Value) -> Result<Self> {
        let obj = value
            .as_object()
            .ok_or_else(|| CoreError::Json("options must be a JSON object".into()))?;
        let (query, seen) = read_query(obj)?;
        let mut options = Self::new().with_query(query);
        if let Some(seen) = seen {
            options = options.with_seen_version_id(&seen)?;
        }
        if let Some(v) = obj.get("limits").filter(|v| !v.is_null()) {
            options.limits = Limits::from_json(v)?;
        }
        Ok(options)
    }
}

/// The query and the version seen before in an options object, read in the
/// reference's order: unknown members, at most one query, then each type. A
/// null member counts as absent. The seen versionId is only checked to be
/// text here; whether it is a versionId is checked by the caller.
fn read_query(obj: &Map<String, Value>) -> Result<(Query, Option<String>)> {
    const NAMES: [&str; 5] = [
        "versionId",
        "versionTime",
        "versionNumber",
        "seenVersionId",
        "limits",
    ];
    if let Some(name) = obj.keys().find(|k| !NAMES.contains(&k.as_str())) {
        return Err(CoreError::Json(format!(
            "options holds an unknown member {:?}",
            name.chars().take(40).collect::<String>()
        )));
    }
    let present = |name: &str| obj.get(name).filter(|v| !v.is_null());
    let queries = ["versionId", "versionTime", "versionNumber"]
        .iter()
        .filter(|n| present(n).is_some())
        .count();
    if queries > 1 {
        return Err(CoreError::Json(
            "give at most one of versionId, versionTime and versionNumber".into(),
        ));
    }
    let text = |name: &str, v: &Value| {
        v.as_str()
            .map(str::to_string)
            .ok_or_else(|| CoreError::Json(format!("{name} must be a string")))
    };
    let mut query = Query::Latest;
    if let Some(v) = present("versionId") {
        query = Query::VersionId(text("versionId", v)?);
    }
    if let Some(v) = present("versionTime") {
        query = Query::VersionTime(text("versionTime", v)?);
    }
    if let Some(v) = present("versionNumber") {
        let n = match v {
            Value::Number(n) if n.is_i64() => n.as_i64().unwrap_or(i64::MAX),
            // A whole number beyond i64 names no entry either way.
            Value::Number(n) if n.is_u64() => i64::MAX,
            _ => {
                return Err(CoreError::Json(
                    "versionNumber must be a whole number".into(),
                ))
            }
        };
        query = Query::VersionNumber(n);
    }
    let seen = match present("seenVersionId") {
        Some(v) => Some(text("seenVersionId", v)?),
        None => None,
    };
    Ok((query, seen))
}

fn seen_version_id_error() -> CoreError {
    CoreError::Json("seenVersionId is not a did:webvh versionId".into())
}

/// A verified did:webvh log, resolved to one version.
#[derive(Debug, Clone, PartialEq)]
pub struct Resolution {
    /// The selected entry's `state`, exactly as the log holds it: the DID
    /// document. Its `id` is exactly the DID.
    pub document: Value,
    /// The DID document metadata (spec 3.6.2): `versionId`, `versionTime`
    /// (of the selected entry), `created` and `updated` (the first and last
    /// entries' times), `scid`, `portable`, `deactivated`, `ttl` (a string),
    /// `witness` and `watchers` (active after the last entry).
    pub metadata: Value,
    /// The selected entry's version number.
    pub version_number: usize,
    /// The versionId of the log's last entry, to remember so a later,
    /// shorter log can be refused.
    pub latest_version_id: String,
}

impl Resolution {
    /// `{"document", "metadata", "versionNumber", "latestVersionId"}`.
    pub fn to_json(&self) -> Value {
        json!({
            "document": self.document,
            "metadata": self.metadata,
            "versionNumber": self.version_number,
            "latestVersionId": self.latest_version_id,
        })
    }
}

// =============================================================================
// Reading the log (step 1 of the check order)
// =============================================================================

const ENTRY_MEMBERS: [&str; 5] = ["versionId", "versionTime", "parameters", "state", "proof"];
const PROOF_MEMBERS: [&str; 6] = [
    "type",
    "cryptosuite",
    "verificationMethod",
    "created",
    "proofPurpose",
    "proofValue",
];
const PROOF_REQUIRED: [&str; 5] = [
    "type",
    "cryptosuite",
    "verificationMethod",
    "proofPurpose",
    "proofValue",
];
const PARAMETERS: [&str; 9] = [
    "method",
    "scid",
    "updateKeys",
    "nextKeyHashes",
    "witness",
    "watchers",
    "portable",
    "deactivated",
    "ttl",
];

/// Whether JSON text nests objects and lists more than `limit` deep: one scan
/// of the raw bytes, before parsing. Every `[` or `{` outside a string adds a
/// level and every `]` or `}` takes one away (escapes inside strings are
/// honoured, and a string with no closing quote runs to the end), so the
/// answer does not depend on what else is wrong with the text.
fn json_too_deep(text: &[u8], limit: usize) -> bool {
    let mut depth: i64 = 0;
    let mut i = 0;
    while i < text.len() {
        match text[i] {
            b'"' => {
                i += 1;
                while i < text.len() {
                    match text[i] {
                        b'"' => {
                            i += 1;
                            break;
                        }
                        b'\\' if i + 1 < text.len() => i += 2,
                        b'\\' => break,
                        _ => i += 1,
                    }
                }
                continue;
            }
            b'[' | b'{' => {
                depth += 1;
                if depth > limit as i64 {
                    return true;
                }
            }
            b']' | b'}' => depth -= 1,
            _ => {}
        }
        i += 1;
    }
    false
}

/// Why a log line could not be read as JSON.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum JsonProblem {
    Repeated,
    OutOfRange,
    Invalid,
}

/// A guard for the reader's recursion; the bracket scan keeps every line it
/// reads far below it.
const MAX_READER_DEPTH: usize = 256;

/// A strict JSON reader for one log line. It reads the same grammar as
/// Python's `json` module (the reference's reader) and reports a problem at
/// the same point: a number when it is read, a repeated member name when its
/// object closes, anything else not JSON where it occurs. A lone surrogate is
/// remembered and reported by the caller after the whole line is read.
struct LineReader<'a> {
    b: &'a [u8],
    i: usize,
    lone_surrogate: bool,
}

impl<'a> LineReader<'a> {
    fn skip_ws(&mut self) {
        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\n' | b'\r') {
            self.i += 1;
        }
    }

    fn peek(&self) -> Option<u8> {
        self.b.get(self.i).copied()
    }

    fn literal(&mut self, word: &[u8], value: Value) -> std::result::Result<Value, JsonProblem> {
        if self.b[self.i..].starts_with(word) {
            self.i += word.len();
            Ok(value)
        } else {
            Err(JsonProblem::Invalid)
        }
    }

    fn value(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
        if depth > MAX_READER_DEPTH {
            return Err(JsonProblem::Invalid);
        }
        match self.peek() {
            Some(b'"') => {
                self.i += 1;
                Ok(Value::String(self.string()?.0))
            }
            Some(b'{') => self.object(depth + 1),
            Some(b'[') => self.array(depth + 1),
            Some(b'n') => self.literal(b"null", Value::Null),
            Some(b't') => self.literal(b"true", Value::Bool(true)),
            Some(b'f') => self.literal(b"false", Value::Bool(false)),
            Some(_) => self.number(),
            None => Err(JsonProblem::Invalid),
        }
    }

    fn object(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
        self.i += 1; // '{'
        let mut map = Map::new();
        let mut names: HashSet<Vec<u16>> = HashSet::new();
        let mut repeated = false;
        self.skip_ws();
        if self.peek() == Some(b'}') {
            self.i += 1;
            return Ok(Value::Object(map));
        }
        loop {
            if self.peek() != Some(b'"') {
                return Err(JsonProblem::Invalid);
            }
            self.i += 1;
            let (name, units) = self.string()?;
            self.skip_ws();
            if self.peek() != Some(b':') {
                return Err(JsonProblem::Invalid);
            }
            self.i += 1;
            self.skip_ws();
            let value = self.value(depth)?;
            if !names.insert(units) {
                repeated = true;
            }
            map.insert(name, value);
            self.skip_ws();
            match self.peek() {
                Some(b'}') => {
                    self.i += 1;
                    break;
                }
                Some(b',') => {
                    self.i += 1;
                    self.skip_ws();
                }
                _ => return Err(JsonProblem::Invalid),
            }
        }
        // The reference checks member names when the object closes.
        if repeated {
            return Err(JsonProblem::Repeated);
        }
        Ok(Value::Object(map))
    }

    fn array(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
        self.i += 1; // '['
        let mut items = Vec::new();
        self.skip_ws();
        if self.peek() == Some(b']') {
            self.i += 1;
            return Ok(Value::Array(items));
        }
        loop {
            items.push(self.value(depth)?);
            self.skip_ws();
            match self.peek() {
                Some(b']') => {
                    self.i += 1;
                    break;
                }
                Some(b',') => {
                    self.i += 1;
                    self.skip_ws();
                }
                _ => return Err(JsonProblem::Invalid),
            }
        }
        Ok(Value::Array(items))
    }

    /// A number, matched the way Python's scanner matches one (an integer
    /// part, then a fraction only when a digit follows the dot, then an
    /// exponent only when it has digits), and range-checked at once.
    fn number(&mut self) -> std::result::Result<Value, JsonProblem> {
        let b = self.b;
        let n = b.len();
        let start = self.i;
        let mut i = start;
        let digit = |j: usize| j < n && b[j].is_ascii_digit();
        if b[i] == b'-' {
            i += 1;
            if i >= n {
                return Err(JsonProblem::Invalid);
            }
        }
        match b[i] {
            b'1'..=b'9' => {
                i += 1;
                while digit(i) {
                    i += 1;
                }
            }
            b'0' => i += 1,
            _ => return Err(JsonProblem::Invalid),
        }
        let mut is_float = false;
        if i + 1 < n && b[i] == b'.' && b[i + 1].is_ascii_digit() {
            is_float = true;
            i += 2;
            while digit(i) {
                i += 1;
            }
        }
        if i + 1 < n && (b[i] == b'e' || b[i] == b'E') {
            let e_start = i;
            i += 1;
            if i + 1 < n && (b[i] == b'-' || b[i] == b'+') {
                i += 1;
            }
            let digits_start = i;
            while digit(i) {
                i += 1;
            }
            if i > digits_start {
                is_float = true;
            } else {
                i = e_start;
            }
        }
        self.i = i;
        // ASCII digits and signs only.
        let text = std::str::from_utf8(&b[start..i]).map_err(|_| JsonProblem::Invalid)?;
        if is_float {
            let value: f64 = text.parse().map_err(|_| JsonProblem::Invalid)?;
            // Also refuses infinity (1e400).
            if !value.is_finite() || value.abs() > MAX_SAFE_INTEGER as f64 {
                return Err(JsonProblem::OutOfRange);
            }
            return Number::from_f64(value)
                .map(Value::Number)
                .ok_or(JsonProblem::OutOfRange);
        }
        let digits = text.len() - usize::from(text.starts_with('-'));
        if digits > 16 {
            // 2^53 - 1 has 16 digits.
            return Err(JsonProblem::OutOfRange);
        }
        let value: i64 = text.parse().map_err(|_| JsonProblem::Invalid)?;
        if value.abs() > MAX_SAFE_INTEGER {
            return Err(JsonProblem::OutOfRange);
        }
        Ok(Value::Number(Number::from(value)))
    }

    /// A string after its opening quote: the text, and its UTF-16 code units
    /// (lone surrogates included, so member names compare exactly as the
    /// reference compares them).
    fn string(&mut self) -> std::result::Result<(String, Vec<u16>), JsonProblem> {
        let b = self.b;
        let n = b.len();
        let mut units: Vec<u16> = Vec::new();
        let mut i = self.i;
        loop {
            let run = i;
            while i < n && b[i] != b'"' && b[i] != b'\\' && b[i] >= 0x20 {
                i += 1;
            }
            // The run ends at an ASCII byte, so it is whole UTF-8 text.
            let text = std::str::from_utf8(&b[run..i]).map_err(|_| JsonProblem::Invalid)?;
            units.extend(text.encode_utf16());
            if i >= n {
                return Err(JsonProblem::Invalid); // no closing quote
            }
            match b[i] {
                b'"' => {
                    i += 1;
                    break;
                }
                b'\\' => {
                    let escape = *b.get(i + 1).ok_or(JsonProblem::Invalid)?;
                    i += 2;
                    let unit = match escape {
                        b'"' => 0x22,
                        b'\\' => 0x5C,
                        b'/' => 0x2F,
                        b'b' => 0x08,
                        b'f' => 0x0C,
                        b'n' => 0x0A,
                        b'r' => 0x0D,
                        b't' => 0x09,
                        b'u' => {
                            let hex = b.get(i..i + 4).ok_or(JsonProblem::Invalid)?;
                            let mut v: u16 = 0;
                            for c in hex {
                                let d = (*c as char).to_digit(16).ok_or(JsonProblem::Invalid)?;
                                v = v * 16 + d as u16;
                            }
                            i += 4;
                            v
                        }
                        _ => return Err(JsonProblem::Invalid),
                    };
                    units.push(unit);
                }
                // A control character inside a string.
                _ => return Err(JsonProblem::Invalid),
            }
        }
        self.i = i;
        match String::from_utf16(&units) {
            Ok(text) => Ok((text, units)),
            Err(_) => {
                self.lone_surrogate = true;
                Ok((String::from_utf16_lossy(&units), units))
            }
        }
    }
}

/// One log line as JSON, and whether it held a lone surrogate.
fn read_json_line(line: &[u8]) -> std::result::Result<(Value, bool), JsonProblem> {
    let mut reader = LineReader {
        b: line,
        i: 0,
        lone_surrogate: false,
    };
    reader.skip_ws();
    let value = reader.value(0)?;
    reader.skip_ws();
    if reader.i != line.len() {
        return Err(JsonProblem::Invalid); // extra data
    }
    Ok((value, reader.lone_surrogate))
}

/// One log line as an entry object, checked for shape (step 1).
fn read_line(line: &[u8], number: usize, limits: &Limits) -> Refusal<Value> {
    let fail = |code, text| DidWebvhError::at(code, text, number);
    if line.is_empty() {
        return Err(fail(INVALID_DID, "the DID log has a blank line"));
    }
    if line.len() > limits.max_line_bytes {
        return Err(fail(TOO_LARGE, "a DID log line is longer than the limit"));
    }
    if line.ends_with(b"\r") {
        return Err(fail(INVALID_DID, "the DID log uses CRLF line endings"));
    }
    if line[0] != b'{' || line[line.len() - 1] != b'}' {
        return Err(fail(INVALID_DID, "a DID log line is not one JSON object"));
    }
    if json_too_deep(line, MAX_LOG_DEPTH) {
        return Err(fail(INVALID_DID, "a DID log line is nested too deeply"));
    }
    let (entry, lone_surrogate) = match read_json_line(line) {
        Ok(read) => read,
        Err(JsonProblem::Repeated) => {
            return Err(fail(INVALID_DID, "a DID log line repeats a member name"))
        }
        Err(JsonProblem::OutOfRange) => return Err(fail(
            INVALID_DID,
            "a DID log line holds a number beyond 2^53 - 1, which not every reader holds exactly",
        )),
        Err(JsonProblem::Invalid) => {
            return Err(fail(INVALID_DID, "a DID log line is not valid JSON"))
        }
    };
    let Some(obj) = entry.as_object() else {
        return Err(fail(INVALID_DID, "a DID log line is not one JSON object"));
    };
    if lone_surrogate {
        return Err(fail(
            INVALID_DID,
            "a DID log line holds text that is not valid Unicode",
        ));
    }
    if ENTRY_MEMBERS.iter().any(|m| !obj.contains_key(*m)) {
        return Err(fail(INVALID_DID, "a DID log entry is missing a member"));
    }
    if obj.len() != ENTRY_MEMBERS.len() {
        return Err(fail(
            INVALID_DID,
            "a DID log entry has a member did:webvh does not define",
        ));
    }
    if !(obj["versionId"].is_string()
        && obj["versionTime"].is_string()
        && obj["parameters"].is_object()
        && obj["state"].is_object())
    {
        return Err(fail(
            INVALID_DID,
            "a DID log entry member has the wrong type",
        ));
    }
    let proofs = match &obj["proof"] {
        Value::Array(items) if !items.is_empty() => items,
        _ => {
            return Err(fail(
                INVALID_DID,
                "a DID log entry's proof is not a non-empty list",
            ))
        }
    };
    if proofs.len() > limits.max_proofs {
        return Err(fail(
            TOO_LARGE,
            "a DID log entry has more proofs than the limit",
        ));
    }
    if !proofs.iter().all(Value::is_object) {
        return Err(fail(
            INVALID_DID,
            "a DID log entry's proof is not a JSON object",
        ));
    }
    Ok(entry)
}

/// Every entry of a log, read and shape-checked (step 1).
fn read_log(log: &[u8], limits: &Limits) -> Refusal<Vec<Value>> {
    if log.len() > limits.max_bytes {
        return Err(DidWebvhError::new(
            TOO_LARGE,
            "the DID log is larger than the limit",
        ));
    }
    if log.starts_with(b"\xef\xbb\xbf") {
        return Err(invalid("the DID log starts with a byte order mark"));
    }
    if std::str::from_utf8(log).is_err() {
        return Err(invalid("the DID log is not UTF-8 text"));
    }
    // More than max_entries + 1 pieces always means too many entries, even
    // after the final newline's empty piece is dropped.
    let mut lines: Vec<&[u8]> = log
        .split(|b| *b == b'\n')
        .take(limits.max_entries.saturating_add(2))
        .collect();
    if lines.last().is_some_and(|l| l.is_empty())
        && lines.len() <= limits.max_entries.saturating_add(1)
    {
        lines.pop();
    }
    if lines.is_empty() {
        return Err(invalid("the DID log is empty"));
    }
    if lines.len() > limits.max_entries {
        return Err(DidWebvhError::new(
            TOO_LARGE,
            "the DID log has more entries than the limit",
        ));
    }
    lines
        .iter()
        .enumerate()
        .map(|(i, line)| read_line(line, i + 1, limits))
        .collect()
}

// =============================================================================
// Hashes (spec 3.7.2, 3.7.3, 3.7.6)
// =============================================================================

/// base58btc(0x12 0x20 || SHA-256(data)): a SHA-256 multihash.
fn multihash_b58(data: &[u8]) -> String {
    let mut raw = Vec::with_capacity(34);
    raw.extend_from_slice(&[0x12, 0x20]);
    raw.extend_from_slice(&Sha256::digest(data));
    bs58::encode(raw).into_string()
}

fn jcs_hash(value: &Value) -> String {
    multihash_b58(&jcs::canonicalize(value))
}

fn is_sha256_multihash(text: &str) -> bool {
    match multikey::decode_base58_bounded(text) {
        Ok(raw) => {
            raw.len() == 34 && raw[..2] == [0x12, 0x20] && bs58::encode(&raw).into_string() == text
        }
        Err(_) => false,
    }
}

/// A pre-rotation hash: base58btc(multihash(UTF-8 of the Multikey)).
fn key_hash(key: &str) -> String {
    multihash_b58(key.as_bytes())
}

/// Every member name and every string value in `value`.
fn names_and_strings<'a>(value: &'a Value, names: &mut Vec<&'a str>, strings: &mut Vec<&'a str>) {
    match value {
        Value::String(s) => strings.push(s),
        Value::Object(map) => {
            for (k, v) in map {
                names.push(k);
                names_and_strings(v, names, strings);
            }
        }
        Value::Array(items) => {
            for v in items {
                names_and_strings(v, names, strings);
            }
        }
        _ => {}
    }
}

/// `value` with every occurrence of the SCID in a string replaced by
/// `{SCID}` (member names hold no SCID; that was checked).
fn with_placeholder(value: &Value, scid: &str) -> Value {
    match value {
        Value::String(s) => Value::String(s.replace(scid, SCID_PLACEHOLDER)),
        Value::Object(map) => Value::Object(
            map.iter()
                .map(|(k, v)| (k.clone(), with_placeholder(v, scid)))
                .collect(),
        ),
        Value::Array(items) => {
            Value::Array(items.iter().map(|v| with_placeholder(v, scid)).collect())
        }
        other => other.clone(),
    }
}

fn without_proof(entry: &Value) -> Map<String, Value> {
    let mut body = entry.as_object().cloned().unwrap_or_default();
    body.remove("proof");
    body
}

/// The SCID is the hash of the first entry with the SCID written as `{SCID}`
/// (spec 3.7.2). The replacement is done on the parsed strings, so an escaped
/// spelling of the SCID is replaced too. A first entry that names the SCID in
/// a member name, or holds the literal `{SCID}`, is refused: readers that
/// replace text and readers that replace values would hash it differently.
fn check_scid(entry: &Value, scid: &str) -> Refusal<()> {
    let body = Value::Object(without_proof(entry));
    let mut names = Vec::new();
    let mut strings = Vec::new();
    names_and_strings(&body, &mut names, &mut strings);
    if names.iter().any(|k| k.contains(scid)) {
        return Err(DidWebvhError::at(
            INVALID_DID,
            "the first entry uses the SCID in a member name",
            1,
        ));
    }
    if names
        .iter()
        .chain(strings.iter())
        .any(|t| t.contains(SCID_PLACEHOLDER))
    {
        return Err(DidWebvhError::at(
            INVALID_DID,
            "the first entry holds the literal {SCID}",
            1,
        ));
    }
    let mut preliminary = with_placeholder(&body, scid);
    if let Some(obj) = preliminary.as_object_mut() {
        obj.insert("versionId".into(), Value::String(SCID_PLACEHOLDER.into()));
    }
    if jcs_hash(&preliminary) != scid {
        return Err(DidWebvhError::at(
            INVALID_DID,
            "the SCID is not the hash of the first entry",
            1,
        ));
    }
    Ok(())
}

// =============================================================================
// Verifying the entries (step 2 of the check order)
// =============================================================================

/// The parameters active after an entry.
#[derive(Debug, Clone)]
struct Active {
    update_keys: Vec<String>,
    next_key_hashes: Vec<String>,
    watchers: Vec<String>,
    portable: bool,
    deactivated: bool,
    ttl: i64,
}

impl Active {
    fn initial() -> Self {
        Self {
            update_keys: Vec::new(),
            next_key_hashes: Vec::new(),
            watchers: Vec::new(),
            portable: false,
            deactivated: false,
            ttl: DEFAULT_TTL,
        }
    }
}

/// `(0|[1-9][0-9]{0,8})` as a number.
fn method_version_part(text: &str) -> Option<u32> {
    let b = text.as_bytes();
    if text == "0" {
        return Some(0);
    }
    if b.is_empty()
        || b.len() > 9
        || !(b'1'..=b'9').contains(&b[0])
        || !b.iter().all(u8::is_ascii_digit)
    {
        return None;
    }
    text.parse().ok()
}

fn check_method(value: &Value, number: usize) -> Refusal<()> {
    let not_a_version = || {
        DidWebvhError::at(
            INVALID_DID,
            "method is not a did:webvh method version",
            number,
        )
    };
    let text = value.as_str().ok_or_else(not_a_version)?;
    if text == METHOD {
        return Ok(());
    }
    let version = text.strip_prefix(PREFIX).ok_or_else(not_a_version)?;
    let (major, minor) = version.split_once('.').ok_or_else(not_a_version)?;
    let (major, minor) = match (method_version_part(major), method_version_part(minor)) {
        (Some(a), Some(b)) => (a, b),
        _ => return Err(not_a_version()),
    };
    if number > 1 && (major, minor) < (1, 0) {
        return Err(DidWebvhError::at(
            INVALID_DID,
            "a did:webvh log cannot move to a lower method version",
            number,
        ));
    }
    Err(DidWebvhError::at(
        UNSUPPORTED,
        "only did:webvh:1.0 logs are supported",
        number,
    ))
}

fn string_list(value: &Value) -> Option<Vec<&str>> {
    value.as_array()?.iter().map(Value::as_str).collect()
}

fn has_duplicates(items: &[&str]) -> bool {
    let mut seen = HashSet::new();
    !items.iter().all(|i| seen.insert(*i))
}

/// A ttl: a whole number (an integral float counts) from 0 to 2^31.
fn whole_ttl(value: &Value) -> Option<i64> {
    let Value::Number(n) = value else {
        return None;
    };
    let ttl = match n.as_i64() {
        Some(i) => i,
        None => {
            let f = n.as_f64()?;
            if f.fract() != 0.0 || !(0.0..=MAX_TTL as f64).contains(&f) {
                return None;
            }
            f as i64
        }
    };
    (0..=MAX_TTL).contains(&ttl).then_some(ttl)
}

/// Check one entry's parameters and return the parameters active after it
/// (spec 3.7.1). The members are checked in a fixed order: unknown names,
/// then null, then that the first entry sets method, scid and updateKeys,
/// then each parameter in the order of `PARAMETERS`.
fn check_parameters(
    given: &Map<String, Value>,
    active: &Active,
    number: usize,
    limits: &Limits,
) -> Refusal<Active> {
    let fail = |code, text| DidWebvhError::at(code, text, number);
    if given.keys().any(|k| !PARAMETERS.contains(&k.as_str())) {
        return Err(fail(
            INVALID_DID,
            "the parameters hold a member did:webvh v1.0 does not define",
        ));
    }
    if given.values().any(Value::is_null) {
        return Err(fail(INVALID_DID, "a did:webvh parameter is null"));
    }
    let first = number == 1;
    if first {
        for (name, text) in [
            ("method", "the first entry does not set method"),
            ("scid", "the first entry does not set scid"),
            ("updateKeys", "the first entry does not set updateKeys"),
        ] {
            if !given.contains_key(name) {
                return Err(fail(INVALID_DID, text));
            }
        }
    }

    if let Some(method) = given.get("method") {
        check_method(method, number)?;
    }
    if let Some(scid) = given.get("scid") {
        if !first {
            return Err(fail(INVALID_DID, "only the first entry may set scid"));
        }
        if !scid.as_str().is_some_and(is_scid) {
            return Err(fail(INVALID_DID, "scid is not 46 base58btc characters"));
        }
    }
    if let Some(value) = given.get("updateKeys") {
        let keys = string_list(value)
            .ok_or_else(|| fail(INVALID_DID, "updateKeys must be a list of Multikey strings"))?;
        if keys.len() > limits.max_update_keys {
            return Err(fail(TOO_LARGE, "updateKeys holds more keys than the limit"));
        }
        for key in &keys {
            if !multikey::decode(key).is_ok_and(|d| d.algorithm == "Ed25519") {
                return Err(fail(
                    INVALID_DID,
                    "an updateKeys entry is not an Ed25519 Multikey",
                ));
            }
        }
        if has_duplicates(&keys) {
            return Err(fail(INVALID_DID, "updateKeys lists a key twice"));
        }
    }
    if let Some(value) = given.get("nextKeyHashes") {
        let hashes = string_list(value)
            .ok_or_else(|| fail(INVALID_DID, "nextKeyHashes must be a list of strings"))?;
        if hashes.len() > limits.max_next_key_hashes {
            return Err(fail(
                TOO_LARGE,
                "nextKeyHashes holds more hashes than the limit",
            ));
        }
        if has_duplicates(&hashes) {
            return Err(fail(INVALID_DID, "nextKeyHashes lists a hash twice"));
        }
    }
    if let Some(value) = given.get("witness") {
        let witness = value
            .as_object()
            .ok_or_else(|| fail(INVALID_DID, "witness must be a JSON object"))?;
        if !witness.is_empty() {
            return Err(fail(UNSUPPORTED, "did:webvh witnesses are not supported"));
        }
    }
    if let Some(value) = given.get("watchers") {
        let watchers = string_list(value)
            .ok_or_else(|| fail(INVALID_DID, "watchers must be a list of strings"))?;
        if has_duplicates(&watchers) {
            return Err(fail(INVALID_DID, "watchers lists a URL twice"));
        }
    }
    if let Some(value) = given.get("portable") {
        let portable = value
            .as_bool()
            .ok_or_else(|| fail(INVALID_DID, "portable must be true or false"))?;
        if portable && !first {
            return Err(fail(
                INVALID_DID,
                "only the first entry may set portable to true",
            ));
        }
    }
    if given.get("deactivated").is_some_and(|v| !v.is_boolean()) {
        return Err(fail(INVALID_DID, "deactivated must be true or false"));
    }
    let ttl = match given.get("ttl") {
        Some(value) => Some(whole_ttl(value).ok_or_else(|| {
            fail(
                INVALID_DID,
                "ttl must be a whole number of seconds from 0 to 2^31",
            )
        })?),
        None => None,
    };

    let mut after = if first {
        Active::initial()
    } else {
        active.clone()
    };
    let owned = |v: &Value| -> Vec<String> {
        string_list(v)
            .unwrap_or_default()
            .into_iter()
            .map(str::to_string)
            .collect()
    };
    if let Some(v) = given.get("updateKeys") {
        after.update_keys = owned(v);
    }
    if let Some(v) = given.get("nextKeyHashes") {
        after.next_key_hashes = owned(v);
    }
    if let Some(v) = given.get("watchers") {
        after.watchers = owned(v);
    }
    if let Some(v) = given.get("portable").and_then(Value::as_bool) {
        after.portable = v;
    }
    if let Some(v) = given.get("deactivated").and_then(Value::as_bool) {
        after.deactivated = v;
    }
    if let Some(ttl) = ttl {
        after.ttl = ttl;
    }
    Ok(after)
}

/// The Multikey a log proof's `did:key:<key>#<key>` names (spec 3.7.4,
/// 3.7.8: the body and the fragment must be the same).
fn proof_key(verification_method: Option<&Value>, number: usize) -> Refusal<String> {
    let shape = || {
        DidWebvhError::at(
            INVALID_DID,
            "a log entry proof's verificationMethod must be did:key:<key>#<key>",
            number,
        )
    };
    let rest = verification_method
        .and_then(Value::as_str)
        .and_then(|vm| vm.strip_prefix("did:key:"))
        .ok_or_else(shape)?;
    let (body, fragment) = rest.split_once('#').ok_or_else(shape)?;
    if body != fragment {
        return Err(shape());
    }
    if !multikey::decode(body).is_ok_and(|d| d.algorithm == "Ed25519") {
        return Err(DidWebvhError::at(
            INVALID_DID,
            "a log entry proof's key is not an Ed25519 Multikey",
            number,
        ));
    }
    Ok(body.to_string())
}

/// The group order L, little-endian.
const GROUP_ORDER_LE: [u8; 32] = [
    0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
];

/// Every encoding of a small-order Ed25519 point (the 8 torsion points, with
/// their sign-bit and y >= p spellings): the fixed set the reference refuses
/// as a signature's R.
const SMALL_ORDER_ENCODINGS: [&str; 14] = [
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0000000000000000000000000000000000000000000000000000000000000080",
    "0100000000000000000000000000000000000000000000000000000000000000",
    "0100000000000000000000000000000000000000000000000000000000000080",
    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
    "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
    "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
    "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
    "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
];

/// The 64-byte Ed25519 signature in an eddsa-jcs-2022 proofValue, checked
/// for its form before it is used, exactly as the reference checks it:
/// multibase base58btc ("z") of exactly 64 bytes, an R whose y is below p
/// and that is not one of the small-order encodings, and an S below the
/// group order. None for anything else. Whether R is a point on the curve is
/// not checked here: an R off the curve fails at verification ("does not
/// verify"), as in the reference.
fn strict_signature(proof_value: &Value) -> Option<Vec<u8>> {
    let body = proof_value.as_str()?.strip_prefix('z')?;
    let signature = multikey::decode_base58_bounded(body).ok()?;
    if signature.len() != keys::ED25519_SIGNATURE_LEN {
        return None;
    }
    let mut r = [0u8; 32];
    r.copy_from_slice(&signature[..32]);
    if !keys::is_canonical_point_encoding(&r) {
        return None;
    }
    let r_hex: String = r.iter().map(|b| format!("{b:02x}")).collect();
    if SMALL_ORDER_ENCODINGS.contains(&r_hex.as_str()) {
        return None;
    }
    // S < L, compared as little-endian numbers from the top byte down.
    let s = &signature[32..];
    for i in (0..32).rev() {
        if s[i] != GROUP_ORDER_LE[i] {
            return (s[i] < GROUP_ORDER_LE[i]).then_some(signature);
        }
    }
    None // S == L
}

/// Every proof on the entry is a valid eddsa-jcs-2022 proof by an
/// authorized update key (spec 3.6.2 step 2, 3.7.4). The signing input is
/// [`crate::data_integrity::hash_data`]'s: SHA-256 of the JCS proof configuration
/// (the proof without proofValue) joined with SHA-256 of the JCS entry
/// without its proof. The entry's half is computed once and shared by every
/// proof. The key and the signature are checked with the strict Ed25519
/// rules.
fn check_proofs(entry: &Value, authorized: &[String], number: usize) -> Refusal<()> {
    let fail = |text| DidWebvhError::at(INVALID_DID, text, number);
    let proofs: &[Value] = entry["proof"].as_array().map_or(&[], Vec::as_slice);
    let document = Value::Object(without_proof(entry));
    let mut document_hash: Option<[u8; 32]> = None;
    for proof in proofs {
        let Some(p) = proof.as_object() else {
            return Err(fail("a log entry proof is missing a member"));
        };
        if p.keys().any(|k| !PROOF_MEMBERS.contains(&k.as_str())) {
            return Err(fail("a log entry proof has a member it may not have"));
        }
        if PROOF_REQUIRED.iter().any(|k| !p.contains_key(*k)) {
            return Err(fail("a log entry proof is missing a member"));
        }
        let text_of = |name: &str| p.get(name).and_then(Value::as_str);
        if text_of("type") != Some(PROOF_TYPE) {
            return Err(fail("a log entry proof is not a DataIntegrityProof"));
        }
        if text_of("cryptosuite") != Some(CRYPTOSUITE) {
            return Err(fail("a log entry proof must use eddsa-jcs-2022"));
        }
        if text_of("proofPurpose") != Some(PROOF_PURPOSE) {
            return Err(fail(
                "a log entry proof's proofPurpose must be assertionMethod",
            ));
        }
        if let Some(created) = p.get("created") {
            let valid = created
                .as_str()
                .is_some_and(|c| time::parse_protocol_time_ns(c).is_ok());
            if !valid {
                return Err(fail("a log entry proof's created is not a valid time"));
            }
        }
        let key = proof_key(p.get("verificationMethod"), number)?;
        if !authorized.contains(&key) {
            return Err(fail(
                "a log entry proof is not made by an authorized update key",
            ));
        }
        let signature = strict_signature(&p["proofValue"])
            .ok_or_else(|| fail("a log entry proof's proofValue is not an Ed25519 signature"))?;
        let raw = multikey::decode(&key)
            .ok()
            .filter(|d| d.algorithm == "Ed25519")
            .map(|d| d.raw_key)
            .ok_or_else(|| fail("a log entry proof's key is not an Ed25519 Multikey"))?;
        let document_hash = *document_hash
            .get_or_insert_with(|| Sha256::digest(jcs::canonicalize(&document)).into());
        // The proof configuration: the proof without proofValue, with the
        // document's @context when it has one (an entry never does).
        let mut config = p.clone();
        config.remove("proofValue");
        if let Some(context) = document.get("@context") {
            config.insert("@context".into(), context.clone());
        }
        let mut signing_input = [0u8; 64];
        signing_input[..32]
            .copy_from_slice(&Sha256::digest(jcs::canonicalize(&Value::Object(config))));
        signing_input[32..].copy_from_slice(&document_hash);
        let verified = keys::verify(&raw, &signing_input, &signature).ok();
        if verified != Some(true) {
            return Err(fail("a log entry proof does not verify"));
        }
    }
    Ok(())
}

/// The state's `id` parses as a did:webvh DID with the log's SCID (spec
/// 3.6.2 step 6), and is the first entry's id: a DID that is not portable may
/// not move (spec 3.7.7), and moves of a portable DID are not supported.
fn check_state_id(
    state: &Value,
    scid: &str,
    first_id: Option<&str>,
    portable: bool,
    number: usize,
) -> Refusal<String> {
    let fail = |code, text| DidWebvhError::at(code, text, number);
    let Some(id) = state.get("id").and_then(Value::as_str) else {
        return Err(fail(INVALID_DID, "the state has no id"));
    };
    let parsed =
        parse(id).map_err(|_| fail(INVALID_DID, "the state id is not a bare did:webvh DID"))?;
    if parsed.scid != scid {
        return Err(fail(
            INVALID_DID,
            "the state id's SCID is not the DID's SCID",
        ));
    }
    if let Some(first) = first_id {
        if id != first {
            if !portable {
                return Err(fail(
                    INVALID_DID,
                    "the state id changed, but the DID is not portable",
                ));
            }
            return Err(fail(
                UNSUPPORTED,
                "did:webvh DIDs that move (portability) are not supported",
            ));
        }
    }
    Ok(id.to_string())
}

struct Verified {
    entries: Vec<Value>,
    /// The parameters active after each entry.
    after: Vec<Active>,
    /// Each entry's versionTime, in nanoseconds.
    times: Vec<i128>,
}

/// Verify every entry in order (step 2), then that the DID appears.
fn verify_entries(
    did: &DidWebvh,
    entries: Vec<Value>,
    now_ns: i128,
    limits: &Limits,
) -> Refusal<Verified> {
    let scid = did.scid.as_str();
    let limit_ns = now_ns + time::seconds_to_ns(MAX_FUTURE_SECONDS);
    let mut active = Active::initial();
    let mut after_each: Vec<Active> = Vec::with_capacity(entries.len());
    let mut times: Vec<i128> = Vec::with_capacity(entries.len());
    let mut previous_id = String::new();
    let mut previous_ns: Option<i128> = None;
    let mut first_id: Option<String> = None;
    let mut matches = 0usize;

    for (index, entry) in entries.iter().enumerate() {
        let number = index + 1;
        let fail = |code, text| DidWebvhError::at(code, text, number);
        let pre_rotation = number > 1 && !active.next_key_hashes.is_empty();
        if number > 1 && active.deactivated {
            return Err(fail(
                INVALID_DID,
                "the DID log has an entry after the DID was deactivated",
            ));
        }
        if number > 1 && !pre_rotation && active.update_keys.is_empty() {
            return Err(fail(
                INVALID_DID,
                "the DID log has an entry after updateKeys was emptied",
            ));
        }

        // versionId: "<number>-<entryHash>" (spec 3.6.2 step 3).
        let version_id = entry["versionId"].as_str().unwrap_or_default();
        let pieces: Vec<&str> = version_id.split('-').collect();
        if pieces.len() != 2 {
            return Err(fail(
                INVALID_DID,
                "a versionId must be its number, one dash and the entry hash",
            ));
        }
        let head = pieces[0].as_bytes();
        if head.is_empty()
            || !(b'1'..=b'9').contains(&head[0])
            || !head.iter().all(u8::is_ascii_digit)
        {
            return Err(fail(
                INVALID_DID,
                "a versionId number must be written without leading zeros",
            ));
        }
        if head.len() > 9 || pieces[0].parse::<usize>().ok() != Some(number) {
            return Err(fail(
                INVALID_DID,
                "the versionId numbers must run 1, 2, 3 and so on",
            ));
        }
        if !is_sha256_multihash(pieces[1]) {
            return Err(fail(
                INVALID_DID,
                "the entry hash is not a SHA-256 multihash",
            ));
        }

        // versionTime (spec 3.6.2 step 4).
        let version_time = entry["versionTime"].as_str().unwrap_or_default();
        let moment_ns = time::parse_protocol_time_ns(version_time)
            .map_err(|_| fail(INVALID_DID, "a versionTime is not a valid time"))?;
        if !(version_time.ends_with('Z') || version_time.ends_with("+00:00")) {
            return Err(fail(
                INVALID_DID,
                "a versionTime must be in UTC (Z or +00:00)",
            ));
        }
        if previous_ns.is_some_and(|p| moment_ns <= p) {
            return Err(fail(
                INVALID_DID,
                "each versionTime must be later than the one before",
            ));
        }
        if moment_ns > limit_ns {
            return Err(fail(
                INVALID_DID,
                "a versionTime is more than five minutes in the future",
            ));
        }

        // Parameters (spec 3.6.2 step 1, 3.7.1).
        let empty = Map::new();
        let given = entry["parameters"].as_object().unwrap_or(&empty);
        let after = check_parameters(given, &active, number, limits)?;

        // Pre-rotation (spec 3.6.2 step 7, 3.7.6).
        if pre_rotation {
            let Some(keys) = given.get("updateKeys").and_then(string_list) else {
                return Err(fail(
                    INVALID_DID,
                    "under pre-rotation every entry must set updateKeys",
                ));
            };
            if keys
                .iter()
                .any(|k| !active.next_key_hashes.contains(&key_hash(k)))
            {
                return Err(fail(
                    INVALID_DID,
                    "an updateKeys key is not committed in the previous nextKeyHashes",
                ));
            }
            if !given.contains_key("nextKeyHashes") {
                return Err(fail(
                    INVALID_DID,
                    "under pre-rotation every entry must set nextKeyHashes",
                ));
            }
        }

        // SCID (spec 3.6.2 step 5, 3.7.2).
        if number == 1 {
            if given.get("scid").and_then(Value::as_str) != Some(scid) {
                return Err(fail(INVALID_DID, "the log's scid is not the DID's SCID"));
            }
            check_scid(entry, scid)?;
        }

        // Entry hash (spec 3.6.2 step 3, 3.7.3).
        let mut body = without_proof(entry);
        let predecessor = if number == 1 {
            scid
        } else {
            previous_id.as_str()
        };
        body.insert("versionId".into(), Value::String(predecessor.to_string()));
        if jcs_hash(&Value::Object(body)) != pieces[1] {
            return Err(fail(INVALID_DID, "the entry hash does not match the entry"));
        }

        // Proofs by an authorized key (spec 3.6.2 step 2, 3.7.4, 3.7.5).
        let authorized: Vec<String> = if number == 1 || pre_rotation {
            after.update_keys.clone()
        } else {
            active.update_keys.clone()
        };
        check_proofs(entry, &authorized, number)?;

        // The state's id (spec 3.6.2 step 6).
        let state_id = check_state_id(
            &entry["state"],
            scid,
            first_id.as_deref(),
            after.portable,
            number,
        )?;
        if first_id.is_none() {
            first_id = Some(state_id.clone());
        }
        if state_id == did.did {
            matches += 1;
        }

        previous_id = version_id.to_string();
        previous_ns = Some(moment_ns);
        times.push(moment_ns);
        active = after.clone();
        after_each.push(after);
    }

    if matches == 0 {
        return Err(invalid("no entry's state id is the DID being resolved"));
    }
    Ok(Verified {
        entries,
        after: after_each,
        times,
    })
}

/// The version remembered from an earlier resolution is still in the log
/// (spec 4, "Truncation or withholding of log entries" and "split view").
fn check_seen(verified: &Verified, seen: &str) -> Refusal<()> {
    // VerifyOptions only holds a seen versionId that has a number.
    let number = version_number_of(seen).unwrap_or(usize::MAX);
    if number > verified.entries.len() {
        return Err(invalid("the DID log is older than a version seen before"));
    }
    if verified.entries[number - 1]["versionId"].as_str() != Some(seen) {
        return Err(invalid(
            "the DID log does not include a version seen before",
        ));
    }
    Ok(())
}

/// The index of the entry a query names, else of the last entry.
fn select(verified: &Verified, query: &Query) -> Refusal<usize> {
    let entries = &verified.entries;
    match query {
        Query::Latest => Ok(entries.len() - 1),
        Query::VersionId(wanted) => entries
            .iter()
            .position(|e| e["versionId"].as_str() == Some(wanted.as_str()))
            .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "no entry has that versionId")),
        Query::VersionNumber(n) => {
            if *n >= 1 && (*n as u64) <= entries.len() as u64 {
                Ok(*n as usize - 1)
            } else {
                Err(DidWebvhError::new(
                    NOT_FOUND,
                    "no entry has that version number",
                ))
            }
        }
        Query::VersionTime(at) => {
            let wanted = time::parse_protocol_time_ns(at)
                .map_err(|_| invalid("the versionTime query is not a valid time"))?;
            verified
                .times
                .iter()
                .rposition(|t| *t <= wanted)
                .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "the DID did not exist at that time"))
        }
    }
}

/// Verify a did:webvh log you already hold and resolve one version of it.
///
/// Pure and offline: nothing is fetched. Every entry is checked, in the
/// order the module documentation lists (spec 3.6.2, "Read (Resolve)"), and
/// any failure refuses the whole log, even for a query that names an earlier
/// entry.
///
/// `did` is the DID being resolved (a bare did:webvh DID), `log` the
/// `did.jsonl` bytes, and `now_ns` the resolver's time in nanoseconds since
/// the Unix epoch ([`crate::time::parse_protocol_time_ns`]); no versionTime
/// may be more than five minutes after it.
pub fn verify_log(
    did: &str,
    log: &[u8],
    now_ns: i128,
    options: &VerifyOptions,
) -> Refusal<Resolution> {
    let parsed = parse(did)?;
    let verified = verify_bytes(&parsed, log, now_ns, &options.limits)?;
    resolve_version(
        &parsed,
        &verified,
        options.seen_version_id.as_deref(),
        &options.query,
    )
}

/// Steps 1 and 2 of the check order, and that some entry's state id is the
/// DID.
fn verify_bytes(parsed: &DidWebvh, log: &[u8], now_ns: i128, limits: &Limits) -> Refusal<Verified> {
    let entries = read_log(log, limits)?;
    verify_entries(parsed, entries, now_ns, limits)
}

/// The rest of step 3 on a verified log: the version seen before (a
/// versionId, checked by the caller), the query, and that the selected
/// version is not the deactivated one. Then the resolution.
fn resolve_version(
    parsed: &DidWebvh,
    verified: &Verified,
    seen: Option<&str>,
    query: &Query,
) -> Refusal<Resolution> {
    if let Some(seen) = seen {
        check_seen(verified, seen)?;
    }
    let index = select(verified, query)?;

    let last_index = verified.entries.len() - 1;
    let last = &verified.after[last_index];
    if index == last_index && last.deactivated {
        // The whole log verified, so its latest version is known: a caller
        // records it, and a log from before the deactivation is then refused.
        let mut error = DidWebvhError::new(DEACTIVATED, "the DID is deactivated");
        error.latest_version_id = verified.entries[last_index]["versionId"]
            .as_str()
            .map(str::to_string);
        return Err(error);
    }
    let selected = &verified.entries[index];
    let first = &verified.entries[0];
    let latest = &verified.entries[last_index];
    let metadata = json!({
        "versionId": selected["versionId"],
        "versionTime": selected["versionTime"],
        "created": first["versionTime"],
        "updated": latest["versionTime"],
        "scid": parsed.scid,
        "portable": last.portable,
        "deactivated": last.deactivated,
        "ttl": last.ttl.to_string(),
        "witness": {},
        "watchers": last.watchers,
    });
    Ok(Resolution {
        document: selected["state"].clone(),
        metadata,
        version_number: index + 1,
        latest_version_id: latest["versionId"].as_str().unwrap_or_default().to_string(),
    })
}

// =============================================================================
// Logs for credential verification: the clock and the set of logs
// =============================================================================

/// The clock a did:webvh log is checked against when it gives the keys of a
/// credential's issuer or of a delegation grant's issuer.
///
/// The reference resolves those logs against the time now, whatever time the
/// credential itself is checked at: the credential's `now` decides whether it
/// is within its validity window, and the log clock decides whether a log
/// entry is dated in the future. [`LogClock::At`] fixes the log clock
/// instead, for tests and replays.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LogClock {
    /// The system clock (the default, as in the reference).
    #[default]
    System,
    /// This time, in nanoseconds since the Unix epoch.
    At(i128),
}

impl LogClock {
    /// The time this clock reads now, in nanoseconds since the Unix epoch.
    ///
    /// Errors for [`LogClock::System`] where there is no system clock
    /// (WebAssembly in a browser; the WASM build passes the JavaScript clock
    /// as [`LogClock::At`]).
    pub fn now_ns(self) -> Result<i128> {
        match self {
            Self::At(ns) => Ok(ns),
            Self::System => system_now_ns().ok_or_else(|| {
                CoreError::Json("there is no system clock here: give logNow".into())
            }),
        }
    }
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn system_now_ns() -> Option<i128> {
    use std::time::{SystemTime, UNIX_EPOCH};
    Some(match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(after) => after.as_nanos() as i128,
        Err(before) => -(before.duration().as_nanos() as i128),
    })
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn system_now_ns() -> Option<i128> {
    None
}

/// The did:webvh logs one credential verification uses, as the caller
/// fetched them: the issuer's, and those of delegation grant issuers.
///
/// The core keeps no state and never fetches. The caller fetches each log
/// from [`log_url`], gives the latest versionId it saw before for each DID
/// ([`LogSet::with_seen_version_id`]), and afterwards remembers the latest
/// versions the set reports ([`LogSet::outcomes`]), so a log later served
/// rolled back or forked is refused.
///
/// A log is verified the first time a verification needs it (credential
/// verification always uses the latest entry), against one clock read when
/// the set is made, and its latest state is then reused for the rest of that
/// verification, as the reference keeps one document per DID per
/// verification. Make one set per verification.
pub struct LogSet {
    now_ns: i128,
    limits: Limits,
    logs: BTreeMap<String, Vec<u8>>,
    seen: BTreeMap<String, String>,
    resolved: RefCell<BTreeMap<String, Refusal<Resolution>>>,
}

impl fmt::Debug for LogSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LogSet")
            .field("now_ns", &self.now_ns)
            .field("limits", &self.limits)
            .field("dids", &self.logs.keys().collect::<Vec<_>>())
            .field("seen", &self.seen)
            .finish()
    }
}

impl LogSet {
    /// An empty set whose logs are checked against `clock`, read now, with
    /// the default limits.
    ///
    /// Errors when the clock cannot be read (see [`LogClock::now_ns`]).
    pub fn new(clock: LogClock) -> Result<Self> {
        Ok(Self {
            now_ns: clock.now_ns()?,
            limits: Limits::default(),
            logs: BTreeMap::new(),
            seen: BTreeMap::new(),
            resolved: RefCell::new(BTreeMap::new()),
        })
    }

    /// Check every log with these limits.
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// The log (`did.jsonl`) of `did`, as fetched from [`log_url`].
    pub fn with_log(mut self, did: &str, log: Vec<u8>) -> Self {
        self.logs.insert(did.to_string(), log);
        self
    }

    /// The latest versionId seen for `did` before. Its log must still
    /// contain it, so a log rolled back or forked since is refused.
    ///
    /// Errors when `seen` is not a did:webvh versionId.
    pub fn with_seen_version_id(mut self, did: &str, seen: &str) -> Result<Self> {
        if version_number_of(seen).is_none() {
            return Err(seen_version_id_error());
        }
        self.seen.insert(did.to_string(), seen.to_string());
        Ok(self)
    }

    /// The time the logs are checked against, in nanoseconds since the Unix
    /// epoch.
    pub fn now_ns(&self) -> i128 {
        self.now_ns
    }

    /// The limits every log is checked with.
    pub fn limits(&self) -> &Limits {
        &self.limits
    }

    /// True when the set holds a log for `did`.
    pub fn contains(&self, did: &str) -> bool {
        self.logs.contains_key(did)
    }

    /// The latest verified state of `did`'s log, or why the log was refused
    /// (a deactivated DID is `deactivated`). None when the set holds no log
    /// for `did`. The log is verified once; later calls reuse the answer.
    pub fn resolve(&self, did: &str) -> Option<Refusal<Resolution>> {
        if let Some(done) = self.resolved.borrow().get(did) {
            return Some(done.clone());
        }
        let log = self.logs.get(did)?;
        let mut options = VerifyOptions::new().with_limits(self.limits);
        // with_seen_version_id checked the form when the set was made.
        options.seen_version_id = self.seen.get(did).cloned();
        let answer = verify_log(did, log, self.now_ns, &options);
        self.resolved
            .borrow_mut()
            .insert(did.to_string(), answer.clone());
        Some(answer)
    }

    /// Every log resolved so far, by DID: its latest versionId (remember it
    /// as the version seen for that DID), or why it was refused. A log the
    /// verification never needed is not listed.
    pub fn outcomes(&self) -> BTreeMap<String, Refusal<String>> {
        self.resolved
            .borrow()
            .iter()
            .map(|(did, answer)| {
                (
                    did.clone(),
                    answer
                        .as_ref()
                        .map(|r| r.latest_version_id.clone())
                        .map_err(Clone::clone),
                )
            })
            .collect()
    }
}

// =============================================================================
// JSON in, JSON out (for the bindings)
// =============================================================================

/// [`parse`] as JSON: `{"scid", "host", "port", "path", "url"}`, or
/// `{"error": {"code", "text"}}` for a refused DID.
pub fn parse_json(did: &str) -> Value {
    match parse(did) {
        Ok(parsed) => parsed.to_json(),
        Err(e) => json!({"error": {"code": e.code, "text": e.text}}),
    }
}

pub(crate) fn base64_decode(text: &str, name: &str) -> Result<Vec<u8>> {
    use base64::{engine::general_purpose::STANDARD, Engine};
    STANDARD
        .decode(text)
        .map_err(|_| CoreError::Json(format!("{name} must be standard base64")))
}

/// The log bytes of a request: `text_name` (the log as text) or `b64_name`
/// (its bytes in base64, for a log that is not UTF-8), exactly one.
fn log_bytes(request: &Map<String, Value>, text_name: &str, b64_name: &str) -> Result<Vec<u8>> {
    match (request.get(text_name), request.get(b64_name)) {
        (Some(Value::String(text)), None) => Ok(text.as_bytes().to_vec()),
        (None, Some(Value::String(b64))) => base64_decode(b64, b64_name),
        _ => Err(CoreError::Json(format!(
            "give the log as {text_name} (text) or {b64_name} (base64), exactly one"
        ))),
    }
}

pub(crate) fn request_object<'a>(
    request: &'a Value,
    allowed: &[&str],
) -> Result<&'a Map<String, Value>> {
    let obj = request
        .as_object()
        .ok_or_else(|| CoreError::Json("the request must be a JSON object".into()))?;
    if let Some(name) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
        return Err(CoreError::Json(format!(
            "the request holds an unknown member {:?}",
            name.chars().take(40).collect::<String>()
        )));
    }
    Ok(obj)
}

fn request_text<'a>(obj: &'a Map<String, Value>, name: &str) -> Result<&'a str> {
    obj.get(name)
        .and_then(Value::as_str)
        .ok_or_else(|| CoreError::Json(format!("{name} must be a string")))
}

/// [`verify_log`] as JSON. The request is `{"did", "log" or "logB64", "now",
/// "options"}`: `log` is the log as text, `logB64` its bytes in base64 (for a
/// log that is not UTF-8), `now` a protocol time, and `options` (optional)
/// as [`VerifyOptions::from_json`] reads it.
///
/// Returns `{"document", "metadata", "versionNumber", "latestVersionId"}`,
/// or `{"error": {"code", "text", "entry"}}` when the DID or the log is
/// refused. A malformed request (a missing member, two queries, bad limits,
/// a seenVersionId that is not a versionId) is an `Err`.
///
/// The checks run in the reference's order, so a request that has both a
/// refusal and a mistake gives the same answer in every language: the
/// request, `now` and the limits; then the DID; then the query (at most one,
/// of the right type); then the log; and only then the form of the version
/// seen before, and the rest of step 3.
pub fn verify_log_json(request: &Value) -> Result<Value> {
    let obj = request_object(request, &["did", "log", "logB64", "now", "options"])?;
    let did = request_text(obj, "did")?;
    let log = log_bytes(obj, "log", "logB64")?;
    let now_ns = time::parse_protocol_time_ns(request_text(obj, "now")?)?;
    let empty = Map::new();
    let options = match obj.get("options") {
        None | Some(Value::Null) => &empty,
        Some(Value::Object(options)) => options,
        Some(_) => return Err(CoreError::Json("options must be a JSON object".into())),
    };
    let limits = match options.get("limits").filter(|v| !v.is_null()) {
        Some(v) => Limits::from_json(v)?,
        None => Limits::default(),
    };
    let refused = |e: DidWebvhError| json!({"error": e.to_json()});
    let parsed = match parse(did) {
        Ok(parsed) => parsed,
        Err(e) => return Ok(refused(e)),
    };
    let (query, seen) = read_query(options)?;
    let verified = match verify_bytes(&parsed, &log, now_ns, &limits) {
        Ok(verified) => verified,
        Err(e) => return Ok(refused(e)),
    };
    if seen
        .as_deref()
        .is_some_and(|s| version_number_of(s).is_none())
    {
        return Err(seen_version_id_error());
    }
    Ok(
        match resolve_version(&parsed, &verified, seen.as_deref(), &query) {
            Ok(resolution) => resolution.to_json(),
            Err(e) => refused(e),
        },
    )
}

/// The request members every verify request shares for the delegation
/// chain and the did:webvh logs (see [`read_chain_request`]).
pub(crate) const CHAIN_REQUEST_MEMBERS: [&str; 12] = [
    "now",
    "clockSkewSeconds",
    "trustedRoots",
    "requirePostQuantum",
    "grantKeys",
    "grantMldsa44Keys",
    "grantSlhdsa128Keys",
    "grantLogs",
    "grantLogsB64",
    "grantSeenVersionIds",
    "limits",
    "logNow",
];

/// The chain and log members of a verify request, read.
pub(crate) struct ChainRequest {
    pub(crate) now: String,
    pub(crate) skew: i64,
    pub(crate) roots: Option<Vec<String>>,
    pub(crate) require_pq: bool,
    pub(crate) grant_keys: Option<BTreeMap<String, Vec<u8>>>,
    pub(crate) grant_mldsa_keys: Option<BTreeMap<String, Vec<u8>>>,
    pub(crate) grant_slhdsa_keys: Option<BTreeMap<String, Vec<u8>>>,
    /// The grant issuers' logs and versions seen, with the limits and the
    /// clock. The did:webvh credential request adds the issuer's log.
    pub(crate) logs: LogSet,
}

fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
    obj.get(name).filter(|v| !v.is_null())
}

/// A JSON object of DID to text, or None when absent.
fn text_map<'a>(
    obj: &'a Map<String, Value>,
    name: &str,
    what: &str,
) -> Result<Option<Vec<(&'a String, &'a str)>>> {
    let bad = || CoreError::Json(format!("{name} must be a JSON object of DID to {what}"));
    match present(obj, name) {
        None => Ok(None),
        Some(Value::Object(map)) => map
            .iter()
            .map(|(did, v)| v.as_str().map(|t| (did, t)).ok_or_else(bad))
            .collect::<Result<Vec<_>>>()
            .map(Some),
        Some(_) => Err(bad()),
    }
}

/// A JSON object of DID to base64 key, decoded.
fn key_map(obj: &Map<String, Value>, name: &str) -> Result<Option<BTreeMap<String, Vec<u8>>>> {
    match text_map(obj, name, "base64 key")? {
        None => Ok(None),
        Some(items) => items
            .into_iter()
            .map(|(did, key)| Ok((did.clone(), base64_decode(key, &format!("a {name} key"))?)))
            .collect::<Result<_>>()
            .map(Some),
    }
}

/// Read the members of a verify request that every entry shares:
///
/// - `now` (a protocol time, required) and `clockSkewSeconds` (0 to 120,
///   default 0): the credential's own clock;
/// - `trustedRoots` (optional): the DIDs a delegation chain must start from;
///   without it a credential carrying a chain is refused;
/// - `requirePostQuantum` (default false);
/// - `grantKeys` (optional): Ed25519 keys (base64) of grant issuers that are
///   not did:key, by DID. They resolve grant signatures only and never make
///   a DID a trusted root;
/// - `grantMldsa44Keys` (optional): ML-DSA-44 keys (base64) of grant
///   issuers, by DID;
/// - `grantLogs` / `grantLogsB64` (optional): the `did.jsonl` of did:webvh
///   grant issuers, by DID, as text or base64 (a DID in at most one);
/// - `grantSeenVersionIds` (optional): the latest versionId seen before for
///   each of those DIDs;
/// - `limits` (optional): as [`Limits::from_json`], for every log;
/// - `logNow` (optional): a protocol time to check the logs against, for
///   tests and replays. Without it the logs are checked against `clock`.
pub(crate) fn read_chain_request(
    obj: &Map<String, Value>,
    clock: LogClock,
) -> Result<ChainRequest> {
    let now = request_text(obj, "now")?.to_string();
    time::parse_protocol_time_ns(&now)?;
    let skew = match present(obj, "clockSkewSeconds") {
        None => 0,
        Some(v) => time::clock_skew_from_json(v)?,
    };
    let roots = match present(obj, "trustedRoots") {
        None => None,
        Some(v) => Some(
            string_list(v)
                .ok_or_else(|| CoreError::Json("trustedRoots must be a list of strings".into()))?
                .into_iter()
                .map(str::to_string)
                .collect(),
        ),
    };
    let require_pq = match present(obj, "requirePostQuantum") {
        None => false,
        Some(Value::Bool(b)) => *b,
        Some(_) => {
            return Err(CoreError::Json(
                "requirePostQuantum must be true or false".into(),
            ))
        }
    };
    let grant_keys = key_map(obj, "grantKeys")?;
    let grant_mldsa_keys = key_map(obj, "grantMldsa44Keys")?;
    let grant_slhdsa_keys = key_map(obj, "grantSlhdsa128Keys")?;
    let clock = match present(obj, "logNow") {
        None => clock,
        Some(v) => LogClock::At(time::parse_protocol_time_ns(
            v.as_str()
                .ok_or_else(|| CoreError::Json("logNow must be a protocol time".into()))?,
        )?),
    };
    let mut logs = LogSet::new(clock)?;
    if let Some(limits) = present(obj, "limits") {
        logs = logs.with_limits(Limits::from_json(limits)?);
    }
    let texts = text_map(obj, "grantLogs", "log text")?.unwrap_or_default();
    let b64s = text_map(obj, "grantLogsB64", "base64 log")?.unwrap_or_default();
    for (did, log) in texts
        .into_iter()
        .map(|(did, text)| Ok((did, text.as_bytes().to_vec())))
        .chain(
            b64s.into_iter()
                .map(|(did, b64)| Ok((did, base64_decode(b64, "a grantLogsB64 log")?))),
        )
        .collect::<Result<Vec<_>>>()?
    {
        if !is_did_webvh(did) {
            return Err(CoreError::Json(
                "grantLogs holds a DID that is not a did:webvh DID".into(),
            ));
        }
        if logs.contains(did) {
            return Err(CoreError::Json(
                "give each grant issuer's log once, in grantLogs or grantLogsB64".into(),
            ));
        }
        logs = logs.with_log(did, log);
    }
    for (did, seen) in text_map(obj, "grantSeenVersionIds", "versionId")?.unwrap_or_default() {
        logs = logs.with_seen_version_id(did, seen)?;
    }
    Ok(ChainRequest {
        now,
        skew,
        roots,
        require_pq,
        grant_keys,
        grant_mldsa_keys,
        grant_slhdsa_keys,
        logs,
    })
}

/// The grant logs a verification resolved, as two JSON objects:
/// `grantVersionIds` (DID to latest versionId) and `grantLogErrors` (DID to
/// `{"code", "text", "entry"}`).
pub(crate) fn grant_log_json(outcomes: &BTreeMap<String, Refusal<String>>) -> (Value, Value) {
    let mut versions = Map::new();
    let mut errors = Map::new();
    for (did, outcome) in outcomes {
        match outcome {
            Ok(version) => {
                versions.insert(did.clone(), Value::String(version.clone()));
            }
            Err(e) => {
                errors.insert(did.clone(), e.to_json());
            }
        }
    }
    (Value::Object(versions), Value::Object(errors))
}

/// [`crate::credentials::verify_with_did_webvh_log`] as JSON, with the logs
/// checked against the system clock (see [`verify_credential_json_with_clock`]).
pub fn verify_credential_json(request: &Value) -> Result<Value> {
    verify_credential_json_with_clock(request, LogClock::System)
}

/// [`crate::credentials::verify_with_did_webvh_log`] as JSON. The request is
/// `{"credential", "issuerLog" or "issuerLogB64", "seenVersionId"}` plus the
/// members [`read_chain_request`] reads (`now`, `clockSkewSeconds`,
/// `trustedRoots`, `requirePostQuantum`, `grantKeys`, `grantMldsa44Keys`,
/// `grantLogs`, `grantLogsB64`, `grantSeenVersionIds`, `limits`, `logNow`):
///
/// - `credential`: the credential (a JSON object) whose issuer is a
///   did:webvh DID;
/// - `issuerLog` / `issuerLogB64`: the issuer's `did.jsonl`, fetched by the
///   caller from [`log_url`], as text or base64, exactly one;
/// - `seenVersionId` (optional): the latest versionId seen before for the
///   issuer.
///
/// Every log is checked against `logNow` when the request gives one, else
/// against `clock` (the system clock for [`verify_credential_json`]), never
/// against the credential's `now`.
///
/// Returns `{"proofValid", "timeValid", "chainValid", "valid",
/// "chainReason", "issuerVersionId", "issuerLogError", "grantVersionIds",
/// "grantLogErrors"}`: `issuerVersionId` is the issuer log's latest
/// versionId (remember it as the version seen) and `issuerLogError` is null,
/// or `{"code", "text", "entry"}` when the log was refused (the proof is then
/// not valid); `grantVersionIds` and `grantLogErrors` say the same, by DID,
/// for the grant issuers' logs the chain needed.
pub fn verify_credential_json_with_clock(request: &Value, clock: LogClock) -> Result<Value> {
    let mut allowed = vec!["credential", "issuerLog", "issuerLogB64", "seenVersionId"];
    allowed.extend(CHAIN_REQUEST_MEMBERS);
    let obj = request_object(request, &allowed)?;
    let credential = obj
        .get("credential")
        .filter(|c| c.is_object())
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
    let log = log_bytes(obj, "issuerLog", "issuerLogB64")?;
    let request = read_chain_request(obj, clock)?;
    let issuer = crate::credentials::issuer_did(credential)
        .filter(|i| is_did_webvh(i))
        .ok_or_else(|| {
            CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
        })?;
    if request.logs.contains(issuer) {
        return Err(CoreError::Json(
            "give the issuer's log once, as issuerLog or issuerLogB64".into(),
        ));
    }
    let mut logs = request.logs.with_log(issuer, log);
    if let Some(seen) = present(obj, "seenVersionId") {
        let seen = seen
            .as_str()
            .ok_or_else(|| CoreError::Json("seenVersionId must be a string".into()))?;
        logs = logs.with_seen_version_id(issuer, seen)?;
    }
    let chain = crate::delegation::ChainOptions {
        trusted_roots: request.roots.as_deref(),
        grant_keys: request.grant_keys.as_ref(),
        mldsa_keys: request.grant_mldsa_keys.as_ref(),
        slhdsa_keys: request.grant_slhdsa_keys.as_ref(),
        require_pq: request.require_pq,
        ..Default::default()
    };
    let outcome = crate::credentials::verify_with_did_webvh_log(
        credential,
        &logs,
        &request.now,
        request.skew,
        &chain,
    )?;
    let r = outcome.result;
    let (grant_versions, grant_errors) = grant_log_json(&outcome.grant_logs);
    Ok(json!({
        "proofValid": r.proof_valid,
        "timeValid": r.time_valid,
        "chainValid": r.chain_valid,
        "valid": r.is_valid(),
        "chainReason": outcome.chain_reason,
        "issuerVersionId": outcome.log.as_ref().ok(),
        "issuerLogError": outcome.log.as_ref().err().map(DidWebvhError::to_json),
        "grantVersionIds": grant_versions,
        "grantLogErrors": grant_errors,
    }))
}

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

    #[test]
    fn depth_scan_counts_brackets_outside_strings() {
        let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
        assert!(!json_too_deep(nested(64).as_bytes(), 64));
        assert!(json_too_deep(nested(65).as_bytes(), 64));
        // Brackets inside strings, escaped quotes included, do not count.
        let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
        assert!(!json_too_deep(quoted.as_bytes(), 64));
        // A string with no closing quote runs to the end.
        assert!(!json_too_deep(b"{\"a\":\"[[[[", 2));
    }

    #[test]
    fn reader_reports_problems_where_python_does() {
        let read = |s: &str| read_json_line(s.as_bytes());
        assert_eq!(read(r#"{"a":1,"a":2}"#).unwrap_err(), JsonProblem::Repeated);
        // A repeated name in an object still open does not count before a
        // number out of range later in it.
        assert_eq!(
            read(r#"{"a":1,"a":2,"b":99999999999999999}"#).unwrap_err(),
            JsonProblem::OutOfRange
        );
        assert_eq!(
            read(r#"{"x":{"a":1,"a":2},"b":1e999}"#).unwrap_err(),
            JsonProblem::Repeated
        );
        assert_eq!(
            read(r#"{"a":1,"a":2,"b":tru}"#).unwrap_err(),
            JsonProblem::Invalid
        );
        // The integer part is read (and range-checked) before a bad exponent.
        assert_eq!(
            read(r#"{"a":99999999999999999e}"#).unwrap_err(),
            JsonProblem::OutOfRange
        );
        assert_eq!(read(r#"{"a":1e}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read(r#"{"a":NaN}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(
            read(r#"{"a":-Infinity}"#).unwrap_err(),
            JsonProblem::Invalid
        );
        assert_eq!(read(r#"{"a":01}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read(r#"{"a":[1,]}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read(r#"{"a":1,}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read("{\"a\":\"\t\"}").unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read(r#"{"a":"\x"}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(read(r#"{}{}"#).unwrap_err(), JsonProblem::Invalid);
        assert_eq!(
            read(r#"{"a":9007199254740991}"#).unwrap().0["a"],
            9007199254740991i64
        );
        assert_eq!(
            read(r#"{"a":-9007199254740992}"#).unwrap_err(),
            JsonProblem::OutOfRange
        );
        assert_eq!(
            read(r#"{"a":9007199254740992.0}"#).unwrap_err(),
            JsonProblem::OutOfRange
        );
        // Lone surrogates are remembered; two different ones are two names.
        assert!(read(r#"{"a":"\ud800"}"#).unwrap().1);
        assert!(read(r#"{"\ud800":1,"\udc00":2}"#).unwrap().1);
        assert_eq!(
            read(r#"{"\ud800":1,"\ud800":2}"#).unwrap_err(),
            JsonProblem::Repeated
        );
        // A pair is one character, and the same name as the raw character.
        let (v, lone) = read(r#"{"a":"😀"}"#).unwrap();
        assert!(!lone);
        assert_eq!(v["a"], "\u{1F600}");
        assert_eq!(
            read("{\"\u{1F600}\":1,\"\\ud83d\\ude00\":2}").unwrap_err(),
            JsonProblem::Repeated
        );
        assert_eq!(
            read(r#"{"a":"a","a":1}"#).unwrap_err(),
            JsonProblem::Repeated
        );
    }

    #[test]
    fn options_from_json() {
        assert!(
            VerifyOptions::from_json(&json!({"versionId": "1-x", "versionNumber": 1})).is_err()
        );
        assert!(VerifyOptions::from_json(&json!({"versionNumber": 1.0})).is_err());
        assert!(VerifyOptions::from_json(&json!({"versionNumber": true})).is_err());
        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "01-x"})).is_err());
        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "1"})).is_err());
        assert!(VerifyOptions::from_json(&json!({"other": 1})).is_err());
        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 0}})).is_err());
        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 5242881}})).is_err());
        assert!(VerifyOptions::from_json(&json!({"limits": {"maxProofs": true}})).is_err());
        assert!(VerifyOptions::from_json(&json!({"limits": {"maxx": 1}})).is_err());
        let o = VerifyOptions::from_json(
            &json!({"versionId": null, "versionTime": "x", "limits": {"maxEntries": 2}}),
        )
        .unwrap();
        assert_eq!(o.query(), &Query::VersionTime("x".into()));
        assert_eq!(o.limits().max_entries(), 2);
        assert_eq!(o.limits().max_bytes(), 1024 * 1024);
        assert_eq!(
            VerifyOptions::from_json(&json!({"versionNumber": u64::MAX}))
                .unwrap()
                .query(),
            &Query::VersionNumber(i64::MAX)
        );
    }

    /// The `create` log of the shared vector, with its proofValue's R
    /// replaced by `r`.
    fn create_log_with_r(r: [u8; 32]) -> (String, String) {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-vectors/did-webvh/vector.json"
        );
        let v: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
        let case = v["logs"]
            .as_array()
            .unwrap()
            .iter()
            .find(|c| c["name"] == "create")
            .unwrap();
        let log = case["log"].as_str().unwrap();
        let entry: Value = serde_json::from_str(log.trim_end()).unwrap();
        let value = entry["proof"][0]["proofValue"].as_str().unwrap();
        let mut signature = bs58::decode(&value[1..]).into_vec().unwrap();
        signature[..32].copy_from_slice(&r);
        let changed = format!("z{}", bs58::encode(signature).into_string());
        (
            case["did"].as_str().unwrap().to_string(),
            log.replace(value, &changed),
        )
    }

    fn refusal(did: &str, log: &str) -> DidWebvhError {
        let now = time::parse_protocol_time_ns("2026-11-30T00:00:00Z").unwrap();
        verify_log(did, log.as_bytes(), now, &VerifyOptions::new()).unwrap_err()
    }

    #[test]
    fn an_r_off_the_curve_fails_at_verification() {
        // A y below p (a canonical encoding) that names no point on the curve.
        let off_curve = (2u8..=255)
            .map(|y| {
                let mut r = [0u8; 32];
                r[0] = y;
                r
            })
            .find(|r| ed25519_dalek::VerifyingKey::from_bytes(r).is_err())
            .expect("a y with no point");
        assert!(keys::is_canonical_point_encoding(&off_curve));
        // The form check lets it through, as the reference's does ...
        let mut signature = vec![0u8; 64];
        signature[..32].copy_from_slice(&off_curve);
        let value = Value::String(format!("z{}", bs58::encode(&signature).into_string()));
        assert!(strict_signature(&value).is_some());
        // ... and the proof then does not verify.
        let (did, log) = create_log_with_r(off_curve);
        let e = refusal(&did, &log);
        assert_eq!(
            (e.code, e.text, e.entry),
            (INVALID_DID, "a log entry proof does not verify", Some(1))
        );
    }

    #[test]
    fn a_small_order_or_non_canonical_r_is_not_a_signature() {
        for hex in SMALL_ORDER_ENCODINGS {
            let mut r = [0u8; 32];
            for (i, b) in r.iter_mut().enumerate() {
                *b = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap();
            }
            let (did, log) = create_log_with_r(r);
            let e = refusal(&did, &log);
            assert_eq!(
                (e.text, e.entry),
                (
                    "a log entry proof's proofValue is not an Ed25519 signature",
                    Some(1)
                ),
                "{hex}"
            );
        }
        // y >= p that is not of small order (y = p + 3).
        let mut r = [0xffu8; 32];
        r[0] = 0xf0;
        r[31] = 0x7f;
        let (did, log) = create_log_with_r(r);
        assert_eq!(
            refusal(&did, &log).text,
            "a log entry proof's proofValue is not an Ed25519 signature"
        );
    }

    #[test]
    fn prefix_keeps_its_colon() {
        assert!(is_did_webvh("did:webvh:x"));
        assert!(!is_did_webvh("did:web:x"));
        assert!(!is_did_webvh("did:webvhx:x"));
        assert_eq!(
            parse("did:web:example.com").unwrap_err().text,
            "not a did:webvh DID"
        );
    }
}