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
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
//! Certificates and related data structures.
//!
//! An OpenPGP certificate, often called a `PGP key` or just a `key,`
//! is a collection of keys, identity information, and certifications
//! about those keys and identities.
//!
//! The foundation of an OpenPGP certificate is the so-called primary
//! key.  A primary key has three essential functions.  First, the
//! primary key is used to derive a universally unique identifier
//! (UUID) for the certificate, the certificate's so-called
//! fingerprint.  Second, the primary key is used to certify
//! assertions that the certificate holder makes about their
//! certificate.  For instance, to associate a subkey or a User ID
//! with a certificate, the certificate holder uses the primary key to
//! create a self signature called a binding signature.  This binding
//! signature is distributed with the certificate.  It allows anyone
//! who has the certificate to verify that the certificate holder
//! (identified by the primary key) really intended for the subkey to
//! be associated with the certificate.  Finally, the primary key can
//! be used to make assertions about other certificates.  For
//! instance, Alice can make a so-called third-party certification
//! that attests that she is convinced that `Bob` (as described by
//! some User ID) controls a particular certificate.  These
//! third-party certifications are typically distributed alongside the
//! signee's certificate, and are used by trust models like the Web of
//! Trust to authenticate certificates.
//!
//! # Common Operations
//!
//!  - *Generating a certificate*: See the [`CertBuilder`] module.
//!  - *Parsing a certificate*: See the [`Parser` implementation] for `Cert`.
//!  - *Parsing a keyring*: See the [`CertParser`] module.
//!  - *Serializing a certificate*: See the [`Serialize`
//!    implementation] for `Cert`, and the [`Cert::as_tsk`] method to
//!    also include any secret key material.
//!  - *Using a certificate*: See the [`Cert`] and [`ValidCert`] data structures.
//!  - *Revoking a certificate*: See the [`CertRevocationBuilder`] data structure.
//!  - *Decrypt or encrypt secret keys*: See [`packet::Key::encrypt_secret`]'s example.
//!  - *Merging packets*: See the [`Cert::insert_packets`] method.
//!  - *Merging certificates*: See the [`Cert::merge_public`] method.
//!  - *Creating third-party certifications*: See the [`UserID::certify`]
//!     and [`UserAttribute::certify`] methods.
//!  - *Using User IDs and User Attributes*: See the [`ComponentAmalgamation`] module.
//!  - *Using keys*: See the [`KeyAmalgamation`] module.
//!  - *Updating a binding signature*: See the [`UserID::bind`],
//!    [`UserAttribute::bind`], and [`Key::bind`] methods.
//!  - *Checking third-party signatures*: See the
//!    [`Signature::verify_direct_key`],
//!    [`Signature::verify_userid_binding`], and
//!    [`Signature::verify_user_attribute_binding`] methods.
//!  - *Checking third-party revocations*: See the
//!    [`ValidCert::revocation_keys`],
//!    [`ValidAmalgamation::revocation_keys`],
//!    [`Signature::verify_primary_key_revocation`],
//!    [`Signature::verify_userid_revocation`],
//!    [`Signature::verify_user_attribute_revocation`] methods.
//!
//! # Data Structures
//!
//! ## `Cert`
//!
//! The [`Cert`] data structure closely mirrors the transferable
//! public key (`TPK`) data structure described in [Section 11.1] of
//! RFC 4880: it contains the certificate's `Component`s and their
//! associated signatures.
//!
//! ## `Component`s
//!
//! In Sequoia, we refer to `User ID`s, `User Attribute`s, and `Key`s
//! as `Component`s.  To accommodate unsupported components (e.g.,
//! deprecated v3 keys) and unknown components (e.g., the
//! yet-to-be-defined `Xyzzy Property`), we also define an `Unknown`
//! component.
//!
//! ## `ComponentBundle`s
//!
//! We call a Component and any associated signatures a
//! [`ComponentBundle`].  There are four types of associated
//! signatures: self signatures, third-party signatures, self
//! revocations, and third-party revocations.
//!
//! Although some information about a given `Component` is stored in
//! the `Component` itself, most of the information is stored on the
//! associated signatures.  For instance, a key's creation time is
//! stored in the key packet, but the key's capabilities (e.g.,
//! whether it can be used for encryption or signing), and its expiry
//! are stored in the associated self signatures.  Thus, to use a
//! component, we usually need its corresponding self signature.
//!
//! When a certificate is parsed, Sequoia ensures that all components
//! (except the primary key) have at least one valid self signature.
//! However, when using a component, it is still necessary to find the
//! right self signature.  And, unfortunately, finding the
//! self signature for the primary `Key` is non-trivial: that's the
//! primary User ID's self signature.  Another complication is that if
//! the self signature doesn't contain the required information, then
//! the implementation should look for the information on a direct key
//! signature.  Thus, a `ComponentBundle` doesn't contain all of the
//! information that is needed to use a component.
//!
//! ## `ComponentAmalgamation`s
//!
//! To workaround this lack of context, we introduce another data
//! structure called a [`ComponentAmalgamation`].  A
//! `ComponentAmalgamation` references a `ComponentBundle` and its
//! associated `Cert`.  Unfortunately, we can't include a reference to
//! the `Cert` in the `ComponentBundle`, because the `Cert` owns the
//! `ComponentBundle`, and that would create a self-referential data
//! structure, which is currently not supported in Rust.
//!
//! [Section 11.1]: https://tools.ietf.org/html/rfc4880#section-11.1
//! [`ComponentBundle`]: bundle::ComponentBundle
//! [`ComponentAmalgamation`]: amalgamation::ComponentAmalgamation
//! [`Parser` implementation]: struct.Cert.html#impl-Parse%3C%27a%2C%20Cert%3E
//! [`Serialize` implementation]: struct.Cert.html#impl-Serialize
//! [`UserID::certify`]: crate::packet::UserID::certify()
//! [`UserAttribute::certify`]: crate::packet::user_attribute::UserAttribute::certify()
//! [`KeyAmalgamation`]: amalgamation::key
//! [`UserID::bind`]: crate::packet::UserID::bind()
//! [`UserAttribute::bind`]: crate::packet::user_attribute::UserAttribute::bind()
//! [`Key::bind`]: crate::packet::Key::bind()
//! [`Signature::verify_direct_key`]: crate::packet::Signature::verify_direct_key()
//! [`Signature::verify_userid_binding`]: crate::packet::Signature::verify_userid_binding()
//! [`Signature::verify_user_attribute_binding`]: crate::packet::Signature::verify_user_attribute_binding()
//! [`ValidAmalgamation::revocation_keys`]: amalgamation::ValidAmalgamation::revocation_keys
//! [`Signature::verify_primary_key_revocation`]: crate::packet::Signature::verify_primary_key_revocation()
//! [`Signature::verify_userid_revocation`]: crate::packet::Signature::verify_userid_revocation()
//! [`Signature::verify_user_attribute_revocation`]: crate::packet::Signature::verify_user_attribute_revocation()

use std::io;
use std::collections::btree_map::BTreeMap;
use std::collections::btree_map::Entry;
use std::collections::hash_map::DefaultHasher;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::hash::Hasher;
use std::path::Path;
use std::mem;
use std::fmt;
use std::time;

use buffered_reader::BufferedReader;

use crate::{
    crypto::{
        Signer,
        hash::Digest,
    },
    Error,
    Result,
    SignatureType,
    packet,
    packet::Signature,
    packet::Key,
    packet::key,
    packet::Tag,
    packet::UserID,
    packet::UserAttribute,
    packet::Unknown,
    Packet,
    PacketPile,
    seal,
    KeyID,
    Fingerprint,
    KeyHandle,
    policy::Policy,
};
use crate::parse::{Cookie, Parse, PacketParserResult, PacketParser};
use crate::types::{
    AEADAlgorithm,
    CompressionAlgorithm,
    Features,
    HashAlgorithm,
    KeyServerPreferences,
    ReasonForRevocation,
    RevocationKey,
    RevocationStatus,
    SymmetricAlgorithm,
};

pub mod amalgamation;
mod builder;
mod bindings;
pub mod bundle;
use bundle::{
    ComponentBundles,
    UserIDBundles,
    UserAttributeBundles,
    SubkeyBundles,
    UnknownBundles,
};
mod lazysigs;
mod parser;
pub mod raw;
mod revoke;

pub use self::builder::{CertBuilder, CipherSuite, KeyBuilder, SubkeyBuilder};

pub use parser::{
    CertParser,
};

pub(crate) use parser::{
    CertValidator,
    CertValidity,
    KeyringValidator,
    KeyringValidity,
};

pub use revoke::{
    SubkeyRevocationBuilder,
    CertRevocationBuilder,
    UserAttributeRevocationBuilder,
    UserIDRevocationBuilder,
};

pub mod prelude;
use prelude::*;

const TRACE : bool = false;

// Helper functions.

/// Compare the creation time of two signatures.  Order them so that
/// the more recent signature is first.
fn canonical_signature_order(a: Option<time::SystemTime>, b: Option<time::SystemTime>)
                             -> Ordering {
    // Note: None < Some, so the normal ordering is:
    //
    //   None, Some(old), Some(new)
    //
    // Reversing the ordering puts the signatures without a creation
    // time at the end, which is where they belong.
    a.cmp(&b).reverse()
}

/// Compares two signatures by creation time using the MPIs as tie
/// breaker.
///
/// Useful to sort signatures so that the most recent ones are at the
/// front.
fn sig_cmp(a: &Signature, b: &Signature) -> Ordering {
    match canonical_signature_order(a.signature_creation_time(),
                                    b.signature_creation_time()) {
        Ordering::Equal => a.mpis().cmp(b.mpis()),
        r => r
    }
}

impl fmt::Display for Cert {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.fingerprint())
    }
}

/// Returns the certificate holder's preferences.
///
/// OpenPGP provides a mechanism for a certificate holder to transmit
/// information about communication preferences, and key management to
/// communication partners in an asynchronous manner.  This
/// information is attached to the certificate itself.  Specifically,
/// the different types of information are stored as signature
/// subpackets in the User IDs' self signatures, and in the
/// certificate's direct key signature.
///
/// OpenPGP allows the certificate holder to specify different
/// information depending on the way the certificate is addressed.
/// When addressed by User ID, that User ID's self signature is first
/// checked for the subpacket in question.  If the subpacket is not
/// present or the certificate is addressed is some other way, for
/// instance, by its fingerprint, then the primary User ID's
/// self signature is checked.  If the subpacket is also not there,
/// then the direct key signature is checked.  This policy and its
/// justification are described in [Section 5.2.3.3] of RFC 4880.
///
/// Note: User IDs may be stripped.  For instance, the [WKD] standard
/// requires User IDs that are unrelated to the WKD's domain be
/// stripped from the certificate prior to publication.  As such, any
/// User ID may be considered the primary User ID.  Consequently, if
/// any User ID includes a particular subpacket, then all User IDs
/// should include it.  Furthermore, RFC 4880bis allows certificates
/// [without any User ID packets].  To handle this case, certificates
/// should also create a direct key signature with this information.
///
/// [Section 5.2.3.3]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
/// [WKD]: https://tools.ietf.org/html/draft-koch-openpgp-webkey-service-09#section-5
/// [without any User ID packets]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-11.1
///
/// # Algorithm Preferences
///
/// Algorithms are ordered with the most preferred algorithm first.
/// According to RFC 4880, if an algorithm is not listed, then the
/// implementation should assume that it is not supported by the
/// certificate holder's software.
///
/// # Examples
///
/// ```
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// use openpgp::cert::prelude::*;
/// use sequoia_openpgp::policy::StandardPolicy;
///
/// # fn main() -> Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #     .generate()?;
/// match cert.with_policy(p, None)?.primary_userid()?.preferred_symmetric_algorithms() {
///     Some(algos) => {
///         println!("Certificate Holder's preferred symmetric algorithms:");
///         for (i, algo) in algos.iter().enumerate() {
///             println!("{}. {}", i, algo);
///         }
///     }
///     None => {
///         println!("Certificate Holder did not specify any preferred \
///                   symmetric algorithms, or the subpacket is missing.");
///     }
/// }
/// # Ok(()) }
/// ```
///
/// # Sealed trait
///
/// This trait is [sealed] and cannot be implemented for types outside this crate.
/// Therefore it can be extended in a non-breaking way.
/// If you want to implement the trait inside the crate
/// you also need to implement the `seal::Sealed` marker trait.
///
/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
pub trait Preferences<'a>: seal::Sealed {
    /// Returns the supported symmetric algorithms ordered by
    /// preference.
    ///
    /// The algorithms are ordered according by the certificate
    /// holder's preference.
    fn preferred_symmetric_algorithms(&self)
        -> Option<&'a [SymmetricAlgorithm]>;

    /// Returns the supported hash algorithms ordered by preference.
    ///
    /// The algorithms are ordered according by the certificate
    /// holder's preference.
    fn preferred_hash_algorithms(&self) -> Option<&'a [HashAlgorithm]>;

    /// Returns the supported compression algorithms ordered by
    /// preference.
    ///
    /// The algorithms are ordered according by the certificate
    /// holder's preference.
    fn preferred_compression_algorithms(&self)
        -> Option<&'a [CompressionAlgorithm]>;

    /// Returns the supported AEAD algorithms ordered by preference.
    ///
    /// The algorithms are ordered according by the certificate holder's
    /// preference.
    #[deprecated]
    fn preferred_aead_algorithms(&self) -> Option<&'a [AEADAlgorithm]>;

    /// Returns the certificate holder's keyserver preferences.
    fn key_server_preferences(&self) -> Option<KeyServerPreferences>;

    /// Returns the certificate holder's preferred keyserver for
    /// updates.
    fn preferred_key_server(&self) -> Option<&'a [u8]>;

    /// Returns the certificate holder's feature set.
    fn features(&self) -> Option<Features>;

    /// Returns the URI of a document describing the policy
    /// the certificate was issued under.
    fn policy_uri(&self) -> Option<&'a [u8]>;
}

/// A collection of components and their associated signatures.
///
/// The `Cert` data structure mirrors the [TPK and TSK data
/// structures] defined in RFC 4880.  Specifically, it contains
/// components ([`Key`]s, [`UserID`]s, and [`UserAttribute`]s), their
/// associated self signatures, self revocations, third-party
/// signatures, and third-party revocations, as well as useful methods.
///
/// [TPK and TSK data structures]: https://tools.ietf.org/html/rfc4880#section-11
/// [`Key`]: crate::packet::Key
/// [`UserID`]: crate::packet::UserID
/// [`UserAttribute`]: crate::packet::user_attribute::UserAttribute
///
/// `Cert`s are canonicalized in the sense that their `Component`s are
/// deduplicated, and their signatures and revocations are
/// deduplicated and checked for validity.  The canonicalization
/// routine does *not* throw away components that have no self
/// signatures.  These are returned as usual by, e.g.,
/// [`Cert::userids`].
///
/// [`Cert::userids`]: Cert::userids()
///
/// Keys are deduplicated by comparing their public bits using
/// [`Key::public_cmp`].  If two keys are considered equal, and only
/// one of them has secret key material, the key with the secret key
/// material is preferred.  If both keys have secret material, then
/// one of them is chosen in a deterministic, but undefined manner,
/// which is subject to change.  ***Note***: the secret key material
/// is not integrity checked.  Hence when updating a certificate with
/// secret key material, it is essential to first strip the secret key
/// material from copies that came from an untrusted source.
///
/// [`Key::public_cmp`]: crate::packet::Key::public_cmp()
///
/// Signatures are deduplicated using [their `Eq` implementation],
/// which compares the data that is hashed and the MPIs.  That is, it
/// does not compare [the unhashed data], the digest prefix and the
/// unhashed subpacket area.  If two signatures are considered equal,
/// but have different unhashed data, the unhashed data are merged in
/// a deterministic, but undefined manner, which is subject to change.
/// This policy prevents an attacker from flooding a certificate with
/// valid signatures that only differ in their unhashed data.
///
/// [their `Eq` implementation]: crate::packet::Signature#a-note-on-equality
/// [the unhashed data]: https://tools.ietf.org/html/rfc4880#section-5.2.3
///
/// Self signatures and self revocations are checked for validity by
/// making sure that the signature is *mathematically* correct.  At
/// this point, the signature is *not* checked against a [`Policy`].
///
/// Third-party signatures and revocations are checked for validity by
/// making sure the computed digest matches the [digest prefix] stored
/// in the signature packet.  This is *not* an integrity check and is
/// easily spoofed.  Unfortunately, at the time of canonicalization,
/// the actual signatures cannot be checked, because the public keys
/// are not available.  If you rely on these signatures, it is up to
/// you to check their validity by using an appropriate signature
/// verification method, e.g., [`Signature::verify_userid_binding`]
/// or [`Signature::verify_userid_revocation`].
///
/// [`Policy`]: crate::policy::Policy
/// [digest prefix]: crate::packet::signature::Signature4::digest_prefix()
/// [`Signature::verify_userid_binding`]: crate::packet::Signature::verify_userid_binding()
/// [`Signature::verify_userid_revocation`]: crate::packet::Signature::verify_userid_revocation()
///
/// If a signature or a revocation is not valid,
/// we check to see whether it is simply out of place (i.e., belongs
/// to a different component) and, if so, we reorder it.  If not, it
/// is added to a list of bad signatures.  These can be retrieved
/// using [`Cert::bad_signatures`].
///
/// [`Cert::bad_signatures`]: Cert::bad_signatures()
///
/// Signatures and revocations are sorted so that the newest signature
/// comes first.  Components are sorted, but in an undefined manner
/// (i.e., when parsing the same certificate multiple times, the
/// components will be in the same order, but we reserve the right to
/// change the sort function between versions).
///
/// # Secret Keys
///
/// Any key in a certificate may include secret key material.  To
/// protect secret key material from being leaked, secret keys are not
/// written out when a `Cert` is serialized.  To also serialize secret
/// key material, you need to serialize the object returned by
/// [`Cert::as_tsk()`].
///
///
/// Secret key material may be protected with a password.  In such
/// cases, it needs to be decrypted before it can be used to decrypt
/// data or generate a signature.  Refer to [`Key::decrypt_secret`]
/// for details.
///
/// [`Key::decrypt_secret`]: crate::packet::Key::decrypt_secret()
///
/// # Filtering Certificates
///
/// Component-wise filtering of userids, user attributes, and subkeys
/// can be done with [`Cert::retain_userids`],
/// [`Cert::retain_user_attributes`], and [`Cert::retain_subkeys`].
///
/// [`Cert::retain_userids`]: Cert::retain_userids()
/// [`Cert::retain_user_attributes`]: Cert::retain_user_attributes()
/// [`Cert::retain_subkeys`]: Cert::retain_subkeys()
///
/// If you need even more control, iterate over all components, clone
/// what you want to keep, and then reassemble the certificate.  The
/// following example simply copies all the packets, and can be
/// adapted to suit your policy:
///
/// ```rust
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// # use openpgp::parse::{Parse, PacketParserResult, PacketParser};
/// use std::convert::TryFrom;
/// use openpgp::cert::prelude::*;
///
/// # fn main() -> Result<()> {
/// fn identity_filter(cert: &Cert) -> Result<Cert> {
///     // Iterate over all of the Cert components, pushing packets we
///     // want to keep into the accumulator.
///     let mut acc = Vec::new();
///
///     // Primary key and related signatures.
///     let c = cert.primary_key();
///     acc.push(c.key().clone().into());
///     for s in c.self_signatures()   { acc.push(s.clone().into()) }
///     for s in c.certifications()    { acc.push(s.clone().into()) }
///     for s in c.self_revocations()  { acc.push(s.clone().into()) }
///     for s in c.other_revocations() { acc.push(s.clone().into()) }
///
///     // UserIDs and related signatures.
///     for c in cert.userids() {
///         acc.push(c.userid().clone().into());
///         for s in c.self_signatures()   { acc.push(s.clone().into()) }
///         for s in c.attestations()      { acc.push(s.clone().into()) }
///         for s in c.certifications()    { acc.push(s.clone().into()) }
///         for s in c.self_revocations()  { acc.push(s.clone().into()) }
///         for s in c.other_revocations() { acc.push(s.clone().into()) }
///     }
///
///     // UserAttributes and related signatures.
///     for c in cert.user_attributes() {
///         acc.push(c.user_attribute().clone().into());
///         for s in c.self_signatures()   { acc.push(s.clone().into()) }
///         for s in c.attestations()      { acc.push(s.clone().into()) }
///         for s in c.certifications()    { acc.push(s.clone().into()) }
///         for s in c.self_revocations()  { acc.push(s.clone().into()) }
///         for s in c.other_revocations() { acc.push(s.clone().into()) }
///     }
///
///     // Subkeys and related signatures.
///     for c in cert.keys().subkeys() {
///         acc.push(c.key().clone().into());
///         for s in c.self_signatures()   { acc.push(s.clone().into()) }
///         for s in c.certifications()    { acc.push(s.clone().into()) }
///         for s in c.self_revocations()  { acc.push(s.clone().into()) }
///         for s in c.other_revocations() { acc.push(s.clone().into()) }
///     }
///
///     // Unknown components and related signatures.
///     for c in cert.unknowns() {
///         acc.push(c.unknown().clone().into());
///         for s in c.self_signatures()   { acc.push(s.clone().into()) }
///         for s in c.certifications()    { acc.push(s.clone().into()) }
///         for s in c.self_revocations()  { acc.push(s.clone().into()) }
///         for s in c.other_revocations() { acc.push(s.clone().into()) }
///     }
///
///     // Any signatures that we could not associate with a component.
///     for s in cert.bad_signatures()     { acc.push(s.clone().into()) }
///
///     // Finally, parse into Cert.
///     Cert::try_from(acc)
/// }
///
/// let (cert, _) =
///     CertBuilder::general_purpose(None, Some("alice@example.org"))
///     .generate()?;
/// assert_eq!(cert, identity_filter(&cert)?);
/// #     Ok(())
/// # }
/// ```
///
/// # A note on equality
///
/// We define equality on `Cert` as the equality of the serialized
/// form as defined by RFC 4880.  That is, two certs are considered
/// equal if and only if their serialized forms are equal, modulo the
/// OpenPGP packet framing (see [`Packet`#a-note-on-equality]).
///
/// Because secret key material is not emitted when a `Cert` is
/// serialized, two certs are considered equal even if only one of
/// them has secret key material.  To take secret key material into
/// account, compare the [`TSK`s](crate::serialize::TSK) instead:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
///
/// // Generate a cert with secrets.
/// let (cert_with_secrets, _) =
///     CertBuilder::general_purpose(None, Some("alice@example.org"))
///     .generate()?;
///
/// // Derive a cert without secrets.
/// let cert_without_secrets =
///     cert_with_secrets.clone().strip_secret_key_material();
///
/// // Both are considered equal.
/// assert!(cert_with_secrets == cert_without_secrets);
///
/// // But not if we compare their TSKs:
/// assert!(cert_with_secrets.as_tsk() != cert_without_secrets.as_tsk());
/// # Ok(()) }
/// ```
///
/// # Examples
///
/// Parse a certificate:
///
/// ```rust
/// use std::convert::TryFrom;
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// # use openpgp::parse::{Parse, PacketParserResult, PacketParser};
/// use openpgp::Cert;
///
/// # fn main() -> Result<()> {
/// #     let ppr = PacketParser::from_bytes(&b""[..])?;
/// match Cert::try_from(ppr) {
///     Ok(cert) => {
///         println!("Key: {}", cert.fingerprint());
///         for uid in cert.userids() {
///             println!("User ID: {}", uid.userid());
///         }
///     }
///     Err(err) => {
///         eprintln!("Error parsing Cert: {}", err);
///     }
/// }
///
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Cert {
    primary: PrimaryKeyBundle<key::PublicParts>,

    userids: UserIDBundles,
    user_attributes: UserAttributeBundles,
    subkeys: SubkeyBundles<key::PublicParts>,

    // Unknown components, e.g., some UserAttribute++ packet from the
    // future.
    unknowns: UnknownBundles,
    // Signatures that we couldn't find a place for.
    bad: Vec<packet::Signature>,
}
assert_send_and_sync!(Cert);

impl std::str::FromStr for Cert {
    type Err = anyhow::Error;

    /// Parses and returns a certificate.
    ///
    /// `s` must return an OpenPGP-encoded certificate.
    ///
    /// If `s` contains multiple certificates, this returns an error.
    /// Use [`CertParser`] if you want to parse a keyring.
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::from_bytes(s.as_bytes())
    }
}

impl<'a> Parse<'a, Cert> for Cert {
    /// Parses and returns a certificate.
    ///
    /// The reader must return an OpenPGP-encoded certificate.
    ///
    /// If `reader` contains multiple certificates, this returns an
    /// error.  Use [`CertParser`] if you want to parse a keyring.
    fn from_buffered_reader<R>(reader: R) -> Result<Cert>
    where
        R: BufferedReader<Cookie> + 'a,
    {
        Cert::try_from(PacketParser::from_buffered_reader(reader)?)
    }

    /// Parses and returns a certificate.
    ///
    /// The reader must return an OpenPGP-encoded certificate.
    ///
    /// If `reader` contains multiple certificates, this returns an
    /// error.  Use [`CertParser`] if you want to parse a keyring.
    fn from_reader<R: io::Read + Send + Sync>(reader: R) -> Result<Self> {
        Cert::try_from(PacketParser::from_reader(reader)?)
    }

    /// Parses and returns a certificate.
    ///
    /// The file must contain an OpenPGP-encoded certificate.
    ///
    /// If the file contains multiple certificates, this returns an
    /// error.  Use [`CertParser`] if you want to parse a keyring.
    fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        Cert::try_from(PacketParser::from_file(path)?)
    }

    /// Parses and returns a certificate.
    ///
    /// `buf` must contain an OpenPGP-encoded certificate.
    ///
    /// If `buf` contains multiple certificates, this returns an
    /// error.  Use [`CertParser`] if you want to parse a keyring.
    fn from_bytes<D: AsRef<[u8]> + ?Sized + Send + Sync>(data: &'a D) -> Result<Self> {
        Cert::try_from(PacketParser::from_bytes(data)?)
    }
}

impl Cert {
    /// Returns the primary key.
    ///
    /// Unlike getting the certificate's primary key using the
    /// [`Cert::keys`] method, this method does not erase the key's
    /// role.
    ///
    /// A key's secret key material may be protected with a password.
    /// In such cases, it needs to be decrypted before it can be used
    /// to decrypt data or generate a signature.  Refer to
    /// [`Key::decrypt_secret`] for details.
    ///
    /// [`Cert::keys`]: Cert::keys()
    /// [`Key::decrypt_secret`]: crate::packet::Key::decrypt_secret()
    ///
    /// # Examples
    ///
    /// The first key returned by [`Cert::keys`] is the primary key,
    /// but its role has been erased:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// assert_eq!(cert.primary_key().key().role_as_unspecified(),
    ///            cert.keys().nth(0).unwrap().key());
    /// #     Ok(())
    /// # }
    /// ```
    pub fn primary_key(&self) -> PrimaryKeyAmalgamation<key::PublicParts>
    {
        PrimaryKeyAmalgamation::new(self)
    }

    /// Returns the certificate's revocation status.
    ///
    /// Normally, methods that take a policy and a reference time are
    /// only provided by [`ValidCert`].  This method is provided here
    /// because there are two revocation criteria, and one of them is
    /// independent of the reference time.  That is, even if it is not
    /// possible to turn a `Cert` into a `ValidCert` at time `t`, it
    /// may still be considered revoked at time `t`.
    ///
    ///
    /// A certificate is considered revoked at time `t` if:
    ///
    ///   - There is a valid and live revocation at time `t` that is
    ///     newer than all valid and live self signatures at time `t`,
    ///     or
    ///
    ///   - There is a valid [hard revocation] (even if it is not live
    ///     at time `t`, and even if there is a newer self signature).
    ///
    /// [hard revocation]: crate::types::RevocationType::Hard
    ///
    /// Note: certificates and subkeys have different revocation
    /// criteria from [User IDs] and [User Attributes].
    ///
    //  Pending https://github.com/rust-lang/rust/issues/85960, should be
    //  [User IDs]: bundle::ComponentBundle<UserID>::revocation_status
    //  [User Attributes]: bundle::ComponentBundle<UserAttribute>::revocation_status
    /// [User IDs]: bundle::ComponentBundle#method.revocation_status-1
    /// [User Attributes]: bundle::ComponentBundle#method.revocation_status-2
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::types::RevocationStatus;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let (cert, rev) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    ///
    /// assert_eq!(cert.revocation_status(p, None), RevocationStatus::NotAsFarAsWeKnow);
    ///
    /// // Merge the revocation certificate.  `cert` is now considered
    /// // to be revoked.
    /// let cert = cert.insert_packets(rev.clone())?;
    /// assert_eq!(cert.revocation_status(p, None),
    ///            RevocationStatus::Revoked(vec![&rev.into()]));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn revocation_status<T>(&self, policy: &dyn Policy, t: T) -> RevocationStatus
        where T: Into<Option<time::SystemTime>>
    {
        let t = t.into();
        // Both a primary key signature and the primary userid's
        // binding signature can override a soft revocation.  Compute
        // the most recent one.
        let vkao = self.primary_key().with_policy(policy, t).ok();
        let mut sig = vkao.as_ref().map(|vka| vka.binding_signature());
        if let Some(direct) = vkao.as_ref()
            .and_then(|vka| vka.direct_key_signature().ok())
        {
            match (direct.signature_creation_time(),
                   sig.and_then(|s| s.signature_creation_time())) {
                (Some(ds), Some(bs)) if ds > bs =>
                    sig = Some(direct),
                _ => ()
            }
        }
        self.primary_key().bundle()._revocation_status(policy, t, true, sig)
    }

    /// Generates a revocation certificate.
    ///
    /// This is a convenience function around
    /// [`CertRevocationBuilder`] to generate a revocation
    /// certificate.  To use the revocation certificate, merge it into
    /// the certificate using [`Cert::insert_packets`].
    ///
    ///
    /// If you want to revoke an individual component, use
    /// [`SubkeyRevocationBuilder`], [`UserIDRevocationBuilder`], or
    /// [`UserAttributeRevocationBuilder`], as appropriate.
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::{ReasonForRevocation, RevocationStatus, SignatureType};
    /// use openpgp::cert::prelude::*;
    /// use openpgp::crypto::KeyPair;
    /// use openpgp::parse::Parse;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let (cert, rev) = CertBuilder::new()
    ///     .set_cipher_suite(CipherSuite::Cv25519)
    ///     .generate()?;
    ///
    /// // A new certificate is not revoked.
    /// assert_eq!(cert.revocation_status(p, None),
    ///            RevocationStatus::NotAsFarAsWeKnow);
    ///
    /// // The default revocation certificate is a generic
    /// // revocation.
    /// assert_eq!(rev.reason_for_revocation().unwrap().0,
    ///            ReasonForRevocation::Unspecified);
    ///
    /// // Create a revocation to explain what *really* happened.
    /// let mut keypair = cert.primary_key()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    /// let rev = cert.revoke(&mut keypair,
    ///                       ReasonForRevocation::KeyCompromised,
    ///                       b"It was the maid :/")?;
    /// let cert = cert.insert_packets(rev)?;
    /// if let RevocationStatus::Revoked(revs) = cert.revocation_status(p, None) {
    ///     assert_eq!(revs.len(), 1);
    ///     let rev = revs[0];
    ///
    ///     assert_eq!(rev.typ(), SignatureType::KeyRevocation);
    ///     assert_eq!(rev.reason_for_revocation(),
    ///                Some((ReasonForRevocation::KeyCompromised,
    ///                      "It was the maid :/".as_bytes())));
    /// } else {
    ///     unreachable!()
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn revoke(&self, primary_signer: &mut dyn Signer,
                  code: ReasonForRevocation, reason: &[u8])
        -> Result<Signature>
    {
        CertRevocationBuilder::new()
            .set_reason_for_revocation(code, reason)?
            .build(primary_signer, self, None)
    }

    /// Sets the key to expire in delta seconds.
    ///
    /// Note: the time is relative to the key's creation time, not the
    /// current time!
    ///
    /// This function exists to facilitate testing, which is why it is
    /// not exported.
    #[cfg(test)]
    fn set_validity_period_as_of(self, policy: &dyn Policy,
                                 primary_signer: &mut dyn Signer,
                                 expiration: Option<time::Duration>,
                                 now: time::SystemTime)
        -> Result<Cert>
    {
        let primary = self.primary_key().with_policy(policy, now)?;
        let sigs = primary.set_validity_period_as_of(primary_signer,
                                                     expiration,
                                                     now)?;
        self.insert_packets(sigs)
    }

    /// Sets the certificate to expire at the specified time.
    ///
    /// If no time (`None`) is specified, then the certificate is set
    /// to not expire.
    ///
    /// This function creates new binding signatures that cause the
    /// certificate to expire at the specified time.  Specifically, it
    /// updates the current binding signature on each of the valid,
    /// non-revoked User IDs, and the direct key signature, if any.
    /// This is necessary, because the primary User ID is first
    /// consulted when determining the certificate's expiration time,
    /// and certificates can be distributed with a possibly empty
    /// subset of User IDs.
    ///
    /// A policy is needed, because the expiration is updated by
    /// updating the current binding signatures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::time;
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::crypto::KeyPair;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let t0 = time::SystemTime::now() - time::Duration::from_secs(1);
    /// # let (cert, _) = CertBuilder::new()
    /// #     .set_cipher_suite(CipherSuite::Cv25519)
    /// #     .set_creation_time(t0)
    /// #     .generate()?;
    /// // The certificate is alive (not expired).
    /// assert!(cert.with_policy(p, None)?.alive().is_ok());
    ///
    /// // Make cert expire now.
    /// let mut keypair = cert.primary_key()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    /// let sigs = cert.set_expiration_time(p, None, &mut keypair,
    ///                                     Some(time::SystemTime::now()))?;
    ///
    /// let cert = cert.insert_packets(sigs)?;
    /// assert!(cert.with_policy(p, None)?.alive().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_expiration_time<T>(&self, policy: &dyn Policy, t: T,
                                  primary_signer: &mut dyn Signer,
                                  expiration: Option<time::SystemTime>)
        -> Result<Vec<Signature>>
        where T: Into<Option<time::SystemTime>>,
    {
        let primary = self.primary_key().with_policy(policy, t.into())?;
        primary.set_expiration_time(primary_signer, expiration)
    }

    /// Returns the primary User ID at the reference time, if any.
    fn primary_userid_relaxed<'a, T>(&'a self, policy: &'a dyn Policy, t: T,
                                     valid_cert: bool)
        -> Result<ValidUserIDAmalgamation<'a>>
        where T: Into<Option<std::time::SystemTime>>
    {
        let t = t.into().unwrap_or_else(crate::now);
        ValidComponentAmalgamation::primary(self, self.userids.iter(),
                                            policy, t, valid_cert)
    }

    /// Returns an iterator over the certificate's User IDs.
    ///
    /// **Note:** This returns all User IDs, even those without a
    /// binding signature.  This is not what you want, unless you are
    /// doing a low-level inspection of the certificate.  Use
    /// [`ValidCert::userids`] instead.  (You turn a `Cert` into a
    /// [`ValidCert`] by using [`Cert::with_policy`].)
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::packet::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, rev) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// println!("{}'s User IDs:", cert.fingerprint());
    /// for ua in cert.userids() {
    ///     println!("  {}", String::from_utf8_lossy(ua.value()));
    /// }
    /// # // Add a User ID without a binding signature and make sure
    /// # // it is still returned.
    /// # let userid = UserID::from("alice@example.net");
    /// # let cert = cert.insert_packets(userid)?;
    /// # assert_eq!(cert.userids().count(), 2);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn userids(&self) -> UserIDAmalgamationIter {
        ComponentAmalgamationIter::new(self, self.userids.iter())
    }

    /// Returns an iterator over the certificate's User Attributes.
    ///
    /// **Note:** This returns all User Attributes, even those without
    /// a binding signature.  This is not what you want, unless you
    /// are doing a low-level inspection of the certificate.  Use
    /// [`ValidCert::user_attributes`] instead.  (You turn a `Cert`
    /// into a [`ValidCert`] by using [`Cert::with_policy`].)
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, rev) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// println!("{}'s has {} User Attributes.",
    ///          cert.fingerprint(),
    ///          cert.user_attributes().count());
    /// # assert_eq!(cert.user_attributes().count(), 0);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn user_attributes(&self) -> UserAttributeAmalgamationIter {
        ComponentAmalgamationIter::new(self, self.user_attributes.iter())
    }

    /// Returns an iterator over the certificate's keys.
    ///
    /// That is, this returns an iterator over the primary key and any
    /// subkeys.
    ///
    /// **Note:** This returns all keys, even those without a binding
    /// signature.  This is not what you want, unless you are doing a
    /// low-level inspection of the certificate.  Use
    /// [`ValidCert::keys`] instead.  (You turn a `Cert` into a
    /// [`ValidCert`] by using [`Cert::with_policy`].)
    ///
    /// By necessity, this function erases the returned keys' roles.
    /// If you are only interested in the primary key, use
    /// [`Cert::primary_key`].  If you are only interested in the
    /// subkeys, use [`KeyAmalgamationIter::subkeys`].  These
    /// functions preserve the keys' role in the type system.
    ///
    /// A key's secret key material may be protected with a
    /// password.  In such cases, it needs to be decrypted before it
    /// can be used to decrypt data or generate a signature.  Refer to
    /// [`Key::decrypt_secret`] for details.
    ///
    /// [`Cert::primary_key`]: Cert::primary_key()
    /// [`KeyAmalgamationIter::subkeys`]: amalgamation::key::KeyAmalgamationIter::subkeys()
    /// [`Key::decrypt_secret`]: crate::packet::Key::decrypt_secret()
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::packet::Tag;
    /// # use std::convert::TryInto;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// println!("{}'s has {} keys.",
    ///          cert.fingerprint(),
    ///          cert.keys().count());
    /// # assert_eq!(cert.keys().count(), 1 + 2);
    /// #
    /// # // Make sure that we keep all keys even if they don't have
    /// # // any self signatures.
    /// # let packets = cert.into_packets2()
    /// #     .filter(|p| p.tag() != Tag::Signature)
    /// #     .collect::<Vec<_>>();
    /// # let cert : Cert = packets.try_into()?;
    /// # assert_eq!(cert.keys().count(), 1 + 2);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn keys(&self) -> KeyAmalgamationIter<key::PublicParts, key::UnspecifiedRole>
    {
        KeyAmalgamationIter::new(self)
    }

    /// Returns an iterator over the certificate's subkeys.
    pub(crate) fn subkeys(&self) -> ComponentAmalgamationIter<Key<key::PublicParts,
                                                      key::SubordinateRole>>
    {
        ComponentAmalgamationIter::new(self, self.subkeys.iter())
    }

    /// Returns an iterator over the certificate's unknown components.
    ///
    /// This function returns all unknown components even those
    /// without a binding signature.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// # let tag = Tag::Private(61);
    /// # let unknown
    /// #     = Unknown::new(tag, openpgp::Error::UnsupportedPacketType(tag).into());
    /// # let cert = cert.insert_packets(unknown)?;
    /// println!("{}'s has {} unknown components.",
    ///          cert.fingerprint(),
    ///          cert.unknowns().count());
    /// for ua in cert.unknowns() {
    ///     println!("  Unknown component with tag {} ({}), error: {}",
    ///              ua.tag(), u8::from(ua.tag()), ua.error());
    /// }
    /// # assert_eq!(cert.unknowns().count(), 1);
    /// # assert_eq!(cert.unknowns().nth(0).unwrap().tag(), tag);
    /// # Ok(())
    /// # }
    /// ```
    pub fn unknowns(&self) -> UnknownComponentAmalgamationIter {
        ComponentAmalgamationIter::new(self, self.unknowns.iter())
    }

    /// Returns the bad signatures.
    ///
    /// Bad signatures are signatures and revocations that we could
    /// not associate with one of the certificate's components.
    ///
    /// For self signatures and self revocations, we check that the
    /// signature is correct.  For third-party signatures and
    /// third-party revocations, we only check that the [digest
    /// prefix] is correct, because third-party keys are not
    /// available.  Checking the digest prefix is *not* an integrity
    /// check; third party-signatures and third-party revocations may
    /// be invalid and must still be checked for validity before use.
    ///
    /// [digest prefix]: packet::signature::Signature4::digest_prefix()
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, rev) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// println!("{}'s has {} bad signatures.",
    ///          cert.fingerprint(),
    ///          cert.bad_signatures().count());
    /// # assert_eq!(cert.bad_signatures().count(), 0);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn bad_signatures(&self)
                          -> impl Iterator<Item = &Signature> + Send + Sync {
        self.primary.bad_signatures()
            .chain(self.userids.iter().flat_map(|u| u.bad_signatures()))
            .chain(self.user_attributes.iter().flat_map(|u| u.bad_signatures()))
            .chain(self.subkeys.iter().flat_map(|u| u.bad_signatures()))
            .chain(self.unknowns.iter().flat_map(|u| u.bad_signatures()))
            .chain(self.bad.iter())
    }

    /// Returns a list of any designated revokers for this certificate.
    ///
    /// This function returns the designated revokers listed on the
    /// primary key's binding signatures and the certificate's direct
    /// key signatures.
    ///
    /// Note: the returned list is deduplicated.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::types::RevocationKey;
    ///
    /// # fn main() -> Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let (alice, _) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    /// // Make Alice a designated revoker for Bob.
    /// let (bob, _) =
    ///     CertBuilder::general_purpose(None, Some("bob@example.org"))
    ///     .set_revocation_keys(vec![(&alice).into()])
    ///     .generate()?;
    ///
    /// // Make sure Alice is listed as a designated revoker for Bob.
    /// assert_eq!(bob.revocation_keys(p).collect::<Vec<&RevocationKey>>(),
    ///            vec![&(&alice).into()]);
    /// # Ok(()) }
    /// ```
    pub fn revocation_keys<'a>(&'a self, policy: &dyn Policy)
        -> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>
    {
        let mut keys = std::collections::HashSet::new();

        let pk_sec = self.primary_key().hash_algo_security();

        // All user ids.
        self.userids()
            .flat_map(|ua| {
                // All valid self-signatures.
                let sec = ua.hash_algo_security;
                ua.self_signatures()
                    .filter(move |sig| {
                        policy.signature(sig, sec).is_ok()
                   })
            })
            // All direct-key signatures.
            .chain(self.primary_key()
                   .self_signatures()
                   .filter(|sig| {
                       policy.signature(sig, pk_sec).is_ok()
                   }))
            .flat_map(|sig| sig.revocation_keys())
            .for_each(|rk| { keys.insert(rk); });

        Box::new(keys.into_iter())
    }

    /// Converts the certificate into an iterator over a sequence of
    /// packets.
    ///
    /// **WARNING**: When serializing a `Cert`, any secret key
    /// material is dropped.  In order to serialize the secret key
    /// material, it is first necessary to convert the `Cert` into a
    /// [`TSK`] and serialize that.  This behavior makes it harder to
    /// accidentally leak secret key material.  *This function is
    /// different.* If a key contains secret key material, it is
    /// exported as a [`SecretKey`] or [`SecretSubkey`], as
    /// appropriate.  This means that **if you serialize the resulting
    /// packets, the secret key material will be serialized too**.
    ///
    /// [`TSK`]: crate::serialize::TSK
    /// [`SecretKey`]: Packet::SecretKey
    /// [`SecretSubkey`]: Packet::SecretSubkey
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// println!("Cert contains {} packets",
    ///          cert.into_packets().count());
    /// #     Ok(())
    /// # }
    /// ```
    #[deprecated(
        since = "1.18.0",
        note = "Use Cert::into_packets2() to strip secret key material \
                or cert.into_tsk().into_packets() to serialize any \
                secret key material")]
    pub fn into_packets(self) -> impl Iterator<Item=Packet> + Send + Sync {
        fn rewrite(mut p: impl Iterator<Item=Packet> + Send + Sync)
            -> impl Iterator<Item=Packet> + Send + Sync
        {
            let k: Packet = match p.next().unwrap() {
                Packet::PublicKey(k) => {
                    if k.has_secret() {
                        Packet::SecretKey(k.parts_into_secret().unwrap())
                    } else {
                        Packet::PublicKey(k)
                    }
                }
                Packet::PublicSubkey(k) => {
                    if k.has_secret() {
                        Packet::SecretSubkey(k.parts_into_secret().unwrap())
                    } else {
                        Packet::PublicSubkey(k)
                    }
                }
                _ => unreachable!(),
            };

            std::iter::once(k).chain(p)
        }

        rewrite(self.primary.into_packets())
            .chain(self.userids.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.user_attributes.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.subkeys.into_iter().flat_map(|b| rewrite(b.into_packets())))
            .chain(self.unknowns.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.bad.into_iter().map(|s| s.into()))
    }

    /// Converts the certificate into an iterator over a sequence of
    /// packets.
    ///
    /// This function strips secrets from the keys, similar to how
    /// serializing a [`Cert`] would not serialize secret keys.  This
    /// behavior makes it harder to accidentally leak secret key
    /// material.
    ///
    /// If you do want to preserve secret key material, use
    /// [`Cert::into_tsk`] to opt-in to getting the secret key
    /// material, then use [`TSK::into_packets`] to convert to a
    /// packet stream.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// assert!(cert.is_tsk());
    /// // But:
    /// assert!(! Cert::from_packets(cert.into_packets2())?.is_tsk());
    /// # Ok(()) }
    /// ```
    pub fn into_packets2(self) -> impl Iterator<Item=Packet> + Send + Sync {
        /// Strips the secret key material.
        fn rewrite(mut p: impl Iterator<Item=Packet> + Send + Sync)
            -> impl Iterator<Item=Packet> + Send + Sync
        {
            let k: Packet = match p.next().unwrap() {
                Packet::PublicKey(k) =>
                    Packet::PublicKey(k.take_secret().0),
                Packet::PublicSubkey(k) =>
                    Packet::PublicSubkey(k.take_secret().0),
                _ => unreachable!(),
            };

            std::iter::once(k).chain(p)
        }

        rewrite(self.primary.into_packets())
            .chain(self.userids.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.user_attributes.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.subkeys.into_iter().flat_map(|b| rewrite(b.into_packets())))
            .chain(self.unknowns.into_iter().flat_map(|b| b.into_packets()))
            .chain(self.bad.into_iter().map(|s| s.into()))
    }

    /// Returns the first certificate found in the sequence of packets.
    ///
    /// If the sequence of packets does not start with a certificate
    /// (specifically, if it does not start with a primary key
    /// packet), then this fails.
    ///
    /// If the sequence contains multiple certificates (i.e., it is a
    /// keyring), or the certificate is followed by an invalid packet
    /// this function will fail.  To parse keyrings, use
    /// [`CertParser`] instead of this function.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::PacketPile;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let (cert, rev) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    ///
    /// // We should be able to turn a certificate into a PacketPile
    /// // and back.
    /// assert!(Cert::from_packets(cert.into_packets2()).is_ok());
    ///
    /// // But a revocation certificate is not a certificate, so this
    /// // will fail.
    /// let p : Vec<Packet> = vec![rev.into()];
    /// assert!(Cert::from_packets(p.into_iter()).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_packets(p: impl Iterator<Item=Packet> + Send + Sync) -> Result<Self> {
        let mut i = parser::CertParser::from_iter(p);
        if let Some(cert_result) = i.next() {
            if i.next().is_some() {
                Err(Error::MalformedCert(
                    "Additional packets found, is this a keyring?".into()
                ).into())
            } else {
                cert_result
            }
        } else {
            Err(Error::MalformedCert("No data".into()).into())
        }
    }

    /// Converts the certificate into a `PacketPile`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::PacketPile;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// let pp = cert.into_packet_pile();
    /// # let _ : PacketPile = pp;
    /// #     Ok(())
    /// # }
    /// ```
    pub fn into_packet_pile(self) -> PacketPile {
        self.into()
    }

    /// Sorts and deduplicates all components and all signatures of
    /// all components.
    ///
    /// Signatures are compared using [`Signature::normalized_eq`]
    /// (i.e., the unhashed subpacket area is ignored).  If two
    /// signatures are considered equal, the one that comes first is
    /// kept.
    ///
    /// Keys are compares using [`Key::public_cmp`].  If two keys are
    /// considered equivalent, then the one with secret key material
    /// is kept.  If they both have secret key material, then the one
    /// that comes first is kept.
    fn sort_and_dedup(&mut self) {
        self.primary.sort_and_dedup();

        self.bad.sort_by(Signature::normalized_cmp);
        self.bad.dedup_by(|a, b| a.normalized_eq(b));
        // Order bad signatures so that the most recent one comes
        // first.
        self.bad.sort_by(sig_cmp);

        self.userids.sort_and_dedup(UserID::cmp, |_, _| {});
        self.user_attributes.sort_and_dedup(UserAttribute::cmp, |_, _| {});
        // XXX: If we have two keys with the same public parts and
        // different non-empty secret parts, then the one that comes
        // first will be dropped, the one that comes later will be
        // kept.
        //
        // This can happen if:
        //
        //   - One is corrupted
        //   - There are two versions that are encrypted differently
        //
        // If the order of the keys is unpredictable, this effect is
        // unpredictable!  However, if we merge two canonicalized
        // certs with Cert::merge_public_and_secret, then we know the
        // order: the version in `self` comes first, the version in
        // `other` comes last.
        self.subkeys.sort_and_dedup(Key::public_cmp,
            |a, b| {
                // Recall: if a and b are equal, a will be dropped.
                // Also, the elements are given in the opposite order
                // from their order in the vector.
                //
                // Prefer the secret in `a`, i.e. the "later" one.
                if a.has_secret() {
                    std::mem::swap(a, b);
                }
            });

        self.unknowns.sort_and_dedup(Unknown::best_effort_cmp, |_, _| {});
    }

    fn canonicalize(mut self) -> Self {
        tracer!(TRACE, "canonicalize", 0);
        use SignatureType::*;

        // Before we do anything, we'll order and deduplicate the
        // components.  If two components are the same, they will be
        // merged, and their signatures will also be deduplicated.
        // This improves the performance considerably when we update a
        // certificate, because the certificates will be most likely
        // almost identical, and we avoid about half of the signature
        // verifications.
        self.sort_and_dedup();

        // Now we verify the self signatures.  There are a few things
        // that we need to be aware of:
        //
        //  - Signatures may be invalid.  These should be dropped.
        //
        //  - Signatures may be out of order.  These should be
        //    reordered so that we have the latest self signature and
        //    we don't drop a userid or subkey that is actually
        //    valid.

        // We collect bad signatures here in self.bad.  Below, we'll
        // test whether they are just out of order by checking them
        // against all userids and subkeys.  Furthermore, this may be
        // a partial Cert that is merged into an older copy.

        // desc: a description of the component
        // binding: the binding to check
        // sigs: a vector of sigs in $binding to check
        macro_rules! check {
            ($desc:expr, $binding:expr, $sigs:ident,
             $hash_method:ident,    // method to hash the signature
             $sig_type_pat:pat,     // pattern to test signature types against
             $($hash_args:expr),* // additional arguments to pass to hash_method
            ) => ({
                let sigs = $binding.$sigs.take();
                t!("check!({}, {}, {} ({:?}), {}, ...)",
                   $desc, stringify!($binding), sigs.len(), sigs,
                   stringify!($hash_method));
                for sig in sigs.into_iter() {
                    // Use hash prefix as heuristic.
                    let key = self.primary.key();
                    match sig.hash_algo().context().and_then(|mut ctx| {
                        if matches!(sig.typ(), $sig_type_pat) {
                            sig.$hash_method(&mut ctx, key, $($hash_args),*);
                            ctx.into_digest()
                        } else {
                            Err(Error::UnsupportedSignatureType(sig.typ()).into())
                        }
                    }) {
                      Ok(hash) => {
                        if &sig.digest_prefix()[..] == &hash[..2] {
                            sig.set_computed_digest(Some(hash));
                            $binding.$sigs.push(sig);
                        } else {
                            t!("Sig {:02X}{:02X}, type = {} \
                                doesn't belong to {} (computed hash's prefix: {:02X}{:02X})",
                               sig.digest_prefix()[0], sig.digest_prefix()[1],
                               sig.typ(), $desc,
                               hash[0], hash[1]);

                            self.bad.push(sig);
                        }
                      },
                      Err(e) => {
                        // Hashing failed, we likely don't support the
                        // hash algorithm, or the signature type was
                        // bad.
                        t!("Sig {:02X}{:02X}, type = {}: \
                            Hashing failed: {}",
                           sig.digest_prefix()[0], sig.digest_prefix()[1],
                           sig.typ(), e);

                        self.bad.push(sig);
                      },
                    }
                }
            });
            ($desc:expr, $binding:expr, $sigs:ident,
             $hash_method:ident, $sig_type_pat:pat) => ({
                check!($desc, $binding, $sigs, $hash_method, $sig_type_pat, )
            });
        }

        // The same as check!, but for third party signatures.  If we
        // do have the key that made the signature, we can verify it
        // like in check!.  Otherwise, we use the hash prefix as
        // heuristic approximating the verification.
        macro_rules! check_3rd_party {
            ($desc:expr,            // a description of the component
             $binding:expr,         // the binding to check
             $sigs:ident,           // a vector of sigs in $binding to check
             $lookup_fn:expr,       // a function to lookup keys
             $verify_method:ident,  // the method to call to verify it
             $hash_method:ident,    // the method to call to compute the hash
             $sig_type_pat:pat,     // pattern to test signature types against
             $($verify_args:expr),* // additional arguments to pass to the above
            ) => ({
                let sigs = mem::take(&mut $binding.$sigs);
                t!("check_3rd_party!({}, {}, {} ({:?}_, {}, {}, ...)",
                   $desc, stringify!($binding), sigs.len(), sigs,
                   stringify!($verify_method), stringify!($hash_method));
                for sig in sigs {
                    // Use hash prefix as heuristic.
                    let key = self.primary.key();
                    match sig.hash_algo().context().and_then(|mut ctx| {
                        if matches!(sig.typ(), $sig_type_pat) {
                            sig.$hash_method(&mut ctx, key, $($verify_args),*);
                            ctx.into_digest()
                        } else {
                            Err(Error::UnsupportedSignatureType(sig.typ()).into())
                        }
                    }) {
                      Ok(hash) => {
                        if &sig.digest_prefix()[..] == &hash[..2] {
                            // See if we can get the key for a
                            // positive verification.
                            if let Some(key) = $lookup_fn(&sig) {
                                if let Ok(()) = sig.$verify_method(
                                    &key, self.primary.key(), $($verify_args),*)
                                {
                                    $binding.$sigs.push(sig);
                                } else {
                                    t!("Sig {:02X}{:02X}, type = {} \
                                        doesn't belong to {}",
                                       sig.digest_prefix()[0],
                                       sig.digest_prefix()[1],
                                       sig.typ(), $desc);

                                    self.bad.push(sig);
                                }
                            } else {
                                // No key, we need to trust our heuristic.
                                sig.set_computed_digest(Some(hash));
                                $binding.$sigs.push(sig);
                            }
                        } else {
                            t!("Sig {:02X}{:02X}, type = {} \
                                doesn't belong to {} (computed hash's prefix: {:02X}{:02X})",
                               sig.digest_prefix()[0], sig.digest_prefix()[1],
                               sig.typ(), $desc,
                               hash[0], hash[1]);

                            self.bad.push(sig);
                        }
                      },
                      Err(e) => {
                        // Hashing failed, we likely don't support the
                        // hash algorithm, or the signature type was
                        // bad.
                        t!("Sig {:02X}{:02X}, type = {}: \
                            Hashing failed: {}",
                           sig.digest_prefix()[0], sig.digest_prefix()[1],
                           sig.typ(), e);

                        self.bad.push(sig);
                      },
                    }
                }
            });
            ($desc:expr, $binding:expr, $sigs:ident, $lookup_fn:expr,
             $verify_method:ident, $hash_method:ident, $sig_type_pat:pat) => ({
                 check_3rd_party!($desc, $binding, $sigs, $lookup_fn,
                                  $verify_method, $hash_method, $sig_type_pat, )
            });
        }

        // Placeholder lookup function.
        fn lookup_fn(_: &Signature)
                     -> Option<Key<key::PublicParts, key::UnspecifiedRole>> {
            None
        }

        check!("primary key",
               self.primary, self_signatures, hash_direct_key, DirectKey);
        check!("primary key",
               self.primary, self_revocations, hash_direct_key, KeyRevocation);
        check_3rd_party!("primary key",
                         self.primary, certifications, lookup_fn,
                         verify_direct_key, hash_direct_key, DirectKey);
        check_3rd_party!("primary key",
                         self.primary, other_revocations, lookup_fn,
                         verify_primary_key_revocation, hash_direct_key,
                         KeyRevocation);

        // Attestations are never associated with a primary key.  If
        // there are any, they need to be reordered.
        self.bad.append(&mut self.primary.attestations.take());

        for ua in self.userids.iter_mut() {
            check!(format!("userid \"{}\"",
                           String::from_utf8_lossy(ua.userid().value())),
                   ua, self_signatures, hash_userid_binding,
                   GenericCertification | PersonaCertification
                   | CasualCertification | PositiveCertification,
                   ua.userid());
            check!(format!("userid \"{}\"",
                           String::from_utf8_lossy(ua.userid().value())),
                   ua, self_revocations, hash_userid_binding,
                   CertificationRevocation,
                   ua.userid());
            check!(format!("userid \"{}\"",
                           String::from_utf8_lossy(ua.userid().value())),
                   ua, attestations, hash_userid_binding,
                   AttestationKey,
                   ua.userid());
            check_3rd_party!(
                format!("userid \"{}\"",
                        String::from_utf8_lossy(ua.userid().value())),
                ua, certifications, lookup_fn,
                verify_userid_binding, hash_userid_binding,
                GenericCertification | PersonaCertification
                    | CasualCertification | PositiveCertification,
                ua.userid());
            check_3rd_party!(
                format!("userid \"{}\"",
                        String::from_utf8_lossy(ua.userid().value())),
                ua, other_revocations, lookup_fn,
                verify_userid_revocation, hash_userid_binding,
                CertificationRevocation,
                ua.userid());
        }

        for binding in self.user_attributes.iter_mut() {
            check!("user attribute",
                   binding, self_signatures, hash_user_attribute_binding,
                   GenericCertification | PersonaCertification
                   | CasualCertification | PositiveCertification,
                   binding.user_attribute());
            check!("user attribute",
                   binding, self_revocations, hash_user_attribute_binding,
                   CertificationRevocation,
                   binding.user_attribute());
            check!("user attribute",
                   binding, attestations, hash_user_attribute_binding,
                   AttestationKey,
                   binding.user_attribute());
            check_3rd_party!(
                "user attribute",
                binding, certifications, lookup_fn,
                verify_user_attribute_binding, hash_user_attribute_binding,
                GenericCertification | PersonaCertification
                    | CasualCertification | PositiveCertification,
                binding.user_attribute());
            check_3rd_party!(
                "user attribute",
                binding, other_revocations, lookup_fn,
                verify_user_attribute_revocation, hash_user_attribute_binding,
                CertificationRevocation,
                binding.user_attribute());
        }

        for binding in self.subkeys.iter_mut() {
            check!(format!("subkey {}", binding.key().keyid()),
                   binding, self_signatures, hash_subkey_binding,
                   SubkeyBinding,
                   binding.key());
            check!(format!("subkey {}", binding.key().keyid()),
                   binding, self_revocations, hash_subkey_binding,
                   SubkeyRevocation,
                   binding.key());
            check_3rd_party!(
                format!("subkey {}", binding.key().keyid()),
                binding, certifications, lookup_fn,
                verify_subkey_binding, hash_subkey_binding,
                SubkeyBinding,
                binding.key());
            check_3rd_party!(
                format!("subkey {}", binding.key().keyid()),
                binding, other_revocations, lookup_fn,
                verify_subkey_revocation, hash_subkey_binding,
                SubkeyRevocation,
                binding.key());

            // Attestations are never associated with a subkey.  If
            // there are any, they need to be reordered.
            self.bad.append(&mut binding.attestations.take());
        }

        // See if the signatures that didn't validate are just out of
        // place.
        let mut bad_sigs: Vec<(Option<usize>, Signature)> =
            std::mem::take(&mut self.bad).into_iter()
            .map(|sig| {
                t!("We're going to reconsider bad signature {:?}", sig);
                (None, sig)
            })
            .collect();
        t!("Attempting to reorder {} signatures", bad_sigs.len());

        // Do the same for signatures on unknown components, but
        // remember where we took them from.
        for (i, c) in self.unknowns.iter_mut().enumerate() {
            for sig in
                c.self_signatures.take().into_iter()
                .chain(
                    std::mem::take(&mut c.certifications).into_iter())
                .chain(
                    c.attestations.take().into_iter())
                .chain(
                    c.self_revocations.take().into_iter())
                .chain(
                    std::mem::take(&mut c.other_revocations).into_iter())
            {
                t!("We're going to reconsider {:?} on unknown component #{}",
                   sig, i);
                bad_sigs.push((Some(i), sig));
            }
        }

        let primary_fp: KeyHandle = self.key_handle();

        'outer: for (unknown_idx, sig) in bad_sigs {
            // Did we find a new place for sig?
            let mut found_component = false;

            // Is this signature a self-signature?
            let issuers =
                sig.get_issuers();
            let is_selfsig =
                issuers.is_empty()
                || issuers.iter().any(|kh| kh.aliases(&primary_fp));

            macro_rules! check_one {
                ($desc:expr,            // a description of the component
                 $sigs:expr,            // where to put $sig if successful
                 $sig:ident,            // the signature to check
                 $hash_method:ident,    // the method to compute the hash
                 $($verify_args:expr),* // additional arguments for the above
                ) => ({
                   if is_selfsig {
                     t!("check_one!({}, {:?}, {:?}/{}, {}, ...)",
                      $desc, $sigs, $sig, $sig.typ(),
                      stringify!($hash_method));
                     // Use hash prefix as heuristic.
                     let key = self.primary.key();
                     if let Ok(hash) = $sig.hash_algo().context()
                         .and_then(|mut ctx| {
                             $sig.$hash_method(&mut ctx, key,
                                              $($verify_args),*);
                             ctx.into_digest()
                         })
                     {
                         if &$sig.digest_prefix()[..] == &hash[..2] {
                             t!("Sig {:02X}{:02X}, {:?} \
                                 was out of place.  Likely belongs to {}.",
                                $sig.digest_prefix()[0],
                                $sig.digest_prefix()[1],
                                $sig.typ(), $desc);

                             $sigs.push({
                                 let sig = $sig.clone();
                                 sig.set_computed_digest(Some(hash));
                                 sig
                             });

                             // The cost of missing a revocation
                             // certificate merely because we put
                             // it into the wrong place seem to
                             // outweigh the cost of duplicating
                             // it.
                             t!("Will keep trying to match this sig to \
                                 other components (found before? {:?})...",
                                found_component);
                             found_component = true;
                         } else {
                             t!("Sig {:02X}{:02X}, {:?} \
                                 does not belong to {}: \
                                 hash prefix mismatch",
                                $sig.digest_prefix()[0],
                                $sig.digest_prefix()[1],
                                $sig.typ(), $desc);
                         }
                     } else {
                         t!("Sig {:02X}{:02X}, type = {} \
                             doesn't use a supported hash algorithm: \
                             {:?} unsupported",
                            $sig.digest_prefix()[0], $sig.digest_prefix()[1],
                            $sig.typ(), $sig.hash_algo());
                     }
                   }
                 });
                ($desc:expr, $sigs:expr, $sig:ident,
                 $hash_method:ident) => ({
                    check_one!($desc, $sigs, $sig, $hash_method,)
                });
            }

            // The same as check_one!, but for third party signatures.
            // If we do have the key that made the signature, we can
            // verify it like in check!.  Otherwise, we use the hash
            // prefix as heuristic approximating the verification.
            macro_rules! check_one_3rd_party {
                ($desc:expr,            // a description of the component
                 $sigs:expr,            // where to put $sig if successful
                 $sig:ident,            // the signature to check
                 $lookup_fn:expr,       // a function to lookup keys
                 $verify_method:ident,  // the method to verify it
                 $hash_method:ident,    // the method to compute the hash
                 $($verify_args:expr),* // additional arguments for the above
                ) => ({
                  if ! is_selfsig {
                    t!("check_one_3rd_party!({}, {}, {:?}, {}, {}, ...)",
                       $desc, stringify!($sigs), $sig,
                       stringify!($verify_method), stringify!($hash_method));
                    if let Some(key) = $lookup_fn(&$sig) {
                        match $sig.$verify_method(&key,
                                                 self.primary.key(),
                                                 $($verify_args),*)
                        {
                          Ok(()) => {
                            t!("Sig {:02X}{:02X}, {:?} \
                                was out of place.  Belongs to {}.",
                               $sig.digest_prefix()[0],
                               $sig.digest_prefix()[1],
                               $sig.typ(), $desc);

                            $sigs.push($sig);
                            continue 'outer;
                          },
                          Err(err) => {
                            t!("Sig {:02X}{:02X}, type = {} \
                                doesn't belong to {}: {:?}",
                               $sig.digest_prefix()[0], $sig.digest_prefix()[1],
                               $sig.typ(), $desc, err);
                          },
                       }
                    } else {
                        // Use hash prefix as heuristic.
                        let key = self.primary.key();
                        if let Ok(hash) = $sig.hash_algo().context()
                            .and_then(|mut ctx| {
                                $sig.$hash_method(&mut ctx, key,
                                                 $($verify_args),*);
                                ctx.into_digest()
                            })
                        {
                            if &$sig.digest_prefix()[..] == &hash[..2] {
                                t!("Sig {:02X}{:02X}, {:?} \
                                    was out of place.  Likely belongs to {}.",
                                   $sig.digest_prefix()[0],
                                   $sig.digest_prefix()[1],
                                   $sig.typ(), $desc);

                                $sigs.push({
                                    let sig = $sig.clone();
                                    sig.set_computed_digest(Some(hash));
                                    sig
                                });

                                // The cost of missing a revocation
                                // certificate merely because we put
                                // it into the wrong place seem to
                                // outweigh the cost of duplicating
                                // it.
                                t!("Will keep trying to match this sig to \
                                    other components (found before? {:?})...",
                                   found_component);
                                found_component = true;
                            } else {
                                t!("Sig {:02X}{:02X}, {:?} \
                                    does not belong to {}: \
                                    hash prefix mismatch",
                                   $sig.digest_prefix()[0],
                                   $sig.digest_prefix()[1],
                                   $sig.typ(), $desc);
                            }
                        } else {
                            t!("Sig {:02X}{:02X}, type = {} \
                                doesn't use a supported hash algorithm: \
                                {:?} unsupported",
                               $sig.digest_prefix()[0], $sig.digest_prefix()[1],
                               $sig.typ(), $sig.hash_algo());
                        }
                    }
                  }
                });
                ($desc:expr, $sigs:expr, $sig:ident, $lookup_fn:expr,
                 $verify_method:ident, $hash_method:ident) => ({
                     check_one_3rd_party!($desc, $sigs, $sig, $lookup_fn,
                                          $verify_method, $hash_method, )
                 });
            }

            match sig.typ() {
                DirectKey => {
                    check_one!("primary key", self.primary.self_signatures,
                               sig, hash_direct_key);
                    check_one_3rd_party!(
                        "primary key", self.primary.certifications, sig,
                        lookup_fn,
                        verify_direct_key, hash_direct_key);
                },

                KeyRevocation => {
                    check_one!("primary key", self.primary.self_revocations,
                               sig, hash_direct_key);
                    check_one_3rd_party!(
                        "primary key", self.primary.other_revocations, sig,
                        lookup_fn, verify_primary_key_revocation,
                        hash_direct_key);
                },

                GenericCertification | PersonaCertification
                    | CasualCertification | PositiveCertification =>
                {
                    for binding in self.userids.iter_mut() {
                        check_one!(format!("userid \"{}\"",
                                           String::from_utf8_lossy(
                                               binding.userid().value())),
                                   binding.self_signatures, sig,
                                   hash_userid_binding, binding.userid());
                        check_one_3rd_party!(
                            format!("userid \"{}\"",
                                    String::from_utf8_lossy(
                                        binding.userid().value())),
                            binding.certifications, sig, lookup_fn,
                            verify_userid_binding, hash_userid_binding,
                            binding.userid());
                    }

                    for binding in self.user_attributes.iter_mut() {
                        check_one!("user attribute",
                                   binding.self_signatures, sig,
                                   hash_user_attribute_binding,
                                   binding.user_attribute());
                        check_one_3rd_party!(
                            "user attribute",
                            binding.certifications, sig, lookup_fn,
                            verify_user_attribute_binding,
                            hash_user_attribute_binding,
                            binding.user_attribute());
                    }
                },

                crate::types::SignatureType::AttestationKey => {
                    for binding in self.userids.iter_mut() {
                        check_one!(format!("userid \"{}\"",
                                           String::from_utf8_lossy(
                                               binding.userid().value())),
                                   binding.attestations, sig,
                                   hash_userid_binding, binding.userid());
                    }

                    for binding in self.user_attributes.iter_mut() {
                        check_one!("user attribute",
                                   binding.attestations, sig,
                                   hash_user_attribute_binding,
                                   binding.user_attribute());
                    }
                },

                CertificationRevocation => {
                    for binding in self.userids.iter_mut() {
                        check_one!(format!("userid \"{}\"",
                                           String::from_utf8_lossy(
                                               binding.userid().value())),
                                   binding.self_revocations, sig,
                                   hash_userid_binding,
                                   binding.userid());
                        check_one_3rd_party!(
                            format!("userid \"{}\"",
                                    String::from_utf8_lossy(
                                        binding.userid().value())),
                            binding.other_revocations, sig, lookup_fn,
                            verify_userid_revocation, hash_userid_binding,
                            binding.userid());
                    }

                    for binding in self.user_attributes.iter_mut() {
                        check_one!("user attribute",
                                   binding.self_revocations, sig,
                                   hash_user_attribute_binding,
                                   binding.user_attribute());
                        check_one_3rd_party!(
                            "user attribute",
                            binding.other_revocations, sig, lookup_fn,
                            verify_user_attribute_revocation,
                            hash_user_attribute_binding,
                            binding.user_attribute());
                    }
                },

                SubkeyBinding => {
                    for binding in self.subkeys.iter_mut() {
                        check_one!(format!("subkey {}", binding.key().keyid()),
                                   binding.self_signatures, sig,
                                   hash_subkey_binding, binding.key());
                        check_one_3rd_party!(
                            format!("subkey {}", binding.key().keyid()),
                            binding.certifications, sig, lookup_fn,
                            verify_subkey_binding, hash_subkey_binding,
                            binding.key());
                    }
                },

                SubkeyRevocation => {
                    for binding in self.subkeys.iter_mut() {
                        check_one!(format!("subkey {}", binding.key().keyid()),
                                   binding.self_revocations, sig,
                                   hash_subkey_binding, binding.key());
                        check_one_3rd_party!(
                            format!("subkey {}", binding.key().keyid()),
                            binding.other_revocations, sig, lookup_fn,
                            verify_subkey_revocation, hash_subkey_binding,
                            binding.key());
                    }
                },

                typ => {
                    t!("Odd signature type: {:?}", typ);
                },
            }

            if found_component {
                continue;
            }

            // Keep them for later.
            t!("{} {:02X}{:02X}, {:?}, originally found on {:?} \
                doesn't belong to any known component or is bad.",
               if is_selfsig { "Self-sig" } else { "3rd-party-sig" },
               sig.digest_prefix()[0], sig.digest_prefix()[1],
               sig.typ(), unknown_idx);

            if let Some(i) = unknown_idx {
                let is_revocation = match sig.typ() {
                    CertificationRevocation | KeyRevocation | SubkeyRevocation
                        => true,
                    _ => false,
                };
                match (is_selfsig, is_revocation) {
                    (false, false) =>
                        self.unknowns[i].certifications.push(sig),
                    (false, true) =>
                        self.unknowns[i].other_revocations.push(sig),
                    (true, false) =>
                        self.unknowns[i].self_signatures.push(sig),
                    (true, true) =>
                        self.unknowns[i].self_revocations.push(sig),
                }
            } else {
                self.bad.push(sig);
            }
        }

        if !self.bad.is_empty() {
            t!("{}: ignoring {} bad self signatures",
               self.keyid(), self.bad.len());
        }

        // Sort again.  We may have moved signatures to the right
        // component, and we need to ensure they are in the right spot
        // (i.e. newest first).
        self.sort_and_dedup();

        // XXX: Check if the sigs in other_sigs issuer are actually
        // designated revokers for this key (listed in a "Revocation
        // Key" subpacket in *any* non-revoked self signature).  Only
        // if that is the case should a sig be considered a potential
        // revocation.  (This applies to
        // self.primary_other_revocations as well as
        // self.userids().other_revocations, etc.)  If not, put the
        // sig on the bad list.
        //
        // Note: just because the Cert doesn't indicate that a key is a
        // designed revoker doesn't mean that it isn't---we might just
        // be missing the signature.  In other words, this is a policy
        // decision, but given how easy it could be to create rogue
        // revocations, is probably the better to reject such
        // signatures than to keep them around and have many keys
        // being shown as "potentially revoked".

        // XXX Do some more canonicalization.

        self
    }

    /// Returns the certificate's fingerprint as a `KeyHandle`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::KeyHandle;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// #
    /// println!("{}", cert.key_handle());
    ///
    /// // This always returns a fingerprint.
    /// match cert.key_handle() {
    ///     KeyHandle::Fingerprint(_) => (),
    ///     KeyHandle::KeyID(_) => unreachable!(),
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn key_handle(&self) -> KeyHandle {
        self.primary.key().key_handle()
    }

    /// Returns the certificate's fingerprint.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// #
    /// println!("{}", cert.fingerprint());
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn fingerprint(&self) -> Fingerprint {
        self.primary.key().fingerprint()
    }

    /// Returns the certificate's Key ID.
    ///
    /// As a general rule of thumb, you should prefer the fingerprint
    /// as it is possible to create keys with a colliding Key ID using
    /// a [birthday attack].
    ///
    /// [birthday attack]: https://nullprogram.com/blog/2019/07/22/
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// #
    /// println!("{}", cert.keyid());
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn keyid(&self) -> KeyID {
        self.primary.key().keyid()
    }

    /// Merges `other` into `self`, ignoring secret key material in
    /// `other`.
    ///
    /// If `other` is a different certificate, then an error is
    /// returned.
    ///
    /// Merging two versions of a certificate is complicated, because
    /// there may be multiple variants of the same key or signature
    /// packet.  It is possible to have multiple variants of a key
    /// packet if one contains secret key material, and the other
    /// does not, or if both contain secret key material that is
    /// protected in different ways, e.g., a different algorithm, or a
    /// different password.  Multiple variants of a signature packet
    /// are possible when the unhashed subpacket areas differ.
    ///
    /// This routine is different from [`Cert::insert_packets`] in the
    /// following ways:
    ///
    ///   - `Cert::merge_public` strictly prefers keys in `self` to
    ///     those in `other`.  That is, if a primary key or subkey
    ///     appears in both `self` and `other`, the version in `self`
    ///     is kept.  In contrast, [`Cert::insert_packets`] prefers
    ///     the new variant.
    ///
    ///   - If `other` contains a new subkey, `Cert::merge_public`
    ///     merges it into the certificate, but strips any secret key
    ///     material.  In contrast, [`Cert::insert_packets`] preserves
    ///     the secret key material.
    ///
    ///   - If both `self` and `other` contain two variants of a
    ///     signature (that is, a signature packet that is identical
    ///     expect for the contents of the unhashed subpacket area),
    ///     `Cert::merge_public` merges the two variants using
    ///     [`Signature::merge`], which combines the unhashed
    ///     subpacket areas.  [`Cert::insert_packets`] just takes the
    ///     new signature packet.
    ///
    /// This function is appropriate to merge certificate material
    /// from untrusted sources like keyservers, because it only adds
    /// data to the existing certificate, it never overwrites existing
    /// data, and it doesn't import secret key material, which may
    /// have been manipulated by an attacker.
    ///
    /// [`Cert::merge_public_and_secret`] is similar to this function,
    /// but merges in secret key material from `other`.
    ///
    /// # Examples
    ///
    /// Merge a certificate from an untrusted source:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (local, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// # let keyserver = local.clone();
    /// // Merge the local version with the version from the keyserver.
    /// let cert = local.merge_public(keyserver)?;
    /// # let _ = cert;
    /// # Ok(()) }
    /// ```
    ///
    /// Secret key material in `other` is stripped, even if the
    /// variant of the packet in `self` doesn't have secret key
    /// material:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::CertBuilder;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// let stripped = cert.clone().strip_secret_key_material();
    /// assert!(! stripped.is_tsk());
    ///
    /// // Merge `cert` into `stripped`.
    /// let merged = stripped.merge_public(cert).expect("same certificate");
    /// assert!(! merged.is_tsk());
    ///
    /// # Ok(()) }
    /// ```
    ///
    /// Secret key material from `self` is preferred to secret key
    /// material from `other`:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::crypto::Password;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::Packet;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p0 = Password::from("old password");
    /// let p1 = Password::from("new password");
    ///
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .set_password(Some(p0.clone()))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Change the password for the primary key.
    /// let pk = cert.primary_key().key().clone().parts_into_secret()?
    ///     .decrypt_secret(&p0)?
    ///     .encrypt_secret(&p1)?;
    /// let other = Cert::try_from(vec![ Packet::from(pk) ])
    ///     .expect("a primary key is a certificate");
    ///
    /// // Merge `other` into `cert`.
    /// let merged = cert.merge_public(other).expect("same certificate");
    ///
    /// // `merged` has the secret key material from `cert`, which is
    /// // password protected with `p0`, not `other`, which is password
    /// // protected with `p1`.
    /// assert!(merged.primary_key().key().clone().parts_into_secret()?
    ///         .decrypt_secret(&p0).is_ok());
    /// # Ok(()) }
    /// ```
    ///
    /// The unhashed subpacket areas of two variants of a signature
    /// are merged:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::signature::subpacket::Subpacket;
    /// use openpgp::packet::signature::subpacket::SubpacketTag;
    /// use openpgp::packet::signature::subpacket::SubpacketValue;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Add a subpacket to the unhashed subpacket area.
    /// let subpacket_a = Subpacket::new(
    ///     SubpacketValue::Unknown {
    ///         tag: SubpacketTag::Private(100),
    ///         body: Vec::new(),
    ///     },
    ///     false).expect("valid");
    /// let subpacket_b = Subpacket::new(
    ///     SubpacketValue::Unknown {
    ///         tag: SubpacketTag::Private(101),
    ///         body: Vec::new(),
    ///     },
    ///     false).expect("valid");
    ///
    /// let mut cert_a = cert.clone().into_packets2().collect::<Vec<Packet>>();
    /// match cert_a[1] {
    ///     Packet::Signature(ref mut sig) => {
    ///         let unhashed_area = sig.unhashed_area_mut();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_none());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_none());
    ///         unhashed_area.add(subpacket_a.clone());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// let cert_a = Cert::try_from(cert_a).expect("valid");
    ///
    /// let mut cert_b = cert.clone().into_packets2().collect::<Vec<Packet>>();
    /// match cert_b[1] {
    ///     Packet::Signature(ref mut sig) => {
    ///         let unhashed_area = sig.unhashed_area_mut();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_none());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_none());
    ///         unhashed_area.add(subpacket_b.clone());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// let cert_b = Cert::try_from(cert_b).expect("valid");
    ///
    /// // When we merge `cert_b` into `cert_a`, the signature packets
    /// // are merged:
    /// let merged = cert_a.clone().merge_public(cert_b.clone())
    ///     .expect("same certificate")
    ///     .into_packets2()
    ///     .collect::<Vec<Packet>>();
    /// match merged[1] {
    ///     Packet::Signature(ref sig) => {
    ///         let unhashed_area = sig.unhashed_area();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_some());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_some());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    ///
    /// // Likewise, when we merge `cert_a` into `cert_b`, the signature
    /// // packets are merged:
    /// let merged = cert_b.clone().merge_public(cert_a.clone())
    ///     .expect("same certificate")
    ///     .into_packets2()
    ///     .collect::<Vec<Packet>>();
    /// match merged[1] {
    ///     Packet::Signature(ref sig) => {
    ///         let unhashed_area = sig.unhashed_area();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_some());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_some());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// # Ok(()) }
    /// ```
    pub fn merge_public(self, other: Cert) -> Result<Self> {
        // Strip all secrets from `other`.
        let other_public = other.strip_secret_key_material();
        // Then merge it.
        self.merge_public_and_secret(other_public)
    }

    /// Merges `other` into `self`, including secret key material.
    ///
    /// If `other` is a different certificate, then an error is
    /// returned.
    ///
    /// This function is like [`Cert::merge_public`] except:
    ///
    ///   - if two variants of the same key have secret key material,
    ///     then the version in `other` is preferred,
    ///
    ///   - if there are two variants of the same key, and one has
    ///     secret key material, that variant is preferred.
    ///
    /// This is different from [`Cert::insert_packets`], which
    /// unconditionally prefers keys in the packets that are being
    /// merged into the certificate.
    ///
    /// It is important to only merge key material from trusted
    /// sources using this function, because it may be used to import
    /// secret key material.  Secret key material is not authenticated
    /// by OpenPGP, and there are plausible attack scenarios where a
    /// malicious actor injects secret key material.
    ///
    /// To merge only public key material, which is always safe, use
    /// [`Cert::merge_public`].
    ///
    /// # Examples
    ///
    /// Merge a certificate from a trusted source:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (local, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// # let other_device = local.clone();
    /// // Merge the local version with the version from your other device.
    /// let cert = local.merge_public_and_secret(other_device)?;
    /// # let _ = cert;
    /// # Ok(()) }
    /// ```
    ///
    /// Secret key material is preferred to no secret key material:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::CertBuilder;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// let stripped = cert.clone().strip_secret_key_material();
    /// assert!(! stripped.is_tsk());
    ///
    /// // If we merge `cert` into `stripped`, the secret key material is
    /// // preserved:
    /// let merged = stripped.clone().merge_public_and_secret(cert.clone())
    ///     .expect("same certificate");
    /// assert!(merged.is_tsk());
    ///
    /// // Likewise if we merge `stripped` into `cert`:
    /// let merged = cert.merge_public_and_secret(stripped)
    ///     .expect("same certificate");
    /// assert!(merged.is_tsk());
    ///
    /// # Ok(()) }
    /// ```
    ///
    /// Secret key material in `other` is preferred:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::crypto::Password;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::Packet;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p0 = Password::from("old password");
    /// let p1 = Password::from("new password");
    ///
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .set_password(Some(p0.clone()))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Change the password for the primary key.
    /// let pk = cert.primary_key().key().clone().parts_into_secret()?
    ///     .decrypt_secret(&p0)?
    ///     .encrypt_secret(&p1)?;
    /// let other = Cert::try_from(vec![ Packet::from(pk) ])
    ///     .expect("a primary key is a certificate");
    ///
    /// // Merge `other` into `cert`.
    /// let merged = cert.merge_public_and_secret(other).expect("same certificate");
    ///
    /// // `merged` has the secret key material from `other`, which is
    /// // password protected with `p1`, not `self`, which is password
    /// // protected with `p0`.
    /// assert!(merged.primary_key().key().clone().parts_into_secret()?
    ///         .decrypt_secret(&p1).is_ok());
    /// # Ok(()) }
    /// ```
    ///
    /// The unhashed subpacket areas of two variants of a signature
    /// are merged:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::signature::subpacket::Subpacket;
    /// use openpgp::packet::signature::subpacket::SubpacketTag;
    /// use openpgp::packet::signature::subpacket::SubpacketValue;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Add a subpacket to the unhashed subpacket area.
    /// let subpacket_a = Subpacket::new(
    ///     SubpacketValue::Unknown {
    ///         tag: SubpacketTag::Private(100),
    ///         body: Vec::new(),
    ///     },
    ///     false).expect("valid");
    /// let subpacket_b = Subpacket::new(
    ///     SubpacketValue::Unknown {
    ///         tag: SubpacketTag::Private(101),
    ///         body: Vec::new(),
    ///     },
    ///     false).expect("valid");
    ///
    /// let mut cert_a = cert.clone().into_packets2().collect::<Vec<Packet>>();
    /// match cert_a[1] {
    ///     Packet::Signature(ref mut sig) => {
    ///         let unhashed_area = sig.unhashed_area_mut();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_none());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_none());
    ///         unhashed_area.add(subpacket_a.clone());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// let cert_a = Cert::try_from(cert_a).expect("valid");
    ///
    /// let mut cert_b = cert.clone().into_packets2().collect::<Vec<Packet>>();
    /// match cert_b[1] {
    ///     Packet::Signature(ref mut sig) => {
    ///         let unhashed_area = sig.unhashed_area_mut();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_none());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_none());
    ///         unhashed_area.add(subpacket_b.clone());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// let cert_b = Cert::try_from(cert_b).expect("valid");
    ///
    /// // When we merge `cert_b` into `cert_a`, the signature packets
    /// // are merged:
    /// let merged = cert_a.clone().merge_public_and_secret(cert_b.clone())
    ///     .expect("same certificate")
    ///     .into_packets2()
    ///     .collect::<Vec<Packet>>();
    /// match merged[1] {
    ///     Packet::Signature(ref sig) => {
    ///         let unhashed_area = sig.unhashed_area();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_some());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_some());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    ///
    /// // Likewise, when we merge `cert_a` into `cert_b`, the signature
    /// // packets are merged:
    /// let merged = cert_b.clone().merge_public_and_secret(cert_a.clone())
    ///     .expect("same certificate")
    ///     .into_packets2()
    ///     .collect::<Vec<Packet>>();
    /// match merged[1] {
    ///     Packet::Signature(ref sig) => {
    ///         let unhashed_area = sig.unhashed_area();
    ///         assert!(unhashed_area.subpacket(subpacket_a.tag()).is_some());
    ///         assert!(unhashed_area.subpacket(subpacket_b.tag()).is_some());
    ///     }
    ///     _ => panic!("Second packet is the direct signature packet."),
    /// };
    /// # Ok(()) }
    /// ```
    pub fn merge_public_and_secret(mut self, mut other: Cert) -> Result<Self> {
        if self.fingerprint() != other.fingerprint() {
            // The primary key is not the same.  There is nothing to
            // do.
            return Err(Error::InvalidArgument(
                "Primary key mismatch".into()).into());
        }

        // Prefer the secret in `other`.
        if other.primary.key().has_secret() {
            std::mem::swap(self.primary.key_mut(), other.primary.key_mut());
        }

        self.primary.self_signatures.append(
            &mut other.primary.self_signatures);
        self.primary.attestations.append(
            &mut other.primary.attestations);
        self.primary.certifications.append(
            &mut other.primary.certifications);
        self.primary.self_revocations.append(
            &mut other.primary.self_revocations);
        self.primary.other_revocations.append(
            &mut other.primary.other_revocations);

        self.userids.append(&mut other.userids);
        self.user_attributes.append(&mut other.user_attributes);
        self.subkeys.append(&mut other.subkeys);
        self.bad.append(&mut other.bad);

        Ok(self.canonicalize())
    }

    // Returns whether the specified packet is a valid start of a
    // certificate.
    fn valid_start<T>(tag: T) -> Result<()>
        where T: Into<Tag>
    {
        let tag = tag.into();
        match tag {
            Tag::SecretKey | Tag::PublicKey => Ok(()),
            _ => Err(Error::MalformedCert(
                format!("A certificate does not start with a {}",
                        tag)).into()),
        }
    }

    // Returns whether the specified packet can occur in a
    // certificate.
    //
    // This function rejects all packets that are known to not belong
    // in a certificate.  It conservatively accepts unknown packets
    // based on the assumption that they are some new component type
    // from the future.
    fn valid_packet<T>(tag: T) -> Result<()>
        where T: Into<Tag>
    {
        let tag = tag.into();
        match tag {
            // Packets that definitely don't belong in a certificate.
            Tag::Reserved
                | Tag::PKESK
                | Tag::SKESK
                | Tag::OnePassSig
                | Tag::CompressedData
                | Tag::SED
                | Tag::Literal
                | Tag::SEIP
                | Tag::MDC
                | Tag::AED =>
            {
                Err(Error::MalformedCert(
                    format!("A certificate cannot not include a {}",
                            tag)).into())
            }
            // The rest either definitely belong in a certificate or
            // are unknown (and conservatively accepted for future
            // compatibility).
            _ => Ok(()),
        }
    }

    /// Adds packets to the certificate.
    ///
    /// This function turns the certificate into a sequence of
    /// packets, appends the packets to the end of it, and
    /// canonicalizes the result.  [Known packets that don't belong in
    /// a TPK or TSK] cause this function to return an error.  Unknown
    /// packets are retained and added to the list of [unknown
    /// components].  The goal is to provide some future
    /// compatibility.
    ///
    /// If a key is merged that already exists in the certificate, it
    /// replaces the existing key.  This way, secret key material can
    /// be added, removed, encrypted, or decrypted.
    ///
    /// Similarly, if a signature is merged that already exists in the
    /// certificate, it replaces the existing signature.  This way,
    /// the unhashed subpacket area can be updated.
    ///
    /// On success, this function returns the certificate with the
    /// packets merged in, and a boolean indicating whether the
    /// certificate actually changed.  Changed here means that at
    /// least one new packet was added, or an existing packet was
    /// updated.  Alternatively, changed means that the serialized
    /// form has changed.
    ///
    /// [Known packets that don't belong in a TPK or TSK]: https://tools.ietf.org/html/rfc4880#section-11
    /// [unknown components]: Cert::unknowns()
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::serialize::Serialize;
    /// use openpgp::parse::Parse;
    /// use openpgp::types::DataFormat;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    ///
    /// // Merging in the certificate doesn't change it.
    /// let identical_cert = cert.clone();
    /// let (cert, changed) =
    ///     cert.insert_packets2(identical_cert.into_tsk().into_packets())?;
    /// assert!(! changed);
    ///
    ///
    /// // Merge in the revocation certificate.
    /// assert_eq!(cert.primary_key().self_revocations().count(), 0);
    /// let (cert, changed) = cert.insert_packets2(rev)?;
    /// assert!(changed);
    /// assert_eq!(cert.primary_key().self_revocations().count(), 1);
    ///
    ///
    /// // Add an unknown packet.
    /// let tag = Tag::Private(61.into());
    /// let unknown = Unknown::new(tag,
    ///     openpgp::Error::UnsupportedPacketType(tag).into());
    ///
    /// // It shows up as an unknown component.
    /// let (cert, changed) = cert.insert_packets2(unknown)?;
    /// assert!(changed);
    /// assert_eq!(cert.unknowns().count(), 1);
    /// for p in cert.unknowns() {
    ///     assert_eq!(p.tag(), tag);
    /// }
    ///
    ///
    /// // Try and merge a literal data packet.
    /// let mut lit = Literal::new(DataFormat::Text);
    /// lit.set_body(b"test".to_vec());
    ///
    /// // Merging packets that are known to not belong to a
    /// // certificate result in an error.
    /// assert!(cert.insert_packets(lit).is_err());
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Remove secret key material:
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // We just created the key, so all of the keys have secret key
    /// // material.
    /// let mut pk = cert.primary_key().key().clone();
    ///
    /// // Split off the secret key material.
    /// let (pk, sk) = pk.take_secret();
    /// assert!(sk.is_some());
    /// assert!(! pk.has_secret());
    ///
    /// // Merge in the public key.  Recall: the packets that are
    /// // being merged into the certificate take precedence.
    /// let (cert, changed) = cert.insert_packets2(pk)?;
    /// assert!(changed);
    ///
    /// // The secret key material is stripped.
    /// assert!(! cert.primary_key().has_secret());
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Update a binding signature's unhashed subpacket area:
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::packet::signature::subpacket::*;
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert_eq!(cert.userids().nth(0).unwrap().self_signatures().count(), 1);
    ///
    /// // Grab the binding signature so that we can modify it.
    /// let mut sig =
    ///     cert.userids().nth(0).unwrap().self_signatures().nth(0)
    ///     .unwrap().clone();
    ///
    /// // Add a notation subpacket.  Note that the information is not
    /// // authenticated, therefore it may only be trusted if the
    /// // certificate with the signature is placed in a trusted store.
    /// let notation = NotationData::new("retrieved-from@example.org",
    ///                                  "generated-locally",
    ///                                  NotationDataFlags::empty()
    ///                                      .set_human_readable());
    /// sig.unhashed_area_mut().add(
    ///     Subpacket::new(SubpacketValue::NotationData(notation), false)?)?;
    ///
    /// // Merge in the signature.  Recall: the packets that are
    /// // being merged into the certificate take precedence.
    /// let (cert, changed) = cert.insert_packets2(sig)?;
    /// assert!(changed);
    ///
    /// // The old binding signature is replaced.
    /// assert_eq!(cert.userids().nth(0).unwrap().self_signatures().count(), 1);
    /// assert_eq!(cert.userids().nth(0).unwrap().self_signatures().nth(0)
    ///                .unwrap()
    ///                .unhashed_area()
    ///                .subpackets(SubpacketTag::NotationData).count(), 1);
    /// # Ok(()) }
    /// ```
    pub fn insert_packets2<I>(self, packets: I)
        -> Result<(Self, bool)>
        where I: IntoIterator,
              I::Item: Into<Packet>,
    {
        self.insert_packets_merge(packets, |_old, new| Ok(new))
    }

    /// Adds packets to the certificate with an explicit merge policy.
    ///
    /// Like [`Cert::insert_packets2`], but also takes a function that
    /// will be called on inserts and replacements that can be used to
    /// log changes to the certificate, and to influence how packets
    /// are merged.  The merge function takes two parameters, an
    /// optional existing packet, and the packet to be merged in.
    ///
    /// If a new packet is inserted, there is no packet currently in
    /// the certificate.  Hence, the first parameter to the merge
    /// function is `None`.
    ///
    /// If an existing packet is updated, there is a packet currently
    /// in the certificate that matches the given packet.  Hence, the
    /// first parameter to the merge function is
    /// `Some(existing_packet)`.
    ///
    /// Both packets given to the merge function are considered equal
    /// when considering the normalized form (only comparing public
    /// key parameters and ignoring unhashed signature subpackets, see
    /// [`Packet::normalized_hash`]).  It must return a packet that
    /// equals the input packet.  In practice that means that the
    /// merge function returns either the old packet, the new packet,
    /// or a combination of both packets.  If the merge function
    /// returns a different packet, this function returns
    /// [`Error::InvalidOperation`].
    ///
    /// If the merge function returns the existing packet, this
    /// function will still consider this as a change to the
    /// certificate.  In other words, it may return that the
    /// certificate has changed even if the serialized representation
    /// has not changed.
    ///
    /// # Examples
    ///
    /// In the first example, we give an explicit merge function that
    /// just returns the new packet.  This policy prefers the new
    /// packet.  This is the policy used by [`Cert::insert_packets2`].
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::crypto::Password;
    /// use openpgp::cert::prelude::CertBuilder;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p0 = Password::from("old password");
    /// let p1 = Password::from("new password");
    ///
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .set_password(Some(p0.clone()))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Change the password for the primary key.
    /// let pk = cert.primary_key().key().clone().parts_into_secret()?
    ///     .decrypt_secret(&p0)?
    ///     .encrypt_secret(&p1)?;
    ///
    /// // Merge it back in, with a policy projecting to the new packet.
    /// let (cert, changed) =
    ///     cert.insert_packets_merge(pk, |_old, new| Ok(new))?;
    /// assert!(changed);
    ///
    /// // Make sure we can still decrypt the primary key using the
    /// // new password.
    /// assert!(cert.primary_key().key().clone().parts_into_secret()?
    ///         .decrypt_secret(&p1).is_ok());
    /// # Ok(()) }
    /// ```
    ///
    /// In the second example, we give an explicit merge function that
    /// returns the old packet if given, falling back to the new
    /// packet, if not.  This policy prefers the existing packets.
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::crypto::Password;
    /// use openpgp::cert::prelude::CertBuilder;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p0 = Password::from("old password");
    /// let p1 = Password::from("new password");
    ///
    /// // Create a new key.
    /// let (cert, rev) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .set_password(Some(p0.clone()))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // Change the password for the primary key.
    /// let pk = cert.primary_key().key().clone().parts_into_secret()?
    ///     .decrypt_secret(&p0)?
    ///     .encrypt_secret(&p1)?;
    ///
    /// // Merge it back in, with a policy preferring the old packet.
    /// let (cert, changed) =
    ///     cert.insert_packets_merge(pk, |old, new| Ok(old.unwrap_or(new)))?;
    /// assert!(changed); // Overestimates changes.
    ///
    /// // Make sure we can still decrypt the primary key using the
    /// // old password.
    /// assert!(cert.primary_key().key().clone().parts_into_secret()?
    ///         .decrypt_secret(&p0).is_ok());
    /// # Ok(()) }
    /// ```
    pub fn insert_packets_merge<P, I>(self, packets: P, merge: I)
        -> Result<(Self, bool)>
        where P: IntoIterator,
              P::Item: Into<Packet>,
              I: FnMut(Option<Packet>, Packet) -> Result<Packet>,
    {
        self.insert_packets_(&mut packets.into_iter().map(Into::into),
                             Box::new(merge))
    }

    /// Adds packets to the certificate with an explicit merge policy.
    ///
    /// This implements all the Cert::insert_packets* functions.  Its
    /// arguments `packets` and `merge` use dynamic dispatch so that
    /// we avoid the cost of monomorphization.
    fn insert_packets_<'a>(self,
                           packets: &mut dyn Iterator<Item = Packet>,
                           mut merge: Box<dyn FnMut(Option<Packet>, Packet)
                                                    -> Result<Packet> + 'a>)
        -> Result<(Self, bool)>
    {
        let mut changed = false;
        let mut combined =
            self.as_tsk().into_packets().collect::<Vec<_>>();

        // Hashes a packet ignoring the unhashed subpacket area and
        // any secret key material.
        let hash_packet = |p: &Packet| -> u64 {
            let mut hasher = DefaultHasher::new();
            p.normalized_hash(&mut hasher);
            hasher.finish()
        };

        // BTreeMap of (hash) -> Vec<index in combined>.
        //
        // We don't use a HashMap, because the key would be a
        // reference to the packets in combined, which would prevent
        // us from modifying combined.
        //
        // Note: we really don't want to dedup components now, because
        // we want to keep signatures immediately after their
        // components.
        let mut packet_map: BTreeMap<u64, Vec<usize>> = BTreeMap::new();
        for (i, p) in combined.iter().enumerate() {
            match packet_map.entry(hash_packet(p)) {
                Entry::Occupied(mut oe) => {
                    oe.get_mut().push(i)
                }
                Entry::Vacant(ve) => {
                    ve.insert(vec![ i ]);
                }
            }
        }

        enum Action {
            Drop,
            Overwrite(usize),
            Insert,
        }
        use Action::*;

        // Now we merge in the new packets.
        for p in packets {
            Cert::valid_packet(&p)?;

            let hash = hash_packet(&p);
            let mut action = Insert;
            if let Some(combined_i) = packet_map.get(&hash) {
                for i in combined_i {
                    let i: usize = *i;
                    let (same, identical) = match (&p, &combined[i]) {
                        // For keys, only compare the public bits.  If
                        // they match, then we keep whatever is in the
                        // new key.
                        (Packet::PublicKey(a), Packet::PublicKey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             a == b),
                        (Packet::SecretKey(a), Packet::SecretKey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             a == b),
                        (Packet::PublicKey(a), Packet::SecretKey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             false),
                        (Packet::SecretKey(a), Packet::PublicKey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             false),

                        (Packet::PublicSubkey(a), Packet::PublicSubkey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             a == b),
                        (Packet::SecretSubkey(a), Packet::SecretSubkey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             a == b),
                        (Packet::PublicSubkey(a), Packet::SecretSubkey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             false),
                        (Packet::SecretSubkey(a), Packet::PublicSubkey(b)) =>
                            (a.public_cmp(b) == Ordering::Equal,
                             false),

                        // For signatures, don't compare the unhashed
                        // subpacket areas.  If it's the same
                        // signature, then we keep what is the new
                        // signature's unhashed subpacket area.
                        (Packet::Signature(a), Packet::Signature(b)) =>
                            (a.normalized_eq(b),
                             a == b),

                        (a, b) => {
                            let identical = a == b;
                            (identical, identical)
                        }
                    };

                    if same {
                        if identical {
                            action = Drop;
                        } else {
                            action = Overwrite(i);
                        }
                        break;
                    }
                }
            }

            match action {
                Drop => (),
                Overwrite(i) => {
                    // Existing packet.
                    let existing =
                        std::mem::replace(&mut combined[i],
                                          Packet::Marker(Default::default()));
                    let merged = merge(Some(existing), p)?;
                    let merged_hash = hash_packet(&merged);
                    if hash != merged_hash {
                        return Err(Error::InvalidOperation(
                            format!("merge function changed packet hash \
                                     (expected: {}, got: {})",
                                    hash, merged_hash)).into());
                    }

                    combined[i] = merged;
                    changed = true;
                },
                Insert => {
                    // New packet.
                    let merged = merge(None, p)?;
                    let merged_hash = hash_packet(&merged);
                    if hash != merged_hash {
                        return Err(Error::InvalidOperation(
                            format!("merge function changed packet hash \
                                     (expected: {}, got: {})",
                                    hash, merged_hash)).into());
                    }

                    // Add it to combined.
                    combined.push(merged);
                    changed = true;

                    // Because the caller might insert the same packet
                    // multiple times, we need to also add it to
                    // packet_map.
                    let i = combined.len() - 1;
                    match packet_map.entry(hash) {
                        Entry::Occupied(mut oe) => {
                            oe.get_mut().push(i)
                        }
                        Entry::Vacant(ve) => {
                            ve.insert(vec![ i ]);
                        }
                    }
                }
            }
        }

        Cert::try_from(combined).map(|cert| (cert, changed))
    }

    /// Adds packets to the certificate.
    ///
    /// Like [`Cert::insert_packets2`], but does not return whether
    /// the certificate changed.
    pub fn insert_packets<I>(self, packets: I)
        -> Result<Self>
        where I: IntoIterator,
              I::Item: Into<Packet>,
    {
        self.insert_packets2(packets).map(|(cert, _)| cert)
    }

    /// Returns whether at least one of the keys includes secret
    /// key material.
    ///
    /// This returns true if either the primary key or at least one of
    /// the subkeys includes secret key material.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::serialize::Serialize;
    /// use openpgp::parse::Parse;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// // If we serialize the certificate, the secret key material is
    /// // stripped, unless we first convert it to a TSK.
    ///
    /// let mut buffer = Vec::new();
    /// cert.as_tsk().serialize(&mut buffer);
    /// let cert = Cert::from_bytes(&buffer)?;
    /// assert!(cert.is_tsk());
    ///
    /// // Now round trip it without first converting it to a TSK.  This
    /// // drops the secret key material.
    /// let mut buffer = Vec::new();
    /// cert.serialize(&mut buffer);
    /// let cert = Cert::from_bytes(&buffer)?;
    /// assert!(!cert.is_tsk());
    /// #     Ok(())
    /// # }
    /// ```
    pub fn is_tsk(&self) -> bool {
        if self.primary_key().has_secret() {
            return true;
        }
        self.subkeys().any(|sk| {
            sk.key().has_secret()
        })
    }

    /// Strips any secret key material.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    ///
    /// # fn main() -> openpgp::Result<()> {
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .generate()?;
    /// assert!(cert.is_tsk());
    ///
    /// let cert = cert.strip_secret_key_material();
    /// assert!(! cert.is_tsk());
    /// #     Ok(())
    /// # }
    /// ```
    pub fn strip_secret_key_material(mut self) -> Cert {
        self.primary.key_mut().steal_secret();
        self.subkeys.iter_mut().for_each(|sk| {
            sk.key_mut().steal_secret();
        });
        self
    }

    /// Retains only the userids specified by the predicate.
    ///
    /// Removes all the userids for which the given predicate returns
    /// false.
    ///
    /// # Warning
    ///
    /// Because userid binding signatures are traditionally used to
    /// provide additional information like the certificate holder's
    /// algorithm preferences (see [`Preferences`]) and primary key
    /// flags (see [`ValidKeyAmalgamation::key_flags`]).  Removing a
    /// userid may inadvertently change this information.
    ///
    ///   [`ValidKeyAmalgamation::key_flags`]: amalgamation::key::ValidKeyAmalgamation::key_flags()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       .add_userid("Alice Lovelace <alice@lovelace.name>")
    ///       .generate()?;
    /// assert_eq!(cert.userids().count(), 2);
    ///
    /// let cert = cert.retain_userids(|ua| {
    ///     if let Ok(Some(address)) = ua.email() {
    ///         address == "alice@example.org" // Only keep this one.
    ///     } else {
    ///         false                          // Drop malformed userids.
    ///     }
    /// });
    /// assert_eq!(cert.userids().count(), 1);
    /// assert_eq!(cert.userids().nth(0).unwrap().email()?.unwrap(),
    ///            "alice@example.org");
    /// # Ok(()) }
    /// ```
    pub fn retain_userids<P>(mut self, mut predicate: P) -> Cert
        where P: FnMut(UserIDAmalgamation) -> bool,
    {
        let mut keep = vec![false; self.userids.len()];
        for (i, a) in self.userids().enumerate() {
            keep[i] = predicate(a);
        }
        // Note: Vec::retain visits the elements in the original
        // order.
        let mut keep = keep.iter();
        self.userids.retain(|_| *keep.next().unwrap());
        self
    }

    /// Retains only the user attributes specified by the predicate.
    ///
    /// Removes all the user attributes for which the given predicate
    /// returns false.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///       // Add nonsensical user attribute.
    ///       .add_user_attribute(vec![0, 1, 2])
    ///       .generate()?;
    /// assert_eq!(cert.user_attributes().count(), 1);
    ///
    /// // Strip all user attributes
    /// let cert = cert.retain_user_attributes(|_| false);
    /// assert_eq!(cert.user_attributes().count(), 0);
    /// # Ok(()) }
    /// ```
    pub fn retain_user_attributes<P>(mut self, mut predicate: P) -> Cert
        where P: FnMut(UserAttributeAmalgamation) -> bool,
    {
        let mut keep = vec![false; self.user_attributes.len()];
        for (i, a) in self.user_attributes().enumerate() {
            keep[i] = predicate(a);
        }
        // Note: Vec::retain visits the elements in the original
        // order.
        let mut keep = keep.iter();
        self.user_attributes.retain(|_| *keep.next().unwrap());
        self
    }

    /// Retains only the subkeys specified by the predicate.
    ///
    /// Removes all the subkeys for which the given predicate returns
    /// false.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::cert::prelude::*;
    ///
    /// // Create a new key.
    /// let (cert, _) =
    ///       CertBuilder::new()
    ///       .add_userid("Alice Lovelace <alice@lovelace.name>")
    ///       .add_transport_encryption_subkey()
    ///       .add_storage_encryption_subkey()
    ///       .generate()?;
    /// assert_eq!(cert.keys().subkeys().count(), 2);
    ///
    /// // Retain only the transport encryption subkey.  For that, we
    /// // need to examine the key flags, therefore we need to turn
    /// // the `KeyAmalgamation` into a `ValidKeyAmalgamation` under a
    /// // policy.
    /// let p = &StandardPolicy::new();
    /// let cert = cert.retain_subkeys(|ka| {
    ///     if let Ok(vka) = ka.with_policy(p, None) {
    ///         vka.key_flags().map(|flags| flags.for_transport_encryption())
    ///             .unwrap_or(false)      // Keep transport encryption keys.
    ///     } else {
    ///         false                      // Drop unbound keys.
    ///     }
    /// });
    /// assert_eq!(cert.keys().subkeys().count(), 1);
    /// assert!(cert.with_policy(p, None)?.keys().subkeys().nth(0).unwrap()
    ///             .key_flags().unwrap().for_transport_encryption());
    /// # Ok(()) }
    /// ```
    pub fn retain_subkeys<P>(mut self, mut predicate: P) -> Cert
        where P: FnMut(SubordinateKeyAmalgamation<crate::packet::key::PublicParts>) -> bool,
    {
        let mut keep = vec![false; self.subkeys.len()];
        for (i, a) in self.keys().subkeys().enumerate() {
            keep[i] = predicate(a);
        }
        // Note: Vec::retain visits the elements in the original
        // order.
        let mut keep = keep.iter();
        self.subkeys.retain(|_| *keep.next().unwrap());
        self
    }

    /// Associates a policy and a reference time with the certificate.
    ///
    /// This is used to turn a `Cert` into a
    /// [`ValidCert`].  (See also [`ValidateAmalgamation`],
    /// which does the same for component amalgamations.)
    ///
    /// A certificate is considered valid if:
    ///
    ///   - It has a self signature that is live at time `t`.
    ///
    ///   - The policy considers it acceptable.
    ///
    /// This doesn't say anything about whether the certificate itself
    /// is alive (see [`ValidCert::alive`]) or revoked (see
    /// [`ValidCert::revocation_status`]).
    ///
    /// [`ValidateAmalgamation`]: amalgamation::ValidateAmalgamation
    /// [`ValidCert::alive`]: ValidCert::alive()
    /// [`ValidCert::revocation_status`]: ValidCert::revocation_status()
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    /// # assert!(std::ptr::eq(vc.policy(), p));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn with_policy<'a, T>(&'a self, policy: &'a dyn Policy, time: T)
                              -> Result<ValidCert<'a>>
        where T: Into<Option<time::SystemTime>>,
    {
        let time = time.into().unwrap_or_else(crate::now);
        self.primary_key().with_policy(policy, time)?;

        Ok(ValidCert {
            cert: self,
            policy,
            time,
        })
    }
}

use crate::serialize::TSK;
impl<'a> TSK<'a> {
    /// Converts the certificate into an iterator over a sequence of
    /// packets.
    ///
    /// This function emits secret key packets, modulo the keys that
    /// are filtered (see [`TSK::set_filter`]).  If requested, missing
    /// secret key material is replaced by stubs (see
    /// [`TSK::emit_secret_key_stubs`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::serialize::{Serialize, SerializeInto};
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let (cert, _) =
    /// #       CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #       .generate()?;
    /// assert!(cert.is_tsk());
    /// let a = cert.as_tsk().to_vec()?;
    /// let mut b = Vec::new();
    /// cert.into_tsk().into_packets()
    ///     .for_each(|p| p.serialize(&mut b).unwrap());
    /// assert_eq!(a, b);
    /// # Ok(()) }
    /// ```
    pub fn into_packets(self) -> impl Iterator<Item=Packet> + 'a {
        /// Strips the secret key material if the filter rejects it,
        /// and optionally inserts secret key stubs.
        use std::sync::Arc;
        fn rewrite<'a>(
            filter: Arc<Box<dyn Fn(&key::UnspecifiedSecret) -> bool + 'a>>,
            emit_secret_key_stubs: bool,
            mut p: impl Iterator<Item=Packet> + Send + Sync)
            -> impl Iterator<Item=Packet> + Send + Sync
        {
            let k: Packet = match p.next().unwrap() {
                Packet::PublicKey(mut k) => {
                    if ! k.role_as_unspecified().parts_as_secret()
                        .map(|k| (filter)(k))
                        .unwrap_or(false)
                    {
                        k = k.take_secret().0;
                    }

                    if ! k.has_secret() && emit_secret_key_stubs {
                        k = TSK::add_stub(k).into();
                    }

                    if k.has_secret() {
                        Packet::SecretKey(k.parts_into_secret().unwrap())
                    } else {
                        Packet::PublicKey(k)
                    }
                }
                Packet::PublicSubkey(mut k) => {
                    if ! k.role_as_unspecified().parts_as_secret()
                        .map(|k| (filter)(k))
                        .unwrap_or(false)
                    {
                        k = k.take_secret().0;
                    }

                    if ! k.has_secret() && emit_secret_key_stubs {
                        k = TSK::add_stub(k).into();
                    }

                    if k.has_secret() {
                        Packet::SecretSubkey(k.parts_into_secret().unwrap())
                    } else {
                        Packet::PublicSubkey(k)
                    }
                }
                _ => unreachable!(),
            };

            std::iter::once(k).chain(p)
        }

        let (cert, filter, emit_secret_key_stubs) = self.decompose();
        let filter = Arc::new(filter);
        let cert = cert.into_owned();

        rewrite(filter.clone(), emit_secret_key_stubs, cert.primary.into_packets())
            .chain(cert.userids.into_iter().flat_map(|b| b.into_packets()))
            .chain(cert.user_attributes.into_iter().flat_map(|b| b.into_packets()))
            .chain(cert.subkeys.into_iter().flat_map(
                move |b| rewrite(filter.clone(), emit_secret_key_stubs, b.into_packets())))
            .chain(cert.unknowns.into_iter().flat_map(|b| b.into_packets()))
            .chain(cert.bad.into_iter().map(|s| s.into()))
    }
}

impl TryFrom<PacketParserResult<'_>> for Cert {
    type Error = anyhow::Error;

    /// Returns the Cert found in the packet stream.
    ///
    /// If the sequence contains multiple certificates (i.e., it is a
    /// keyring), or the certificate is followed by an invalid packet
    /// this function will fail.  To parse keyrings, use
    /// [`CertParser`] instead of this function.
    fn try_from(ppr: PacketParserResult) -> Result<Self> {
        let mut parser = parser::CertParser::from(ppr);
        if let Some(cert_result) = parser.next() {
            if parser.next().is_some() {
                Err(Error::MalformedCert(
                    "Additional packets found, is this a keyring?".into()
                ).into())
            } else {
                cert_result
            }
        } else {
            Err(Error::MalformedCert("No data".into()).into())
        }
    }
}

impl TryFrom<Vec<Packet>> for Cert {
    type Error = anyhow::Error;

    fn try_from(p: Vec<Packet>) -> Result<Self> {
        Cert::from_packets(p.into_iter())
    }
}

impl TryFrom<Packet> for Cert {
    type Error = anyhow::Error;

    fn try_from(p: Packet) -> Result<Self> {
        Cert::from_packets(std::iter::once(p))
    }
}

impl TryFrom<PacketPile> for Cert {
    type Error = anyhow::Error;

    /// Returns the certificate found in the `PacketPile`.
    ///
    /// If the [`PacketPile`] does not start with a certificate
    /// (specifically, if it does not start with a primary key
    /// packet), then this fails.
    ///
    /// If the sequence contains multiple certificates (i.e., it is a
    /// keyring), or the certificate is followed by an invalid packet
    /// this function will fail.  To parse keyrings, use
    /// [`CertParser`] instead of this function.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::PacketPile;
    /// use std::convert::TryFrom;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let (cert, rev) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    ///
    /// // We should be able to turn a certificate into a PacketPile
    /// // and back.
    /// let pp : PacketPile = cert.into();
    /// assert!(Cert::try_from(pp).is_ok());
    ///
    /// // But a revocation certificate is not a certificate, so this
    /// // will fail.
    /// let pp : PacketPile = Packet::from(rev).into();
    /// assert!(Cert::try_from(pp).is_err());
    /// # Ok(())
    /// # }
    /// ```
    fn try_from(p: PacketPile) -> Result<Self> {
        Self::from_packets(p.into_children())
    }
}

impl From<Cert> for Vec<Packet> {
    /// Converts the `Cert` into a `Vec<Packet>`.
    ///
    /// If any packets include secret key material, that secret key
    /// material is included in the resulting `Vec<Packet>`.  In
    /// contrast, when serializing a `Cert`, or converting a cert to
    /// packets with [`Cert::into_packets2`], the secret key material
    /// not included.
    ///
    /// Note: This will change in sequoia-openpgp version 2, which
    /// will harmonize the behavior and not include secret key
    /// material.
    // XXXv2: Drop the note in the doc comment and mentioned it in the
    // release notes.
    fn from(cert: Cert) -> Self {
        #[allow(deprecated)]
        cert.into_packets().collect::<Vec<_>>()
    }
}

/// An iterator that moves out of a `Cert`.
///
/// This structure is created by the `into_iter` method on [`Cert`]
/// (provided by the [`IntoIterator`] trait).
///
/// [`IntoIterator`]: std::iter::IntoIterator
// We can't use a generic type, and due to the use of closures, we
// can't write down the concrete type.  So, just use a Box.
pub struct IntoIter(Box<dyn Iterator<Item=Packet> + Send + Sync>);
assert_send_and_sync!(IntoIter);

impl Iterator for IntoIter {
    type Item = Packet;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl IntoIterator for Cert
{
    type Item = Packet;
    type IntoIter = IntoIter;

    /// Converts the `Cert` into an iterator over `Packet`s.
    ///
    /// If any packets include secret key material, that secret key
    /// material is included in the resulting iterator.  In contrast,
    /// when serializing a `Cert`, or converting a cert to packets
    /// with [`Cert::into_packets2`], the secret key material not
    /// included.
    ///
    /// Note: This will change in sequoia-openpgp version 2, which
    /// will harmonize the behavior and not include secret key
    /// material.
    // XXXv2: Drop the note in the doc comment and mentioned it in the
    // release notes.
    fn into_iter(self) -> Self::IntoIter {
        #[allow(deprecated)]
        IntoIter(Box::new(self.into_packets()))
    }
}

/// A `Cert` plus a `Policy` and a reference time.
///
/// A `ValidCert` combines a [`Cert`] with a [`Policy`] and a
/// reference time.  This allows it to implement methods that require
/// a `Policy` and a reference time without requiring the caller to
/// explicitly pass them in.  Embedding them in the `ValidCert` data
/// structure rather than having the caller pass them in explicitly
/// helps ensure that multipart operations, even those that span
/// multiple functions, use the same `Policy` and reference time.
/// This avoids a subtle class of bugs in which different views of a
/// certificate are unintentionally used.
///
/// A `ValidCert` is typically obtained by transforming a `Cert` using
/// [`Cert::with_policy`].
///
/// A `ValidCert` is guaranteed to have a valid and live binding
/// signature at the specified reference time.  Note: this only means
/// that the binding signature is live; it says nothing about whether
/// the certificate or any component is live.  If you care about those
/// things, then you need to check them separately.
///
/// [`Policy`]: crate::policy::Policy
/// [`Cert::with_policy`]: Cert::with_policy()
///
/// # Examples
///
/// ```
/// use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) = CertBuilder::new()
/// #     .add_userid("Alice")
/// #     .add_signing_subkey()
/// #     .add_transport_encryption_subkey()
/// #     .generate()?;
/// let vc = cert.with_policy(p, None)?;
/// # assert!(std::ptr::eq(vc.policy(), p));
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct ValidCert<'a> {
    cert: &'a Cert,
    policy: &'a dyn Policy,
    // The reference time.
    time: time::SystemTime,
}
assert_send_and_sync!(ValidCert<'_>);

impl<'a> std::ops::Deref for ValidCert<'a> {
    type Target = Cert;

    fn deref(&self) -> &Self::Target {
        self.cert
    }
}

impl<'a> fmt::Display for ValidCert<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.fingerprint())
    }
}

impl<'a> ValidCert<'a> {
    /// Returns the underlying certificate.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    /// assert!(std::ptr::eq(vc.cert(), &cert));
    /// # assert!(std::ptr::eq(vc.policy(), p));
    /// # Ok(()) }
    /// ```
    pub fn cert(&self) -> &'a Cert {
        self.cert
    }

    /// Returns the associated reference time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::time::{SystemTime, Duration, UNIX_EPOCH};
    /// #
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let t = UNIX_EPOCH + Duration::from_secs(1307732220);
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .set_creation_time(t)
    /// #         .generate()?;
    /// let vc = cert.with_policy(p, t)?;
    /// assert_eq!(vc.time(), t);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn time(&self) -> time::SystemTime {
        self.time
    }

    /// Returns the associated policy.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    /// assert!(std::ptr::eq(vc.policy(), p));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn policy(&self) -> &'a dyn Policy {
        self.policy
    }

    /// Changes the associated policy and reference time.
    ///
    /// If `time` is `None`, the current time is used.
    ///
    /// Returns an error if the certificate is not valid for the given
    /// policy at the specified time.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::{StandardPolicy, NullPolicy};
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let sp = &StandardPolicy::new();
    /// let np = &NullPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// let vc = cert.with_policy(sp, None)?;
    ///
    /// // ...
    ///
    /// // Now with a different policy.
    /// let vc = vc.with_policy(np, None)?;
    /// #     Ok(())
    /// # }
    /// ```
    pub fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
        -> Result<ValidCert<'a>>
        where T: Into<Option<time::SystemTime>>,
    {
        self.cert.with_policy(policy, time)
    }

    /// Returns the certificate's direct key signature as of the
    /// reference time.
    ///
    /// Subpackets on direct key signatures apply to all components of
    /// the certificate, cf. [Section 5.2.3.3 of RFC 4880].
    ///
    /// [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use sequoia_openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    /// println!("{:?}", vc.direct_key_signature());
    /// # assert!(vc.direct_key_signature().is_ok());
    /// # Ok(()) }
    /// ```
    pub fn direct_key_signature(&self) -> Result<&'a Signature>
    {
        self.cert.primary.binding_signature(self.policy(), self.time())
    }

    /// Returns the certificate's revocation status.
    ///
    /// A certificate is considered revoked at time `t` if:
    ///
    ///   - There is a valid and live revocation at time `t` that is
    ///     newer than all valid and live self signatures at time `t`,
    ///     or
    ///
    ///   - There is a valid [hard revocation] (even if it is not live
    ///     at time `t`, and even if there is a newer self signature).
    ///
    /// [hard revocation]: crate::types::RevocationType::Hard
    ///
    /// Note: certificates and subkeys have different revocation
    /// criteria from [User IDs] and [User Attributes].
    ///
    //  Pending https://github.com/rust-lang/rust/issues/85960, should be
    //  [User IDs]: bundle::ComponentBundle<UserID>::revocation_status
    //  [User Attributes]: bundle::ComponentBundle<UserAttribute>::revocation_status
    /// [User IDs]: bundle::ComponentBundle#method.revocation_status-1
    /// [User Attributes]: bundle::ComponentBundle#method.revocation_status-2
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::types::RevocationStatus;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let (cert, rev) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    ///
    /// // Not revoked.
    /// assert_eq!(cert.with_policy(p, None)?.revocation_status(),
    ///            RevocationStatus::NotAsFarAsWeKnow);
    ///
    /// // Merge the revocation certificate.  `cert` is now considered
    /// // to be revoked.
    /// let cert = cert.insert_packets(rev.clone())?;
    /// assert_eq!(cert.with_policy(p, None)?.revocation_status(),
    ///            RevocationStatus::Revoked(vec![&rev.into()]));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn revocation_status(&self) -> RevocationStatus<'a> {
        self.cert.revocation_status(self.policy, self.time)
    }

    /// Returns whether or not the certificate is alive at the
    /// reference time.
    ///
    /// A certificate is considered to be alive at time `t` if the
    /// primary key is alive at time `t`.
    ///
    /// A valid certificate's primary key is guaranteed to have [a live
    /// binding signature], however, that does not mean that the
    /// [primary key is necessarily alive].
    ///
    /// [a live binding signature]: amalgamation::ValidateAmalgamation
    /// [primary key is necessarily alive]: amalgamation::key::ValidKeyAmalgamation::alive()
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let a_second = time::Duration::from_secs(1);
    ///
    /// let creation_time = time::SystemTime::now();
    /// let before_creation = creation_time - a_second;
    /// let validity_period = 60 * a_second;
    /// let expiration_time = creation_time + validity_period;
    /// let before_expiration_time = expiration_time - a_second;
    /// let after_expiration_time = expiration_time + a_second;
    ///
    /// let (cert, _) = CertBuilder::new()
    ///     .add_userid("Alice")
    ///     .set_creation_time(creation_time)
    ///     .set_validity_period(validity_period)
    ///     .generate()?;
    ///
    /// // There is no binding signature before the certificate was created.
    /// assert!(cert.with_policy(p, before_creation).is_err());
    /// assert!(cert.with_policy(p, creation_time)?.alive().is_ok());
    /// assert!(cert.with_policy(p, before_expiration_time)?.alive().is_ok());
    /// // The binding signature is still alive, but the key has expired.
    /// assert!(cert.with_policy(p, expiration_time)?.alive().is_err());
    /// assert!(cert.with_policy(p, after_expiration_time)?.alive().is_err());
    /// # Ok(()) }
    pub fn alive(&self) -> Result<()> {
        self.primary_key().alive()
    }

    /// Returns the certificate's primary key.
    ///
    /// A key's secret key material may be protected with a
    /// password.  In such cases, it needs to be decrypted before it
    /// can be used to decrypt data or generate a signature.  Refer to
    /// [`Key::decrypt_secret`] for details.
    ///
    /// [`Key::decrypt_secret`]: crate::packet::Key::decrypt_secret()
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::policy::StandardPolicy;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// # let p = &StandardPolicy::new();
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .generate()?;
    /// # let vc = cert.with_policy(p, None)?;
    /// #
    /// let primary = vc.primary_key();
    /// // The certificate's fingerprint *is* the primary key's fingerprint.
    /// assert_eq!(vc.fingerprint(), primary.fingerprint());
    /// # Ok(()) }
    pub fn primary_key(&self)
        -> ValidPrimaryKeyAmalgamation<'a, key::PublicParts>
    {
        self.cert.primary_key().with_policy(self.policy, self.time)
            .expect("A ValidKeyAmalgamation must have a ValidPrimaryKeyAmalgamation")
    }

    /// Returns an iterator over the certificate's valid keys.
    ///
    /// That is, this returns an iterator over the primary key and any
    /// subkeys.
    ///
    /// The iterator always returns the primary key first.  The order
    /// of the subkeys is undefined.
    ///
    /// To only iterate over the certificate's subkeys, call
    /// [`ValidKeyAmalgamationIter::subkeys`] on the returned iterator
    /// instead of skipping the first key: this causes the iterator to
    /// return values with a more accurate type.
    ///
    /// A key's secret key material may be protected with a
    /// password.  In such cases, it needs to be decrypted before it
    /// can be used to decrypt data or generate a signature.  Refer to
    /// [`Key::decrypt_secret`] for details.
    ///
    /// [`ValidKeyAmalgamationIter::subkeys`]: amalgamation::key::ValidKeyAmalgamationIter::subkeys()
    /// [`Key::decrypt_secret`]: crate::packet::Key::decrypt_secret()
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// // Create a key with two subkeys: one for signing and one for
    /// // encrypting data in transit.
    /// let (cert, _) = CertBuilder::new()
    ///     .add_userid("Alice")
    ///     .add_signing_subkey()
    ///     .add_transport_encryption_subkey()
    ///     .generate()?;
    /// // They should all be valid.
    /// assert_eq!(cert.with_policy(p, None)?.keys().count(), 1 + 2);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn keys(&self) -> ValidKeyAmalgamationIter<'a, key::PublicParts, key::UnspecifiedRole> {
        self.cert.keys().with_policy(self.policy, self.time)
    }

    /// Returns the primary User ID at the reference time, if any.
    ///
    /// A certificate may not have a primary User ID if it doesn't
    /// have any valid User IDs.  If a certificate has at least one
    /// valid User ID at time `t`, then it has a primary User ID at
    /// time `t`.
    ///
    /// The primary User ID is determined as follows:
    ///
    ///   - Discard User IDs that are not valid or not alive at time `t`.
    ///
    ///   - Order the remaining User IDs by whether a User ID does not
    ///     have a valid self-revocation (i.e., non-revoked first,
    ///     ignoring third-party revocations).
    ///
    ///   - Break ties by ordering by whether the User ID is [marked
    ///     as being the primary User ID].
    ///
    ///   - Break ties by ordering by the binding signature's creation
    ///     time, most recent first.
    ///
    /// If there are multiple User IDs that are ordered first, then
    /// one is chosen in a deterministic, but undefined manner
    /// (currently, we order the value of the User IDs
    /// lexographically, but you shouldn't rely on this).
    ///
    /// [marked as being the primary User ID]: https://tools.ietf.org/html/rfc4880#section-5.2.3.19
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let t1 = time::SystemTime::now();
    /// let t2 = t1 + time::Duration::from_secs(1);
    ///
    /// let (cert, _) = CertBuilder::new()
    ///     .set_creation_time(t1)
    ///     .add_userid("Alice")
    ///     .generate()?;
    /// let mut signer = cert
    ///     .primary_key().key().clone().parts_into_secret()?.into_keypair()?;
    ///
    /// // There is only one User ID.  It must be the primary User ID.
    /// let vc = cert.with_policy(p, t1)?;
    /// let alice = vc.primary_userid().unwrap();
    /// assert_eq!(alice.value(), b"Alice");
    /// // By default, the primary User ID flag is set.
    /// assert!(alice.binding_signature().primary_userid().is_some());
    ///
    /// let template: signature::SignatureBuilder
    ///     = alice.binding_signature().clone().into();
    ///
    /// // Add another user id whose creation time is after the
    /// // existing User ID, and doesn't have the User ID set.
    /// let sig = template.clone()
    ///     .set_signature_creation_time(t2)?
    ///     .set_primary_userid(false)?;
    /// let bob: UserID = "Bob".into();
    /// let sig = bob.bind(&mut signer, &cert, sig)?;
    /// let cert = cert.insert_packets(vec![Packet::from(bob), sig.into()])?;
    /// # assert_eq!(cert.userids().count(), 2);
    ///
    /// // Alice should still be the primary User ID, because it has the
    /// // primary User ID flag set.
    /// let alice = cert.with_policy(p, t2)?.primary_userid().unwrap();
    /// assert_eq!(alice.value(), b"Alice");
    ///
    ///
    /// // Add another User ID, whose binding signature's creation
    /// // time is after Alice's and also has the primary User ID flag set.
    /// let sig = template.clone()
    ///    .set_signature_creation_time(t2)?;
    /// let carol: UserID = "Carol".into();
    /// let sig = carol.bind(&mut signer, &cert, sig)?;
    /// let cert = cert.insert_packets(vec![Packet::from(carol), sig.into()])?;
    /// # assert_eq!(cert.userids().count(), 3);
    ///
    /// // It should now be the primary User ID, because it is the
    /// // newest User ID with the primary User ID bit is set.
    /// let carol = cert.with_policy(p, t2)?.primary_userid().unwrap();
    /// assert_eq!(carol.value(), b"Carol");
    /// # Ok(()) }
    pub fn primary_userid(&self) -> Result<ValidUserIDAmalgamation<'a>>
    {
        self.cert.primary_userid_relaxed(self.policy(), self.time(), true)
    }

    /// Returns an iterator over the certificate's valid User IDs.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::time;
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::packet::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let t0 = time::SystemTime::now() - time::Duration::from_secs(10);
    /// # let t1 = t0 + time::Duration::from_secs(1);
    /// # let t2 = t1 + time::Duration::from_secs(1);
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .set_creation_time(t0)
    /// #     .generate()?;
    /// // `cert` was created at t0.  Add a second User ID at t1.
    /// let userid = UserID::from("alice@example.com");
    /// // Use the primary User ID's current binding signature as the
    /// // basis for the new User ID's binding signature.
    /// let template : signature::SignatureBuilder
    ///     = cert.with_policy(p, None)?
    ///           .primary_userid()?
    ///           .binding_signature()
    ///           .clone()
    ///           .into();
    /// let sig = template.set_signature_creation_time(t1)?;
    /// let mut signer = cert
    ///     .primary_key().key().clone().parts_into_secret()?.into_keypair()?;
    /// let binding = userid.bind(&mut signer, &cert, sig)?;
    /// // Merge it.
    /// let cert = cert.insert_packets(
    ///     vec![Packet::from(userid), binding.into()])?;
    ///
    /// // At t0, the new User ID is not yet valid (it doesn't have a
    /// // binding signature that is live at t0).  Thus, it is not
    /// // returned.
    /// let vc = cert.with_policy(p, t0)?;
    /// assert_eq!(vc.userids().count(), 1);
    /// // But, at t1, we see both User IDs.
    /// let vc = cert.with_policy(p, t1)?;
    /// assert_eq!(vc.userids().count(), 2);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn userids(&self) -> ValidUserIDAmalgamationIter<'a> {
        self.cert.userids().with_policy(self.policy, self.time)
    }

    /// Returns the primary User Attribute, if any.
    ///
    /// If a certificate has any valid User Attributes, then it has a
    /// primary User Attribute.  In other words, it will not have a
    /// primary User Attribute at time `t` if there are no valid User
    /// Attributes at time `t`.
    ///
    /// The primary User Attribute is determined in the same way as
    /// the primary User ID.  See the documentation of
    /// [`ValidCert::primary_userid`] for details.
    ///
    /// [`ValidCert::primary_userid`]: ValidCert::primary_userid()
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    /// let ua = vc.primary_user_attribute();
    /// # // We don't have an user attributes.  So, this should return an
    /// # // error.
    /// # assert!(ua.is_err());
    /// #     Ok(())
    /// # }
    /// ```
    pub fn primary_user_attribute(&self)
        -> Result<ValidComponentAmalgamation<'a, UserAttribute>>
    {
        ValidComponentAmalgamation::primary(self.cert,
                                            self.cert.user_attributes.iter(),
                                            self.policy(), self.time(), true)
    }

    /// Returns an iterator over the certificate's valid
    /// `UserAttribute`s.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::packet::user_attribute::Subpacket;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// #
    /// # // Create some user attribute. Doctests do not pass cfg(test),
    /// # // so UserAttribute::arbitrary is not available
    /// # let sp = Subpacket::Unknown(7, vec![7; 7].into_boxed_slice());
    /// # let ua = UserAttribute::new(&[sp]);
    /// #
    /// // Add a User Attribute without a self-signature to the certificate.
    /// let cert = cert.insert_packets(ua)?;
    /// assert_eq!(cert.user_attributes().count(), 1);
    ///
    /// // Without a self-signature, it is definitely not valid.
    /// let vc = cert.with_policy(p, None)?;
    /// assert_eq!(vc.user_attributes().count(), 0);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn user_attributes(&self) -> ValidUserAttributeAmalgamationIter<'a> {
        self.cert.user_attributes().with_policy(self.policy, self.time)
    }

    /// Returns a list of any designated revokers for this certificate.
    ///
    /// This function returns the designated revokers listed on the
    /// primary key's binding signatures and the certificate's direct
    /// key signatures.
    ///
    /// Note: the returned list is deduplicated.
    ///
    /// In order to preserve our API during the 1.x series, this
    /// function takes an optional policy argument.  It should be
    /// `None`, but if it is `Some(_)`, it will be used instead of the
    /// `ValidCert`'s policy.  This makes the function signature
    /// compatible with [`Cert::revocation_keys`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::types::RevocationKey;
    ///
    /// # fn main() -> Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// let (alice, _) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .generate()?;
    /// // Make Alice a designated revoker for Bob.
    /// let (bob, _) =
    ///     CertBuilder::general_purpose(None, Some("bob@example.org"))
    ///     .set_revocation_keys(vec![(&alice).into()])
    ///     .generate()?;
    ///
    /// // Make sure Alice is listed as a designated revoker for Bob.
    /// assert_eq!(bob.with_policy(p, None)?.revocation_keys(None)
    ///            .collect::<Vec<&RevocationKey>>(),
    ///            vec![&(&alice).into()]);
    /// # Ok(()) }
    /// ```
    pub fn revocation_keys<P>(&self, policy: P)
        -> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>
    where
        P: Into<Option<&'a dyn Policy>>,
    {
        self.cert.revocation_keys(
            policy.into().unwrap_or_else(|| self.policy()))
    }
}

macro_rules! impl_pref {
    ($subpacket:ident, $rt:ty) => {
        #[allow(deprecated)]
        fn $subpacket(&self) -> Option<$rt>
        {
            // When addressed by the fingerprint or keyid, we first
            // look on the primary User ID and then fall back to the
            // direct key signature.  We need to be careful to handle
            // the case where there are no User IDs.
            if let Ok(u) = self.primary_userid() {
                u.$subpacket()
            } else if let Ok(sig) = self.direct_key_signature() {
                sig.$subpacket()
            } else {
                None
            }
        }
    }
}

impl<'a> seal::Sealed for ValidCert<'a> {}
impl<'a> Preferences<'a> for ValidCert<'a>
{
    impl_pref!(preferred_symmetric_algorithms, &'a [SymmetricAlgorithm]);
    impl_pref!(preferred_hash_algorithms, &'a [HashAlgorithm]);
    impl_pref!(preferred_compression_algorithms, &'a [CompressionAlgorithm]);
    impl_pref!(preferred_aead_algorithms, &'a [AEADAlgorithm]);
    impl_pref!(key_server_preferences, KeyServerPreferences);
    impl_pref!(preferred_key_server, &'a [u8]);
    impl_pref!(policy_uri, &'a [u8]);
    impl_pref!(features, Features);
}

#[cfg(test)]
mod test {
    use std::convert::TryInto;

    use crate::serialize::Serialize;
    use crate::policy::StandardPolicy as P;
    use crate::types::Curve;
    use crate::packet::signature;
    use crate::policy::HashAlgoSecurity;
    use super::*;

    use crate::{
        KeyID,
        types::KeyFlags,
    };

    fn parse_cert(data: &[u8], as_message: bool) -> Result<Cert> {
        if as_message {
            let pile = PacketPile::from_bytes(data).unwrap();
            Cert::try_from(pile)
        } else {
            Cert::from_bytes(data)
        }
    }

    #[test]
    fn broken() {
        use crate::types::Timestamp;
        for i in 0..2 {
            let cert = parse_cert(crate::tests::key("testy-broken-no-pk.pgp"),
                                i == 0);
            assert_match!(Error::MalformedCert(_)
                          = cert.err().unwrap().downcast::<Error>().unwrap());

            // According to 4880, a Cert must have a UserID.  But, we
            // don't require it.
            let cert = parse_cert(crate::tests::key("testy-broken-no-uid.pgp"),
                                i == 0);
            assert!(cert.is_ok());

            // We have:
            //
            //   [ pk, user id, sig, subkey ]
            let cert = parse_cert(crate::tests::key("testy-broken-no-sig-on-subkey.pgp"),
                                i == 0).unwrap();
            assert_eq!(cert.primary.key().creation_time(),
                       Timestamp::from(1511355130).into());
            assert_eq!(cert.userids.len(), 1);
            assert_eq!(cert.userids[0].userid().value(),
                       &b"Testy McTestface <testy@example.org>"[..]);
            assert_eq!(cert.userids[0].self_signatures2().count(), 1);
            assert_eq!(cert.userids[0].self_signatures2().next().unwrap()
                       .digest_prefix(),
                       &[ 0xc6, 0x8f ]);
            assert_eq!(cert.user_attributes.len(), 0);
            assert_eq!(cert.subkeys.len(), 1);
        }
    }

    #[test]
    fn basics() {
        use crate::types::Timestamp;
        for i in 0..2 {
            let cert = parse_cert(crate::tests::key("testy.pgp"),
                                i == 0).unwrap();
            assert_eq!(cert.primary.key().creation_time(),
                       Timestamp::from(1511355130).into());
            assert_eq!(format!("{:X}", cert.fingerprint()),
                       "3E8877C877274692975189F5D03F6F865226FE8B");

            assert_eq!(cert.userids.len(), 1, "number of userids");
            assert_eq!(cert.userids[0].userid().value(),
                       &b"Testy McTestface <testy@example.org>"[..]);
            assert_eq!(cert.userids[0].self_signatures2().count(), 1);
            assert_eq!(cert.userids[0].self_signatures2().next().unwrap()
                       .digest_prefix(),
                       &[ 0xc6, 0x8f ]);

            assert_eq!(cert.user_attributes.len(), 0);

            assert_eq!(cert.subkeys.len(), 1, "number of subkeys");
            assert_eq!(cert.subkeys[0].key().creation_time(),
                       Timestamp::from(1511355130).into());
            assert_eq!(cert.subkeys[0].self_signatures2().next().unwrap()
                       .digest_prefix(),
                       &[ 0xb7, 0xb9 ]);

            let cert = parse_cert(crate::tests::key("testy-no-subkey.pgp"),
                                i == 0).unwrap();
            assert_eq!(cert.primary.key().creation_time(),
                       Timestamp::from(1511355130).into());
            assert_eq!(format!("{:X}", cert.fingerprint()),
                       "3E8877C877274692975189F5D03F6F865226FE8B");

            assert_eq!(cert.user_attributes.len(), 0);

            assert_eq!(cert.userids.len(), 1, "number of userids");
            assert_eq!(cert.userids[0].userid().value(),
                       &b"Testy McTestface <testy@example.org>"[..]);
            assert_eq!(cert.userids[0].self_signatures2().count(), 1);
            assert_eq!(cert.userids[0].self_signatures2().next().unwrap()
                       .digest_prefix(),
                       &[ 0xc6, 0x8f ]);

            assert_eq!(cert.subkeys.len(), 0, "number of subkeys");

            let cert = parse_cert(crate::tests::key("testy.asc"), i == 0).unwrap();
            assert_eq!(format!("{:X}", cert.fingerprint()),
                       "3E8877C877274692975189F5D03F6F865226FE8B");
        }
    }

    #[test]
    fn only_a_public_key() {
        // Make sure the Cert parser can parse a key that just consists
        // of a public key---no signatures, no user ids, nothing.
        let cert = Cert::from_bytes(crate::tests::key("testy-only-a-pk.pgp")).unwrap();
        assert_eq!(cert.userids.len(), 0);
        assert_eq!(cert.user_attributes.len(), 0);
        assert_eq!(cert.subkeys.len(), 0);
    }

    #[test]
    fn merge() {
        use crate::tests::key;
        let cert_base = Cert::from_bytes(key("bannon-base.gpg")).unwrap();

        // When we merge it with itself, we should get the exact same
        // thing.
        let merged = cert_base.clone().merge_public_and_secret(cert_base.clone()).unwrap();
        assert_eq!(cert_base, merged);

        let cert_add_uid_1
            = Cert::from_bytes(key("bannon-add-uid-1-whitehouse.gov.gpg"))
                .unwrap();
        let cert_add_uid_2
            = Cert::from_bytes(key("bannon-add-uid-2-fox.com.gpg"))
                .unwrap();
        // Duplicate user id, but with a different self-sig.
        let cert_add_uid_3
            = Cert::from_bytes(key("bannon-add-uid-3-whitehouse.gov-dup.gpg"))
                .unwrap();

        let cert_all_uids
            = Cert::from_bytes(key("bannon-all-uids.gpg"))
            .unwrap();
        // We have four User ID packets, but one has the same User ID,
        // just with a different self-signature.
        assert_eq!(cert_all_uids.userids.len(), 3);

        // Merge in order.
        let merged = cert_base.clone().merge_public_and_secret(cert_add_uid_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_3.clone()).unwrap();
        assert_eq!(cert_all_uids, merged);

        // Merge in reverse order.
        let merged = cert_base.clone()
            .merge_public_and_secret(cert_add_uid_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_1.clone()).unwrap();
        assert_eq!(cert_all_uids, merged);

        let cert_add_subkey_1
            = Cert::from_bytes(key("bannon-add-subkey-1.gpg")).unwrap();
        let cert_add_subkey_2
            = Cert::from_bytes(key("bannon-add-subkey-2.gpg")).unwrap();
        let cert_add_subkey_3
            = Cert::from_bytes(key("bannon-add-subkey-3.gpg")).unwrap();

        let cert_all_subkeys
            = Cert::from_bytes(key("bannon-all-subkeys.gpg")).unwrap();

        // Merge the first user, then the second, then the third.
        let merged = cert_base.clone().merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_3.clone()).unwrap();
        assert_eq!(cert_all_subkeys, merged);

        // Merge the third user, then the second, then the first.
        let merged = cert_base.clone().merge_public_and_secret(cert_add_subkey_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap();
        assert_eq!(cert_all_subkeys, merged);

        // Merge a lot.
        let merged = cert_base.clone()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_2.clone()).unwrap();
        assert_eq!(cert_all_subkeys, merged);

        let cert_all
            = Cert::from_bytes(key("bannon-all-uids-subkeys.gpg"))
            .unwrap();

        // Merge all the subkeys with all the uids.
        let merged = cert_all_subkeys.clone()
            .merge_public_and_secret(cert_all_uids.clone()).unwrap();
        assert_eq!(cert_all, merged);

        // Merge all uids with all the subkeys.
        let merged = cert_all_uids.clone()
            .merge_public_and_secret(cert_all_subkeys.clone()).unwrap();
        assert_eq!(cert_all, merged);

        // All the subkeys and the uids in a mixed up order.
        let merged = cert_base.clone()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_3.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_2.clone()).unwrap()
            .merge_public_and_secret(cert_add_subkey_1.clone()).unwrap()
            .merge_public_and_secret(cert_add_uid_2.clone()).unwrap();
        assert_eq!(cert_all, merged);

        // Certifications.
        let cert_donald_signs_base
            = Cert::from_bytes(key("bannon-the-donald-signs-base.gpg"))
            .unwrap();
        let cert_donald_signs_all
            = Cert::from_bytes(key("bannon-the-donald-signs-all-uids.gpg"))
            .unwrap();
        let cert_ivanka_signs_base
            = Cert::from_bytes(key("bannon-ivanka-signs-base.gpg"))
            .unwrap();
        let cert_ivanka_signs_all
            = Cert::from_bytes(key("bannon-ivanka-signs-all-uids.gpg"))
            .unwrap();

        assert!(cert_donald_signs_base.userids.len() == 1);
        assert!(cert_donald_signs_base.userids[0].self_signatures2().count() == 1);
        assert!(cert_base.userids[0].certifications.is_empty());
        assert!(cert_donald_signs_base.userids[0].certifications.len() == 1);

        let merged = cert_donald_signs_base.clone()
            .merge_public_and_secret(cert_ivanka_signs_base.clone()).unwrap();
        assert!(merged.userids.len() == 1);
        assert!(merged.userids[0].self_signatures2().count() == 1);
        assert!(merged.userids[0].certifications.len() == 2);

        let merged = cert_donald_signs_base.clone()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap();
        assert!(merged.userids.len() == 3);
        assert!(merged.userids[0].self_signatures2().count() == 1);
        // There should be two certifications from the Donald on the
        // first user id.
        assert!(merged.userids[0].certifications.len() == 2);
        assert!(merged.userids[1].certifications.len() == 1);
        assert!(merged.userids[2].certifications.len() == 1);

        let merged = cert_donald_signs_base.clone()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_ivanka_signs_base.clone()).unwrap()
            .merge_public_and_secret(cert_ivanka_signs_all.clone()).unwrap();
        assert!(merged.userids.len() == 3);
        assert!(merged.userids[0].self_signatures2().count() == 1);
        // There should be two certifications from each of the Donald
        // and Ivanka on the first user id, and one each on the rest.
        assert!(merged.userids[0].certifications.len() == 4);
        assert!(merged.userids[1].certifications.len() == 2);
        assert!(merged.userids[2].certifications.len() == 2);

        // Same as above, but redundant.
        let merged = cert_donald_signs_base.clone()
            .merge_public_and_secret(cert_ivanka_signs_base.clone()).unwrap()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_ivanka_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_ivanka_signs_base.clone()).unwrap()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_donald_signs_all.clone()).unwrap()
            .merge_public_and_secret(cert_ivanka_signs_all.clone()).unwrap();
        assert!(merged.userids.len() == 3);
        assert!(merged.userids[0].self_signatures2().count() == 1);
        // There should be two certifications from each of the Donald
        // and Ivanka on the first user id, and one each on the rest.
        assert!(merged.userids[0].certifications.len() == 4);
        assert!(merged.userids[1].certifications.len() == 2);
        assert!(merged.userids[2].certifications.len() == 2);
    }

    #[test]
    fn out_of_order_self_sigs_test() {
        // neal-out-of-order.pgp contains all of the self-signatures,
        // but some are out of order.  The canonicalization step
        // should reorder them.
        //
        // original order/new order:
        //
        //  1/ 1. pk
        //  2/ 2. user id #1: neal@walfield.org (good)
        //  3/ 3. sig over user ID #1
        //
        //  4/ 4. user id #2: neal@gnupg.org (good)
        //  5/ 7. sig over user ID #3
        //  6/ 5. sig over user ID #2
        //
        //  7/ 6. user id #3: neal@g10code.com (bad)
        //
        //  8/ 8. user ID #4: neal@pep.foundation (bad)
        //  9/11. sig over user ID #5
        //
        // 10/10. user id #5: neal@pep-project.org (bad)
        // 11/ 9. sig over user ID #4
        //
        // 12/12. user ID #6: neal@sequoia-pgp.org (good)
        // 13/13. sig over user ID #6
        //
        // ----------------------------------------------
        //
        // 14/14. signing subkey #1: 7223B56678E02528 (good)
        // 15/15. sig over subkey #1
        // 16/16. sig over subkey #1
        //
        // 17/17. encryption subkey #2: C2B819056C652598 (good)
        // 18/18. sig over subkey #2
        // 19/21. sig over subkey #3
        // 20/22. sig over subkey #3
        //
        // 21/20. auth subkey #3: A3506AFB820ABD08 (bad)
        // 22/19. sig over subkey #2

        let cert = Cert::from_bytes(crate::tests::key("neal-sigs-out-of-order.pgp"))
            .unwrap();

        let mut userids = cert.userids()
            .map(|u| String::from_utf8_lossy(u.value()).into_owned())
            .collect::<Vec<String>>();
        userids.sort();

        assert_eq!(userids,
                   &[ "Neal H. Walfield <neal@g10code.com>",
                      "Neal H. Walfield <neal@gnupg.org>",
                      "Neal H. Walfield <neal@pep-project.org>",
                      "Neal H. Walfield <neal@pep.foundation>",
                      "Neal H. Walfield <neal@sequoia-pgp.org>",
                      "Neal H. Walfield <neal@walfield.org>",
                   ]);

        let mut subkeys = cert.subkeys()
            .map(|sk| Some(sk.key().keyid()))
            .collect::<Vec<Option<KeyID>>>();
        subkeys.sort();
        assert_eq!(subkeys,
                   &[ "7223B56678E02528".parse().ok(),
                      "A3506AFB820ABD08".parse().ok(),
                      "C2B819056C652598".parse().ok(),
                   ]);

        // DKG's key has all of the self-signatures moved to the last
        // subkey; all user ids/user attributes/subkeys have nothing.
        let cert =
            Cert::from_bytes(crate::tests::key("dkg-sigs-out-of-order.pgp")).unwrap();

        let mut userids = cert.userids()
            .map(|u| String::from_utf8_lossy(u.value()).into_owned())
            .collect::<Vec<String>>();
        userids.sort();

        assert_eq!(userids,
                   &[ "Daniel Kahn Gillmor <dkg-debian.org@fifthhorseman.net>",
                      "Daniel Kahn Gillmor <dkg@aclu.org>",
                      "Daniel Kahn Gillmor <dkg@astro.columbia.edu>",
                      "Daniel Kahn Gillmor <dkg@debian.org>",
                      "Daniel Kahn Gillmor <dkg@fifthhorseman.net>",
                      "Daniel Kahn Gillmor <dkg@openflows.com>",
                   ]);

        assert_eq!(cert.user_attributes.len(), 1);

        let mut subkeys = cert.subkeys()
            .map(|sk| Some(sk.key().keyid()))
            .collect::<Vec<Option<KeyID>>>();
        subkeys.sort();
        assert_eq!(subkeys,
                   &[ "1075 8EBD BD7C FAB5".parse().ok(),
                      "1258 68EA 4BFA 08E4".parse().ok(),
                      "1498 ADC6 C192 3237".parse().ok(),
                      "24EC FF5A FF68 370A".parse().ok(),
                      "3714 7292 14D5 DA70".parse().ok(),
                      "3B7A A7F0 14E6 9B5A".parse().ok(),
                      "5B58 DCF9 C341 6611".parse().ok(),
                      "A524 01B1 1BFD FA5C".parse().ok(),
                      "A70A 96E1 439E A852".parse().ok(),
                      "C61B D3EC 2148 4CFF".parse().ok(),
                      "CAEF A883 2167 5333".parse().ok(),
                      "DC10 4C4E 0CA7 57FB".parse().ok(),
                      "E3A3 2229 449B 0350".parse().ok(),
                   ]);

    }

    /// Tests how we deal with v3 keys, certs, and certifications.
    #[test]
    fn v3_packets() {
        // v3 primary keys are not supported.

        let cert = Cert::from_bytes(crate::tests::key("john-v3.pgp"));
        assert_match!(Error::UnsupportedCert2(..)
                      = cert.err().unwrap().downcast::<Error>().unwrap());

        let cert = Cert::from_bytes(crate::tests::key("john-v3-secret.pgp"));
        assert_match!(Error::UnsupportedCert2(..)
                      = cert.err().unwrap().downcast::<Error>().unwrap());

        // Lutz's key is a v3 key.
        let cert = Cert::from_bytes(crate::tests::key("lutz.gpg"));
        assert_match!(Error::UnsupportedCert2(..)
                      = cert.err().unwrap().downcast::<Error>().unwrap());

        // v3 certifications are not supported

        // dkg's includes some v3 signatures.
        let cert = Cert::from_bytes(crate::tests::key("dkg.gpg"));
        assert!(cert.is_ok(), "dkg.gpg: {:?}", cert);
    }

    #[test]
    fn keyring_with_v3_public_keys() {
        let dkg = crate::tests::key("dkg.gpg");
        let lutz = crate::tests::key("lutz.gpg");

        let cert = Cert::from_bytes(dkg);
        assert!(cert.is_ok(), "dkg.gpg: {:?}", cert);

        // Keyring with two good keys
        let mut combined = vec![];
        combined.extend_from_slice(dkg);
        combined.extend_from_slice(dkg);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ true, true ]);

        // Keyring with a good key, and a bad key.
        let mut combined = vec![];
        combined.extend_from_slice(dkg);
        combined.extend_from_slice(lutz);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ true, false ]);

        // Keyring with a bad key, and a good key.
        let mut combined = vec![];
        combined.extend_from_slice(lutz);
        combined.extend_from_slice(dkg);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ false, true ]);

        // Keyring with a good key, a bad key, and a good key.
        let mut combined = vec![];
        combined.extend_from_slice(dkg);
        combined.extend_from_slice(lutz);
        combined.extend_from_slice(dkg);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ true, false, true ]);

        // Keyring with a good key, a bad key, and a bad key.
        let mut combined = vec![];
        combined.extend_from_slice(dkg);
        combined.extend_from_slice(lutz);
        combined.extend_from_slice(lutz);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ true, false, false ]);

        // Keyring with a good key, a bad key, a bad key, and a good key.
        let mut combined = vec![];
        combined.extend_from_slice(dkg);
        combined.extend_from_slice(lutz);
        combined.extend_from_slice(lutz);
        combined.extend_from_slice(dkg);
        let certs = CertParser::from_bytes(&combined[..]).unwrap()
            .map(|certr| certr.is_ok())
            .collect::<Vec<bool>>();
        assert_eq!(certs, &[ true, false, false, true ]);
    }

    #[test]
    fn merge_with_incomplete_update() {
        let p = &P::new();

        let cert = Cert::from_bytes(crate::tests::key("about-to-expire.expired.pgp"))
            .unwrap();
        cert.primary_key().with_policy(p, None).unwrap().alive().unwrap_err();

        let update =
            Cert::from_bytes(crate::tests::key("about-to-expire.update-no-uid.pgp"))
            .unwrap();
        let cert = cert.merge_public_and_secret(update).unwrap();
        cert.primary_key().with_policy(p, None).unwrap().alive().unwrap();
    }

    #[test]
    fn packet_pile_roundtrip() {
        // Make sure Cert::try_from(Cert::to_packet_pile(cert))
        // does a clean round trip.

        let cert = Cert::from_bytes(crate::tests::key("already-revoked.pgp")).unwrap();
        let cert2
            = Cert::try_from(cert.clone().into_packet_pile()).unwrap();
        assert_eq!(cert, cert2);

        let cert = Cert::from_bytes(
            crate::tests::key("already-revoked-direct-revocation.pgp")).unwrap();
        let cert2
            = Cert::try_from(cert.clone().into_packet_pile()).unwrap();
        assert_eq!(cert, cert2);

        let cert = Cert::from_bytes(
            crate::tests::key("already-revoked-userid-revocation.pgp")).unwrap();
        let cert2
            = Cert::try_from(cert.clone().into_packet_pile()).unwrap();
        assert_eq!(cert, cert2);

        let cert = Cert::from_bytes(
            crate::tests::key("already-revoked-subkey-revocation.pgp")).unwrap();
        let cert2
            = Cert::try_from(cert.clone().into_packet_pile()).unwrap();
        assert_eq!(cert, cert2);
    }

    #[test]
    fn insert_packets_add_sig() {
        use crate::armor;
        use crate::packet::Tag;

        // Merge the revocation certificate into the Cert and make sure
        // it shows up.
        let cert = Cert::from_bytes(crate::tests::key("already-revoked.pgp")).unwrap();

        let rev = crate::tests::key("already-revoked.rev");
        let rev = PacketPile::from_reader(armor::Reader::from_reader(rev, None))
            .unwrap();

        let rev : Vec<Packet> = rev.into_children().collect();
        assert_eq!(rev.len(), 1);
        assert_eq!(rev[0].tag(), Tag::Signature);

        let packets_pre_merge = cert.clone().into_packets2().count();
        let cert = cert.insert_packets(rev).unwrap();
        let packets_post_merge = cert.clone().into_packets2().count();
        assert_eq!(packets_post_merge, packets_pre_merge + 1);
    }

    #[test]
    fn insert_packets_update_sig() -> Result<()> {
        use std::time::Duration;

        use crate::packet::signature::subpacket::Subpacket;
        use crate::packet::signature::subpacket::SubpacketValue;

        let (cert, _) = CertBuilder::general_purpose(None, Some("Test"))
            .generate()?;
        let packets = cert.clone().into_packets2().count();

        // Merge a signature with different unhashed subpacket areas.
        // Make sure only the last variant is merged.
        let sig = cert.primary_key().self_signatures().next()
            .expect("binding signature");

        let a = Subpacket::new(
            SubpacketValue::SignatureExpirationTime(
                Duration::new(1, 0).try_into()?),
            false)?;
        let b = Subpacket::new(
            SubpacketValue::SignatureExpirationTime(
                Duration::new(2, 0).try_into()?),
            false)?;

        let mut sig_a = sig.clone();
        sig_a.unhashed_area_mut().add(a)?;
        let mut sig_b = sig.clone();
        sig_b.unhashed_area_mut().add(b)?;

        // Insert sig_a, make sure it (and it alone) appears.
        let cert2 = cert.clone().insert_packets(sig_a.clone())?;
        let mut sigs = cert2.primary_key().self_signatures();
        assert_eq!(sigs.next(), Some(&sig_a));
        assert!(sigs.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert sig_b, make sure it (and it alone) appears.
        let cert2 = cert.clone().insert_packets(sig_b.clone())?;
        let mut sigs = cert2.primary_key().self_signatures();
        assert_eq!(sigs.next(), Some(&sig_b));
        assert!(sigs.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert sig_a and sig_b.  Make sure sig_b (and it alone)
        // appears.
        let cert2 = cert.clone().insert_packets(
            vec![ sig_a.clone(), sig_b.clone() ])?;
        let mut sigs = cert2.primary_key().self_signatures();
        assert_eq!(sigs.next(), Some(&sig_b));
        assert!(sigs.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert sig_b and sig_a.  Make sure sig_a (and it alone)
        // appears.
        let cert2 = cert.clone().insert_packets(
            vec![ sig_b.clone(), sig_a.clone() ])?;
        let mut sigs = cert2.primary_key().self_signatures();
        assert_eq!(sigs.next(), Some(&sig_a));
        assert!(sigs.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        Ok(())
    }

    #[test]
    fn insert_packets_add_userid() -> Result<()> {
        let (cert, _) = CertBuilder::general_purpose(None, Some("a"))
            .generate()?;
        let packets = cert.clone().into_packets2().count();

        let uid_a = UserID::from("a");
        let uid_b = UserID::from("b");

        // Insert a, make sure it appears once.
        let cert2 = cert.clone().insert_packets(uid_a.clone())?;
        let mut uids = cert2.userids();
        assert_eq!(uids.next().unwrap().userid(), &uid_a);
        assert!(uids.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert b, make sure it also appears.
        let cert2 = cert.clone().insert_packets(uid_b.clone())?;
        let mut uids: Vec<UserID>
            = cert2.userids().map(|ua| ua.userid().clone()).collect();
        uids.sort();
        let mut uids = uids.iter();
        assert_eq!(uids.next().unwrap(), &uid_a);
        assert_eq!(uids.next().unwrap(), &uid_b);
        assert!(uids.next().is_none());
        assert_eq!(cert2.clone().into_packets2().count(), packets + 1);

        Ok(())
    }

    #[test]
    fn insert_packets_update_key() -> Result<()> {
        use crate::crypto::Password;

        let (cert, _) = CertBuilder::new().generate()?;
        let packets = cert.clone().into_packets2().count();
        assert_eq!(cert.keys().count(), 1);

        let key = cert.keys().secret().next().unwrap().key();
        assert!(key.has_secret());
        let key_a = key.clone().encrypt_secret(&Password::from("a"))?
            .role_into_primary();
        let key_b = key.clone().encrypt_secret(&Password::from("b"))?
            .role_into_primary();

        // Insert variant a.
        let cert2 = cert.clone().insert_packets(key_a.clone())?;
        assert_eq!(cert2.primary_key().key().parts_as_secret().unwrap(),
                   &key_a);
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert variant b.
        let cert2 = cert.clone().insert_packets(key_b.clone())?;
        assert_eq!(cert2.primary_key().key().parts_as_secret().unwrap(),
                   &key_b);
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert variant a then b.  We should keep b.
        let cert2 = cert.clone().insert_packets(
            vec![ key_a.clone(), key_b.clone() ])?;
        assert_eq!(cert2.primary_key().key().parts_as_secret().unwrap(),
                   &key_b);
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        // Insert variant b then a.  We should keep a.
        let cert2 = cert.clone().insert_packets(
            vec![ key_b.clone(), key_a.clone() ])?;
        assert_eq!(cert2.primary_key().key().parts_as_secret().unwrap(),
                   &key_a);
        assert_eq!(cert2.clone().into_packets2().count(), packets);

        Ok(())
    }

    #[test]
    fn set_validity_period() {
        let p = &P::new();

        let (cert, _) = CertBuilder::general_purpose(None, Some("Test"))
            .generate().unwrap();
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
                   + 1 // userid
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
        );
        let cert = check_set_validity_period(p, cert);
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
                   + 2 // two new direct key signatures
                   + 1 // userid
                   + 1 // binding signature
                   + 2 // two new binding signatures
                   + 1 // subkey
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
        );
    }

    #[test]
    fn set_validity_period_two_uids() -> Result<()> {
        use quickcheck::{Arbitrary, Gen};
        let mut gen = Gen::new(16);
        let p = &P::new();

        let userid1 = UserID::arbitrary(&mut gen);
        // The two user ids need to be unique.
        let mut userid2 = UserID::arbitrary(&mut gen);
        while userid1 == userid2 {
            userid2 = UserID::arbitrary(&mut gen);
        }

        let (cert, _) = CertBuilder::general_purpose(
            None, Some(userid1))
            .add_userid(userid2)
            .generate()?;
        let primary_uid = cert.with_policy(p, None)?.primary_userid()?.userid().clone();
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
                   + 1 // userid
                   + 1 // binding signature
                   + 1 // userid
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
        );
        let cert = check_set_validity_period(p, cert);
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
                   + 2 // two new direct key signatures
                   + 1 // userid
                   + 1 // binding signature
                   + 2 // two new binding signatures
                   + 1 // userid
                   + 1 // binding signature
                   + 2 // two new binding signatures
                   + 1 // subkey
                   + 1 // binding signature
                   + 1 // subkey
                   + 1 // binding signature
        );
        assert_eq!(&primary_uid, cert.with_policy(p, None)?.primary_userid()?.userid());
        Ok(())
    }

    #[test]
    fn set_validity_period_uidless() {
        use crate::types::Duration;
        let p = &P::new();

        let (cert, _) = CertBuilder::new()
            .set_validity_period(None) // Just to assert this works.
            .set_validity_period(Some(Duration::weeks(52).unwrap().try_into().unwrap()))
            .generate().unwrap();
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
        );
        let cert = check_set_validity_period(p, cert);
        assert_eq!(cert.clone().into_packet_pile().children().count(),
                   1 // primary key
                   + 1 // direct key signature
                   + 2 // two new direct key signatures
        );
    }
    fn check_set_validity_period(policy: &dyn Policy, cert: Cert) -> Cert {
        let now = cert.primary_key().creation_time();
        let a_sec = time::Duration::new(1, 0);

        let expiry_orig = cert.primary_key().with_policy(policy, now).unwrap()
            .key_validity_period()
            .expect("Keys expire by default.");

        let mut keypair = cert.primary_key().key().clone().parts_into_secret()
            .unwrap().into_keypair().unwrap();

        // Clear the expiration.
        let as_of1 = now + time::Duration::new(10, 0);
        let cert = cert.set_validity_period_as_of(
            policy, &mut keypair, None, as_of1).unwrap();
        {
            // If t < as_of1, we should get the original expiry.
            assert_eq!(cert.primary_key().with_policy(policy, now).unwrap()
                           .key_validity_period(),
                       Some(expiry_orig));
            assert_eq!(cert.primary_key().with_policy(policy, as_of1 - a_sec).unwrap()
                           .key_validity_period(),
                       Some(expiry_orig));
            // If t >= as_of1, we should get the new expiry.
            assert_eq!(cert.primary_key().with_policy(policy, as_of1).unwrap()
                           .key_validity_period(),
                       None);
        }

        // Shorten the expiry.  (The default expiration should be at
        // least a few weeks, so removing an hour should still keep us
        // over 0.)
        let expiry_new = expiry_orig - time::Duration::new(60 * 60, 0);
        assert!(expiry_new > time::Duration::new(0, 0));

        let as_of2 = as_of1 + time::Duration::new(10, 0);
        let cert = cert.set_validity_period_as_of(
            policy, &mut keypair, Some(expiry_new), as_of2).unwrap();
        {
            // If t < as_of1, we should get the original expiry.
            assert_eq!(cert.primary_key().with_policy(policy, now).unwrap()
                           .key_validity_period(),
                       Some(expiry_orig));
            assert_eq!(cert.primary_key().with_policy(policy, as_of1 - a_sec).unwrap()
                           .key_validity_period(),
                       Some(expiry_orig));
            // If as_of1 <= t < as_of2, we should get the second
            // expiry (None).
            assert_eq!(cert.primary_key().with_policy(policy, as_of1).unwrap()
                           .key_validity_period(),
                       None);
            assert_eq!(cert.primary_key().with_policy(policy, as_of2 - a_sec).unwrap()
                           .key_validity_period(),
                       None);
            // If t <= as_of2, we should get the new expiry.
            assert_eq!(cert.primary_key().with_policy(policy, as_of2).unwrap()
                           .key_validity_period(),
                       Some(expiry_new));
        }
        cert
    }

    #[test]
    fn direct_key_sig() {
        use crate::types::SignatureType;
        // XXX: testing sequoia against itself isn't optimal, but I couldn't
        // find a tool to generate direct key signatures :-(

        let p = &P::new();

        let (cert1, _) = CertBuilder::new().generate().unwrap();
        let mut buf = Vec::default();

        cert1.serialize(&mut buf).unwrap();
        let cert2 = Cert::from_bytes(&buf).unwrap();

        assert_eq!(
            cert2.primary_key().with_policy(p, None).unwrap()
                .direct_key_signature().unwrap().typ(),
            SignatureType::DirectKey);
        assert_eq!(cert2.userids().count(), 0);
    }

    #[test]
    fn revoked() {
        fn check(cert: &Cert, direct_revoked: bool,
                 userid_revoked: bool, subkey_revoked: bool) {
            let p = &P::new();

            // If we have a user id---even if it is revoked---we have
            // a primary key signature.
            let typ = cert.primary_key().with_policy(p, None).unwrap()
                .binding_signature().typ();
            assert_eq!(typ, SignatureType::PositiveCertification,
                       "{:#?}", cert);

            let revoked = cert.revocation_status(p, None);
            if direct_revoked {
                assert_match!(RevocationStatus::Revoked(_) = revoked,
                              "{:#?}", cert);
            } else {
                assert_eq!(revoked, RevocationStatus::NotAsFarAsWeKnow,
                           "{:#?}", cert);
            }

            for userid in cert.userids().with_policy(p, None) {
                let typ = userid.binding_signature().typ();
                assert_eq!(typ, SignatureType::PositiveCertification,
                           "{:#?}", cert);

                let revoked = userid.revocation_status();
                if userid_revoked {
                    assert_match!(RevocationStatus::Revoked(_) = revoked);
                } else {
                    assert_eq!(RevocationStatus::NotAsFarAsWeKnow, revoked,
                               "{:#?}", cert);
                }
            }

            for subkey in cert.subkeys() {
                let typ = subkey.binding_signature(p, None).unwrap().typ();
                assert_eq!(typ, SignatureType::SubkeyBinding,
                           "{:#?}", cert);

                let revoked = subkey.revocation_status(p, None);
                if subkey_revoked {
                    assert_match!(RevocationStatus::Revoked(_) = revoked);
                } else {
                    assert_eq!(RevocationStatus::NotAsFarAsWeKnow, revoked,
                               "{:#?}", cert);
                }
            }
        }

        let cert = Cert::from_bytes(crate::tests::key("already-revoked.pgp")).unwrap();
        check(&cert, false, false, false);

        let d = Cert::from_bytes(
            crate::tests::key("already-revoked-direct-revocation.pgp")).unwrap();
        check(&d, true, false, false);

        check(&cert.clone().merge_public_and_secret(d.clone()).unwrap(), true, false, false);
        // Make sure the merge order does not matter.
        check(&d.clone().merge_public_and_secret(cert.clone()).unwrap(), true, false, false);

        let u = Cert::from_bytes(
            crate::tests::key("already-revoked-userid-revocation.pgp")).unwrap();
        check(&u, false, true, false);

        check(&cert.clone().merge_public_and_secret(u.clone()).unwrap(), false, true, false);
        check(&u.clone().merge_public_and_secret(cert.clone()).unwrap(), false, true, false);

        let k = Cert::from_bytes(
            crate::tests::key("already-revoked-subkey-revocation.pgp")).unwrap();
        check(&k, false, false, true);

        check(&cert.clone().merge_public_and_secret(k.clone()).unwrap(), false, false, true);
        check(&k.clone().merge_public_and_secret(cert.clone()).unwrap(), false, false, true);

        // direct and user id revocation.
        check(&d.clone().merge_public_and_secret(u.clone()).unwrap(), true, true, false);
        check(&u.clone().merge_public_and_secret(d.clone()).unwrap(), true, true, false);

        // direct and subkey revocation.
        check(&d.clone().merge_public_and_secret(k.clone()).unwrap(), true, false, true);
        check(&k.clone().merge_public_and_secret(d.clone()).unwrap(), true, false, true);

        // user id and subkey revocation.
        check(&u.clone().merge_public_and_secret(k.clone()).unwrap(), false, true, true);
        check(&k.clone().merge_public_and_secret(u.clone()).unwrap(), false, true, true);

        // direct, user id and subkey revocation.
        check(&d.clone().merge_public_and_secret(u.clone().merge_public_and_secret(k.clone()).unwrap()).unwrap(),
              true, true, true);
        check(&d.clone().merge_public_and_secret(k.clone().merge_public_and_secret(u.clone()).unwrap()).unwrap(),
              true, true, true);
    }

    #[test]
    fn revoke() {
        let p = &P::new();

        let (cert, _) = CertBuilder::general_purpose(None, Some("Test"))
            .generate().unwrap();
        assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
                   cert.revocation_status(p, None));

        let mut keypair = cert.primary_key().key().clone().parts_into_secret()
            .unwrap().into_keypair().unwrap();

        let sig = CertRevocationBuilder::new()
            .set_reason_for_revocation(
                ReasonForRevocation::KeyCompromised,
                b"It was the maid :/").unwrap()
            .build(&mut keypair, &cert, None)
            .unwrap();
        assert_eq!(sig.typ(), SignatureType::KeyRevocation);
        assert_eq!(sig.issuers().collect::<Vec<_>>(),
                   vec![ &cert.keyid() ]);
        assert_eq!(sig.issuer_fingerprints().collect::<Vec<_>>(),
                   vec![ &cert.fingerprint() ]);

        let cert = cert.insert_packets(sig).unwrap();
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, None));


        // Have other revoke cert.
        let (other, _) = CertBuilder::general_purpose(None, Some("Test 2"))
            .generate().unwrap();

        let mut keypair = other.primary_key().key().clone().parts_into_secret()
            .unwrap().into_keypair().unwrap();

        let sig = CertRevocationBuilder::new()
            .set_reason_for_revocation(
                ReasonForRevocation::KeyCompromised,
                b"It was the maid :/").unwrap()
            .build(&mut keypair, &cert, None)
            .unwrap();

        assert_eq!(sig.typ(), SignatureType::KeyRevocation);
        assert_eq!(sig.issuers().collect::<Vec<_>>(),
                   vec![ &other.keyid() ]);
        assert_eq!(sig.issuer_fingerprints().collect::<Vec<_>>(),
                   vec![ &other.fingerprint() ]);
    }

    #[test]
    fn revoke_subkey() {
        let p = &P::new();
        let (cert, _) = CertBuilder::new()
            .add_transport_encryption_subkey()
            .generate().unwrap();

        let sig = {
            let subkey = cert.subkeys().next().unwrap();
            assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
                       subkey.revocation_status(p, None));

            let mut keypair = cert.primary_key().key().clone().parts_into_secret()
                .unwrap().into_keypair().unwrap();
            SubkeyRevocationBuilder::new()
                .set_reason_for_revocation(
                    ReasonForRevocation::UIDRetired,
                    b"It was the maid :/").unwrap()
                .build(&mut keypair, &cert, subkey.key(), None)
                .unwrap()
        };
        assert_eq!(sig.typ(), SignatureType::SubkeyRevocation);
        let cert = cert.insert_packets(sig).unwrap();
        assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
                   cert.revocation_status(p, None));

        let subkey = cert.subkeys().next().unwrap();
        assert_match!(RevocationStatus::Revoked(_)
                      = subkey.revocation_status(p, None));
    }

    #[test]
    fn revoke_uid() {
        let p = &P::new();
        let (cert, _) = CertBuilder::new()
            .add_userid("Test1")
            .add_userid("Test2")
            .generate().unwrap();

        let sig = {
            let uid = cert.userids().with_policy(p, None).nth(1).unwrap();
            assert_eq!(RevocationStatus::NotAsFarAsWeKnow, uid.revocation_status());

            let mut keypair = cert.primary_key().key().clone().parts_into_secret()
                .unwrap().into_keypair().unwrap();
            UserIDRevocationBuilder::new()
                .set_reason_for_revocation(
                    ReasonForRevocation::UIDRetired,
                    b"It was the maid :/").unwrap()
                .build(&mut keypair, &cert, uid.userid(), None)
                .unwrap()
        };
        assert_eq!(sig.typ(), SignatureType::CertificationRevocation);
        let cert = cert.insert_packets(sig).unwrap();
        assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
                   cert.revocation_status(p, None));

        let uid = cert.userids().with_policy(p, None).nth(1).unwrap();
        assert_match!(RevocationStatus::Revoked(_) = uid.revocation_status());
    }

    #[test]
    fn key_revoked() {
        use crate::types::Features;
        use crate::packet::key::Key4;
        use rand::{thread_rng, Rng, distributions::Open01};

        let p = &P::new();

        /*
         * t1: 1st binding sig ctime
         * t2: soft rev sig ctime
         * t3: 2nd binding sig ctime
         * t4: hard rev sig ctime
         *
         * [0,t1): invalid, but not revoked
         * [t1,t2): valid (not revocations)
         * [t2,t3): revoked (soft revocation)
         * [t3,t4): valid again (new self sig)
         * [t4,inf): hard revocation (hard revocation)
         *
         * Once the hard revocation is merged, then the Cert is
         * considered revoked at all times.
         */
        let t1 = time::UNIX_EPOCH + time::Duration::new(946681200, 0);  // 2000-1-1
        let t2 = time::UNIX_EPOCH + time::Duration::new(978303600, 0);  // 2001-1-1
        let t3 = time::UNIX_EPOCH + time::Duration::new(1009839600, 0); // 2002-1-1
        let t4 = time::UNIX_EPOCH + time::Duration::new(1041375600, 0); // 2003-1-1

        let mut key: key::SecretKey
            = Key4::generate_ecc(true, Curve::Ed25519).unwrap().into();
        key.set_creation_time(t1).unwrap();
        let mut pair = key.clone().into_keypair().unwrap();
        let (bind1, rev1, bind2, rev2) = {
            let bind1 = signature::SignatureBuilder::new(SignatureType::DirectKey)
                .set_features(Features::sequoia()).unwrap()
                .set_key_flags(KeyFlags::empty()).unwrap()
                .set_signature_creation_time(t1).unwrap()
                .set_key_validity_period(Some(time::Duration::new(10 * 52 * 7 * 24 * 60 * 60, 0))).unwrap()
                .set_preferred_hash_algorithms(vec![HashAlgorithm::SHA512]).unwrap()
                .sign_direct_key(&mut pair, key.parts_as_public()).unwrap();

            let rev1 = signature::SignatureBuilder::new(SignatureType::KeyRevocation)
                .set_signature_creation_time(t2).unwrap()
                .set_reason_for_revocation(ReasonForRevocation::KeySuperseded,
                                           &b""[..]).unwrap()
                .sign_direct_key(&mut pair, key.parts_as_public()).unwrap();

            let bind2 = signature::SignatureBuilder::new(SignatureType::DirectKey)
                .set_features(Features::sequoia()).unwrap()
                .set_key_flags(KeyFlags::empty()).unwrap()
                .set_signature_creation_time(t3).unwrap()
                .set_key_validity_period(Some(time::Duration::new(10 * 52 * 7 * 24 * 60 * 60, 0))).unwrap()
                .set_preferred_hash_algorithms(vec![HashAlgorithm::SHA512]).unwrap()
                .sign_direct_key(&mut pair, key.parts_as_public()).unwrap();

            let rev2 = signature::SignatureBuilder::new(SignatureType::KeyRevocation)
                .set_signature_creation_time(t4).unwrap()
                .set_reason_for_revocation(ReasonForRevocation::KeyCompromised,
                                           &b""[..]).unwrap()
                .sign_direct_key(&mut pair, key.parts_as_public()).unwrap();

            (bind1, rev1, bind2, rev2)
        };
        let pk : key::PublicKey = key.into();
        let cert = Cert::try_from(vec![
            pk.into(),
            bind1.into(),
            bind2.into(),
            rev1.into()
        ]).unwrap();

        let f1: f32 = thread_rng().sample(Open01);
        let f2: f32 = thread_rng().sample(Open01);
        let f3: f32 = thread_rng().sample(Open01);
        let f4: f32 = thread_rng().sample(Open01);
        let te1 = t1 - time::Duration::new((60. * 60. * 24. * 300.0 * f1) as u64, 0);
        let t12 = t1 + time::Duration::new((60. * 60. * 24. * 300.0 * f2) as u64, 0);
        let t23 = t2 + time::Duration::new((60. * 60. * 24. * 300.0 * f3) as u64, 0);
        let t34 = t3 + time::Duration::new((60. * 60. * 24. * 300.0 * f4) as u64, 0);

        assert_eq!(cert.revocation_status(p, te1), RevocationStatus::NotAsFarAsWeKnow);
        assert_eq!(cert.revocation_status(p, t12), RevocationStatus::NotAsFarAsWeKnow);
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, t23));
        assert_eq!(cert.revocation_status(p, t34), RevocationStatus::NotAsFarAsWeKnow);

        // Merge in the hard revocation.
        let cert = cert.insert_packets(rev2).unwrap();
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, te1));
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, t12));
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, t23));
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, t34));
        assert_match!(RevocationStatus::Revoked(_) = cert.revocation_status(p, t4));
        assert_match!(RevocationStatus::Revoked(_)
                      = cert.revocation_status(p, crate::now()));
    }

    #[test]
    fn key_revoked2() {
        tracer!(true, "cert_revoked2", 0);

        let p = &P::new();

        fn cert_revoked<T>(p: &dyn Policy, cert: &Cert, t: T) -> bool
            where T: Into<Option<time::SystemTime>>
        {
            !matches!(
                cert.revocation_status(p, t),
                RevocationStatus::NotAsFarAsWeKnow
            )
        }

        fn subkey_revoked<T>(p: &dyn Policy, cert: &Cert, t: T) -> bool
            where T: Into<Option<time::SystemTime>>
        {
            !matches!(
                cert.subkeys().next().unwrap().bundle().revocation_status(p, t),
                RevocationStatus::NotAsFarAsWeKnow
            )
        }

        let tests : [(&str, Box<dyn Fn(&dyn Policy, &Cert, _) -> bool>); 2] = [
            ("cert", Box::new(cert_revoked)),
            ("subkey", Box::new(subkey_revoked)),
        ];

        for (f, revoked) in tests.iter()
        {
            t!("Checking {} revocation", f);

            t!("Normal key");
            let cert = Cert::from_bytes(
                crate::tests::key(
                    &format!("really-revoked-{}-0-public.pgp", f))).unwrap();
            let selfsig0 = cert.primary_key().with_policy(p, None).unwrap()
                .binding_signature().signature_creation_time().unwrap();

            assert!(!revoked(p, &cert, Some(selfsig0)));
            assert!(!revoked(p, &cert, None));

            t!("Soft revocation");
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-1-soft-revocation.pgp", f))
                ).unwrap()).unwrap();
            // A soft revocation made after `t` is ignored when
            // determining whether the key is revoked at time `t`.
            assert!(!revoked(p, &cert, Some(selfsig0)));
            assert!(revoked(p, &cert, None));

            t!("New self signature");
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-2-new-self-sig.pgp", f))
                ).unwrap()).unwrap();
            assert!(!revoked(p, &cert, Some(selfsig0)));
            // Newer self-sig override older soft revocations.
            assert!(!revoked(p, &cert, None));

            t!("Hard revocation");
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-3-hard-revocation.pgp", f))
                ).unwrap()).unwrap();
            // Hard revocations trump all.
            assert!(revoked(p, &cert, Some(selfsig0)));
            assert!(revoked(p, &cert, None));

            t!("New self signature");
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-4-new-self-sig.pgp", f))
                ).unwrap()).unwrap();
            assert!(revoked(p, &cert, Some(selfsig0)));
            assert!(revoked(p, &cert, None));
        }
    }

    #[test]
    fn userid_revoked2() {
        fn check_userids<T>(p: &dyn Policy, cert: &Cert, revoked: bool, t: T)
            where T: Into<Option<time::SystemTime>>, T: Copy
        {
            assert_match!(RevocationStatus::NotAsFarAsWeKnow
                          = cert.revocation_status(p, None));

            let mut slim_shady = false;
            let mut eminem = false;
            for b in cert.userids().with_policy(p, t) {
                if b.userid().value() == b"Slim Shady" {
                    assert!(!slim_shady);
                    slim_shady = true;

                    if revoked {
                        assert_match!(RevocationStatus::Revoked(_)
                                      = b.revocation_status());
                    } else {
                        assert_match!(RevocationStatus::NotAsFarAsWeKnow
                                      = b.revocation_status());
                    }
                } else {
                    assert!(!eminem);
                    eminem = true;

                    assert_match!(RevocationStatus::NotAsFarAsWeKnow
                                  = b.revocation_status());
                }
            }

            assert!(slim_shady);
            assert!(eminem);
        }

        fn check_uas<T>(p: &dyn Policy, cert: &Cert, revoked: bool, t: T)
            where T: Into<Option<time::SystemTime>>, T: Copy
        {
            assert_match!(RevocationStatus::NotAsFarAsWeKnow
                          = cert.revocation_status(p, None));

            assert_eq!(cert.user_attributes().count(), 1);
            let ua = cert.user_attributes().next().unwrap();
            if revoked {
                assert_match!(RevocationStatus::Revoked(_)
                              = ua.revocation_status(p, t));
            } else {
                assert_match!(RevocationStatus::NotAsFarAsWeKnow
                              = ua.revocation_status(p, t));
            }
        }

        tracer!(true, "userid_revoked2", 0);

        let p = &P::new();
        let tests : [(&str, Box<dyn Fn(&dyn Policy, &Cert, bool, _)>); 2] = [
            ("userid", Box::new(check_userids)),
            ("user-attribute", Box::new(check_uas)),
        ];

        for (f, check) in tests.iter()
        {
            t!("Checking {} revocation", f);

            t!("Normal key");
            let cert = Cert::from_bytes(
                crate::tests::key(
                    &format!("really-revoked-{}-0-public.pgp", f))).unwrap();

            let now = crate::now();
            let selfsig0
                = cert.userids().with_policy(p, now).map(|b| {
                    b.binding_signature().signature_creation_time().unwrap()
                })
                .max().unwrap();

            check(p, &cert, false, selfsig0);
            check(p, &cert, false, now);

            // A soft-revocation.
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-1-soft-revocation.pgp", f))
                ).unwrap()).unwrap();

            check(p, &cert, false, selfsig0);
            check(p, &cert, true, now);

            // A new self signature.  This should override the soft-revocation.
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-2-new-self-sig.pgp", f))
                ).unwrap()).unwrap();

            check(p, &cert, false, selfsig0);
            check(p, &cert, false, now);

            // A hard revocation.  Unlike for Certs, this does NOT trumps
            // everything.
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-3-hard-revocation.pgp", f))
                ).unwrap()).unwrap();

            check(p, &cert, false, selfsig0);
            check(p, &cert, true, now);

            // A newer self signature.
            let cert = cert.merge_public_and_secret(
                Cert::from_bytes(
                    crate::tests::key(
                        &format!("really-revoked-{}-4-new-self-sig.pgp", f))
                ).unwrap()).unwrap();

            check(p, &cert, false, selfsig0);
            check(p, &cert, false, now);
        }
    }

    #[test]
    fn unrevoked() {
        let p = &P::new();
        let cert =
            Cert::from_bytes(crate::tests::key("un-revoked-userid.pgp")).unwrap();

        for uid in cert.userids().with_policy(p, None) {
            assert_eq!(uid.revocation_status(), RevocationStatus::NotAsFarAsWeKnow);
        }
    }

    #[test]
    fn is_tsk() {
        let cert = Cert::from_bytes(
            crate::tests::key("already-revoked.pgp")).unwrap();
        assert!(! cert.is_tsk());

        let cert = Cert::from_bytes(
            crate::tests::key("already-revoked-private.pgp")).unwrap();
        assert!(cert.is_tsk());
    }

    #[test]
    fn export_only_exports_public_key() {
        let cert = Cert::from_bytes(
            crate::tests::key("testy-new-private.pgp")).unwrap();
        assert!(cert.is_tsk());

        let mut v = Vec::new();
        cert.serialize(&mut v).unwrap();
        let cert = Cert::from_bytes(&v).unwrap();
        assert!(! cert.is_tsk());
    }

    // Make sure that when merging two Certs, the primary key and
    // subkeys with and without a private key are merged.
    #[test]
    fn public_private_merge() {
        let (tsk, _) = CertBuilder::general_purpose(None, Some("foo@example.com"))
            .generate().unwrap();
        // tsk is now a cert, but it still has its private bits.
        assert!(tsk.primary.key().has_secret());
        assert!(tsk.is_tsk());
        let subkey_count = tsk.subkeys().len();
        assert!(subkey_count > 0);
        assert!(tsk.subkeys().all(|k| k.key().has_secret()));

        // This will write out the tsk as a cert, i.e., without any
        // private bits.
        let mut cert_bytes = Vec::new();
        tsk.serialize(&mut cert_bytes).unwrap();

        // Reading it back in, the private bits have been stripped.
        let cert = Cert::from_bytes(&cert_bytes[..]).unwrap();
        assert!(! cert.primary.key().has_secret());
        assert!(!cert.is_tsk());
        assert!(cert.subkeys().all(|k| ! k.key().has_secret()));

        let merge1 = cert.clone().merge_public_and_secret(tsk.clone()).unwrap();
        assert!(merge1.is_tsk());
        assert!(merge1.primary.key().has_secret());
        assert_eq!(merge1.subkeys().len(), subkey_count);
        assert!(merge1.subkeys().all(|k| k.key().has_secret()));

        let merge2 = tsk.clone().merge_public_and_secret(cert.clone()).unwrap();
        assert!(merge2.is_tsk());
        assert!(merge2.primary.key().has_secret());
        assert_eq!(merge2.subkeys().len(), subkey_count);
        assert!(merge2.subkeys().all(|k| k.key().has_secret()));
    }

    #[test]
    fn issue_120() {
        let cert = "
-----BEGIN PGP ARMORED FILE-----

xcBNBFoVcvoBCACykTKOJddF8SSUAfCDHk86cNTaYnjCoy72rMgWJsrMLnz/V16B
J9M7l6nrQ0JMnH2Du02A3w+kNb5q97IZ/M6NkqOOl7uqjyRGPV+XKwt0G5mN/ovg
8630BZAYS3QzavYf3tni9aikiGH+zTFX5pynTNfYRXNBof3Xfzl92yad2bIt4ITD
NfKPvHRko/tqWbclzzEn72gGVggt1/k/0dKhfsGzNogHxg4GIQ/jR/XcqbDFR3RC
/JJjnTOUPGsC1y82Xlu8udWBVn5mlDyxkad5laUpWWg17anvczEAyx4TTOVItLSu
43iPdKHSs9vMXWYID0bg913VusZ2Ofv690nDABEBAAHNJFRlc3R5IE1jVGVzdGZh
Y2UgPHRlc3R5QGV4YW1wbGUub3JnPsLAlAQTAQgAPhYhBD6Id8h3J0aSl1GJ9dA/
b4ZSJv6LBQJaFXL6AhsDBQkDwmcABQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJ
ENA/b4ZSJv6Lxo8H/1XMt+Nqa6e0SG/up3ypKe5nplA0p/9j/s2EIsP8S8uPUd+c
WS17XOmPwkNDmHeL3J6hzwL74NlYSLEtyf7WoOV74xAKQA9WkqaKPHCtpll8aFWA
ktQDLWTPeKuUuSlobAoRtO17ZmheSQzmm7JYt4Ahkxt3agqGT05OsaAey6nIKqpq
ArokvdHTZ7AFZeSJIWmuCoT9M1lo3LAtLnRGOhBMJ5dDIeOwflJwNBXlJVi4mDPK
+fumV0MbSPvZd1/ivFjSpQyudWWtv1R1nAK7+a4CPTGxPvAQkLtRsL/V+Q7F3BJG
jAn4QVx8p4t3NOPuNgcoZpLBE3sc4Nfs5/CphMLHwE0EWhVy+gEIALSpjYD+tuWC
rj6FGP6crQjQzVlH+7axoM1ooTwiPs4fzzt2iLw3CJyDUviM5F9ZBQTei635RsAR
a/CJTSQYAEU5yXXxhoe0OtwnuvsBSvVT7Fox3pkfNTQmwMvkEbodhfKpqBbDKCL8
f5A8Bb7aISsLf0XRHWDkHVqlz8LnOR3f44wEWiTeIxLc8S1QtwX/ExyW47oPsjs9
ShCmwfSpcngH/vGBRTO7WeI54xcAtKSm/20B/MgrUl5qFo17kUWot2C6KjuZKkHk
3WZmJwQz+6rTB11w4AXt8vKkptYQCkfat2FydGpgRO5dVg6aWNJefOJNkC7MmlzC
ZrrAK8FJ6jcAEQEAAcLAdgQYAQgAIBYhBD6Id8h3J0aSl1GJ9dA/b4ZSJv6LBQJa
FXL6AhsMAAoJENA/b4ZSJv6Lt7kH/jPr5wg8lcamuLj4lydYiLttvvTtDTlD1TL+
IfwVARB/ruoerlEDr0zX1t3DCEcvJDiZfOqJbXtHt70+7NzFXrYxfaNFmikMgSQT
XqHrMQho4qpseVOeJPWGzGOcrxCdw/ZgrWbkDlAU5KaIvk+M4wFPivjbtW2Ro2/F
J4I/ZHhJlIPmM+hUErHC103b08pBENXDQlXDma7LijH5kWhyfF2Ji7Ft0EjghBaW
AeGalQHjc5kAZu5R76Mwt06MEQ/HL1pIvufTFxkr/SzIv8Ih7Kexb0IrybmfD351
Pu1xwz57O4zo1VYf6TqHJzVC3OMvMUM2hhdecMUe5x6GorNaj6g=
=1Vzu
-----END PGP ARMORED FILE-----
";
        assert!(Cert::from_bytes(cert).is_err());
    }

    #[test]
    fn missing_uids() {
        let (cert, _) = CertBuilder::new()
            .add_userid("test1@example.com")
            .add_userid("test2@example.com")
            .add_transport_encryption_subkey()
            .add_certification_subkey()
            .generate().unwrap();
        assert_eq!(cert.subkeys().len(), 2);
        let pile = cert
            .into_packet_pile()
            .into_children()
            .filter(|pkt| {
                match pkt {
                    &Packet::PublicKey(_) | &Packet::PublicSubkey(_)
                    | &Packet::SecretKey(_) | &Packet::SecretSubkey(_) => true,
                    &Packet::Signature(ref sig) => {
                        sig.typ() == SignatureType::DirectKey
                            || sig.typ() == SignatureType::SubkeyBinding
                    }
                    e => {
                        eprintln!("{:?}", e);
                        false
                    }
                }
            })
        .collect::<Vec<_>>();
        eprintln!("parse back");
        let cert = Cert::try_from(pile).unwrap();

        assert_eq!(cert.subkeys().len(), 2);
    }

    #[test]
    fn signature_order() {
        let p = &P::new();
        let neal = Cert::from_bytes(crate::tests::key("neal.pgp")).unwrap();

        // This test is useless if we don't have some lists with more
        // than one signature.
        let mut cmps = 0;

        for uid in neal.userids() {
            for sigs in [
                uid.self_signatures().collect::<Vec<_>>(),
                uid.certifications().collect::<Vec<_>>(),
                uid.self_revocations().collect::<Vec<_>>(),
                uid.other_revocations().collect::<Vec<_>>()
            ].iter() {
                for sigs in sigs.windows(2) {
                    cmps += 1;
                    assert!(sigs[0].signature_creation_time()
                            >= sigs[1].signature_creation_time());
                }
            }

            // Make sure we return the most recent first.
            assert_eq!(uid.self_signatures().next().unwrap(),
                       uid.binding_signature(p, None).unwrap());
        }

        assert!(cmps > 0);
    }

    #[test]
    fn cert_reject_keyrings() {
        let mut keyring = Vec::new();
        keyring.extend_from_slice(crate::tests::key("neal.pgp"));
        keyring.extend_from_slice(crate::tests::key("neal.pgp"));
        assert!(Cert::from_bytes(&keyring).is_err());
    }

    #[test]
    fn primary_userid() {
        // 'really-revoked-userid' has two user ids.  One of them is
        // revoked and then restored.  Neither of the user ids has the
        // primary userid bit set.
        //
        // This test makes sure that Cert::primary_userid prefers
        // unrevoked user ids to revoked user ids, even if the latter
        // have newer self signatures.

        let p = &P::new();
        let cert = Cert::from_bytes(
            crate::tests::key("really-revoked-userid-0-public.pgp")).unwrap();

        let now = crate::now();
        let selfsig0
            = cert.userids().with_policy(p, now).map(|b| {
                b.binding_signature().signature_creation_time().unwrap()
            })
            .max().unwrap();

        // The self-sig for:
        //
        //   Slim Shady: 2019-09-14T14:21
        //   Eminem:     2019-09-14T14:22
        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");

        // A soft-revocation for "Slim Shady".
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("really-revoked-userid-1-soft-revocation.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");

        // A new self signature for "Slim Shady".  This should
        // override the soft-revocation.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("really-revoked-userid-2-new-self-sig.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Slim Shady");

        // A hard revocation for "Slim Shady".
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("really-revoked-userid-3-hard-revocation.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");

        // A newer self signature for "Slim Shady". Unlike for Certs, this
        // does NOT trump everything.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("really-revoked-userid-4-new-self-sig.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Eminem");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"Slim Shady");

        // Play with the primary user id flag.

        let cert = Cert::from_bytes(
            crate::tests::key("primary-key-0-public.pgp")).unwrap();
        let selfsig0
            = cert.userids().with_policy(p, now).map(|b| {
                b.binding_signature().signature_creation_time().unwrap()
            })
            .max().unwrap();

        // There is only a single User ID.
        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");


        // Add a second user id.  Since neither is marked primary, the
        // newer one should be considered primary.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-1-add-userid-bbbbb.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"bbbbb");

        // Mark aaaaa as primary.  It is now primary and the newest one.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-2-make-aaaaa-primary.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");

        // Update the preferences on bbbbb.  It is now the newest, but
        // it is not marked as primary.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-3-make-bbbbb-new-self-sig.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");

        // Mark bbbbb as primary.  It is now the newest and marked as
        // primary.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-4-make-bbbbb-primary.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"bbbbb");

        // Update the preferences on aaaaa.  It is now has the newest
        // self sig, but that self sig does not say that it is
        // primary.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-5-make-aaaaa-self-sig.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"bbbbb");

        // Hard revoke aaaaa.  Unlike with Certs, a hard revocation is
        // not treated specially.
        let cert = cert.merge_public_and_secret(
            Cert::from_bytes(
                crate::tests::key("primary-key-6-revoked-aaaaa.pgp")
            ).unwrap()).unwrap();

        assert_eq!(cert.with_policy(p, selfsig0).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"aaaaa");
        assert_eq!(cert.with_policy(p, now).unwrap()
                   .primary_userid().unwrap().userid().value(),
                   b"bbbbb");
    }

    #[test]
    fn binding_signature_lookup() {
        // Check that searching for the right binding signature works
        // even when there are signatures with the same time.

        use crate::types::Features;
        use crate::packet::key::Key4;

        let p = &P::new();

        let a_sec = time::Duration::new(1, 0);
        let time_zero = time::UNIX_EPOCH;

        let t1 = time::UNIX_EPOCH + time::Duration::new(946681200, 0);  // 2000-1-1
        let t2 = time::UNIX_EPOCH + time::Duration::new(978303600, 0);  // 2001-1-1
        let t3 = time::UNIX_EPOCH + time::Duration::new(1009839600, 0); // 2002-1-1
        let t4 = time::UNIX_EPOCH + time::Duration::new(1041375600, 0); // 2003-1-1

        let mut key: key::SecretKey
            = Key4::generate_ecc(true, Curve::Ed25519).unwrap().into();
        key.set_creation_time(t1).unwrap();
        let mut pair = key.clone().into_keypair().unwrap();
        let pk : key::PublicKey = key.clone().into();
        let mut cert = Cert::try_from(vec![
            pk.into(),
        ]).unwrap();
        let uid: UserID = "foo@example.org".into();
        let sig = uid.certify(&mut pair, &cert,
                              SignatureType::PositiveCertification,
                              None,
                              t1).unwrap();
        cert = cert.insert_packets(
            vec![Packet::from(uid), sig.into()]).unwrap();

        const N: usize = 5;
        for (t, offset) in &[ (t2, 0), (t4, 0), (t3, 1 * N), (t1, 3 * N) ] {
            for i in 0..N {
                let binding = signature::SignatureBuilder::new(SignatureType::DirectKey)
                    .set_features(Features::sequoia()).unwrap()
                    .set_key_flags(KeyFlags::empty()).unwrap()
                    .set_signature_creation_time(t1).unwrap()
                    // Vary this...
                    .set_key_validity_period(Some(
                        time::Duration::new((1 + i as u64) * 24 * 60 * 60, 0)))
                    .unwrap()
                    .set_preferred_hash_algorithms(vec![HashAlgorithm::SHA512]).unwrap()
                    .set_signature_creation_time(*t).unwrap()
                    .sign_direct_key(&mut pair, key.parts_as_public()).unwrap();

                let binding : Packet = binding.into();

                cert = cert.insert_packets(binding).unwrap();
                // A time that matches multiple signatures.
                let direct_signatures =
                    cert.primary_key().bundle().self_signatures2()
                    .collect::<Vec<_>>();
                assert_eq!(cert.primary_key().with_policy(p, *t).unwrap()
                           .direct_key_signature().ok(),
                           direct_signatures.get(*offset).cloned());
                // A time that doesn't match any signature.
                assert_eq!(cert.primary_key().with_policy(p, *t + a_sec).unwrap()
                           .direct_key_signature().ok(),
                           direct_signatures.get(*offset).cloned());

                // The current time, which should use the first signature.
                assert_eq!(cert.primary_key().with_policy(p, None).unwrap()
                           .direct_key_signature().ok(),
                           direct_signatures.get(0).cloned());

                // The beginning of time, which should return no
                // binding signatures.
                assert!(cert.primary_key().with_policy(p, time_zero).is_err());
            }
        }
    }

    #[test]
    fn keysigning_party() {
        use crate::packet::signature;

        for cs in &[ CipherSuite::Cv25519,
                     CipherSuite::P256,
                     CipherSuite::P384,
                     CipherSuite::P521,
                     CipherSuite::RSA2k ]
        {
            if cs.is_supported().is_err() {
                eprintln!("Skipping {:?} because it is not supported.", cs);
                continue;
            }

            let (alice, _) = CertBuilder::new()
                .set_cipher_suite(*cs)
                .add_userid("alice@foo.com")
                .generate().unwrap();

            let (bob, _) = CertBuilder::new()
                .set_cipher_suite(*cs)
                .add_userid("bob@bar.com")
                .add_signing_subkey()
                .generate().unwrap();

            assert_eq!(bob.userids().len(), 1);
            let bob_userid_binding = bob.userids().next().unwrap();
            assert_eq!(bob_userid_binding.userid().value(), b"bob@bar.com");

            let sig_template
                = signature::SignatureBuilder::new(SignatureType::GenericCertification)
                      .set_trust_signature(255, 120)
                      .unwrap();

            // Have alice certify the binding "bob@bar.com" and bob's key.
            let alice_certifies_bob
                = bob_userid_binding.userid().bind(
                    &mut alice.primary_key().key().clone().parts_into_secret()
                        .unwrap().into_keypair().unwrap(),
                    &bob,
                    sig_template).unwrap();

            let bob = bob.insert_packets(alice_certifies_bob.clone()).unwrap();

            // Make sure the certification is merged, and put in the right
            // place.
            assert_eq!(bob.userids().len(), 1);
            let bob_userid_binding = bob.userids().next().unwrap();
            assert_eq!(bob_userid_binding.userid().value(), b"bob@bar.com");

            // Canonicalizing Bob's cert without having Alice's key
            // has to resort to a heuristic to order third party
            // signatures.  However, since we know the signature's
            // type (GenericCertification), we know that it can only
            // go to the only userid, so there is no ambiguity in this
            // case.
            assert_eq!(bob_userid_binding.certifications().collect::<Vec<_>>(),
                       vec![&alice_certifies_bob]);

            // Make sure the certification is correct.
            alice_certifies_bob
                .verify_userid_binding(alice.primary_key().key(),
                                       bob.primary_key().key(),
                                       bob_userid_binding.userid()).unwrap();
        }
   }

    #[test]
    fn decrypt_encrypt_secrets() -> Result<()> {
        let p: crate::crypto::Password = "streng geheim".into();
        let (mut cert, _) = CertBuilder::new()
            .add_transport_encryption_subkey()
            .set_password(Some(p.clone()))
            .generate()?;
        assert_eq!(cert.keys().secret().count(), 2);
        assert_eq!(cert.keys().unencrypted_secret().count(), 0);

        for (i, ka) in cert.clone().keys().secret().enumerate() {
            let key = ka.key().clone().decrypt_secret(&p)?;
            cert = if i == 0 {
                cert.insert_packets(key.role_into_primary())?
            } else {
                cert.insert_packets(key.role_into_subordinate())?
            };
            assert_eq!(cert.keys().secret().count(), 2);
            assert_eq!(cert.keys().unencrypted_secret().count(), i + 1);
        }

        assert_eq!(cert.keys().secret().count(), 2);
        assert_eq!(cert.keys().unencrypted_secret().count(), 2);

        for (i, ka) in cert.clone().keys().secret().enumerate() {
            let key = ka.key().clone().encrypt_secret(&p)?;
            cert = if i == 0 {
                cert.insert_packets(key.role_into_primary())?
            } else {
                cert.insert_packets(key.role_into_subordinate())?
            };
            assert_eq!(cert.keys().secret().count(), 2);
            assert_eq!(cert.keys().unencrypted_secret().count(), 2 - 1 - i);
        }

        assert_eq!(cert.keys().secret().count(), 2);
        assert_eq!(cert.keys().unencrypted_secret().count(), 0);
        Ok(())
    }

    /// Tests that Cert:.into_packets2() and Cert::serialize(..) agree.
    #[test]
    fn test_into_packets2() -> Result<()> {
        use crate::serialize::SerializeInto;

        let dkg = Cert::from_bytes(crate::tests::key("dkg.gpg"))?;
        let mut buf = Vec::new();
        for p in dkg.clone().into_packets2() {
            p.serialize(&mut buf)?;
        }
        let dkg = dkg.to_vec()?;
        if false && buf != dkg {
            std::fs::write("/tmp/buf", &buf)?;
            std::fs::write("/tmp/dkg", &dkg)?;
        }
        assert_eq!(buf, dkg);
        Ok(())
    }

    #[test]
    fn test_canonicalization() -> Result<()> {
        let p = crate::policy::StandardPolicy::new();

        let primary: Key<_, key::PrimaryRole> =
            key::Key4::generate_ecc(true, Curve::Ed25519)?.into();
        let mut primary_pair = primary.clone().into_keypair()?;
        let cert = Cert::try_from(vec![primary.into()])?;

        // We now add components without binding signatures.  They
        // should be kept, be enumerable, but ignored if a policy is
        // applied.

        // Add a bare userid.
        let uid = UserID::from("foo@example.org");
        let cert = cert.insert_packets(uid)?;
        assert_eq!(cert.userids().count(), 1);
        assert_eq!(cert.userids().with_policy(&p, None).count(), 0);

        // Add a bare user attribute.
        use packet::user_attribute::{Subpacket, Image};
        let ua = UserAttribute::new(&[
            Subpacket::Image(
                Image::Private(100, vec![0, 1, 2].into_boxed_slice())),
        ])?;
        let cert = cert.insert_packets(ua)?;
        assert_eq!(cert.user_attributes().count(), 1);
        assert_eq!(cert.user_attributes().with_policy(&p, None).count(), 0);

        // Add a bare signing subkey.
        let signing_subkey: Key<_, key::SubordinateRole> =
            key::Key4::generate_ecc(true, Curve::Ed25519)?.into();
        let _signing_subkey_pair = signing_subkey.clone().into_keypair()?;
        let cert = cert.insert_packets(signing_subkey)?;
        assert_eq!(cert.keys().subkeys().count(), 1);
        assert_eq!(cert.keys().subkeys().with_policy(&p, None).count(), 0);

        // Add a component that Sequoia doesn't understand.
        let mut fake_key = packet::Unknown::new(
            packet::Tag::PublicSubkey, anyhow::anyhow!("fake key"));
        fake_key.set_body("fake key".into());
        let fake_binding = signature::SignatureBuilder::new(
                SignatureType::Unknown(SignatureType::SubkeyBinding.into()))
            .sign_standalone(&mut primary_pair)?;
        let cert = cert.insert_packets(vec![Packet::from(fake_key),
                                           fake_binding.clone().into()])?;
        assert_eq!(cert.unknowns().count(), 1);
        assert_eq!(cert.unknowns().next().unwrap().unknown().tag(),
                   packet::Tag::PublicSubkey);
        assert_eq!(cert.unknowns().next().unwrap().self_signatures().collect::<Vec<_>>(),
                   vec![&fake_binding]);

        Ok(())
    }

    #[test]
    fn canonicalize_with_v3_sig() -> Result<()> {
        if ! crate::types::PublicKeyAlgorithm::DSA.is_supported() {
            eprintln!("Skipping because DSA is not supported");
            return Ok(());
        }

        // This test relies on being able to validate SHA-1
        // signatures.  The standard policy rejects SHA-1.  So, use a
        // custom policy.
        let p = &P::new();
        let sha1 =
            p.hash_cutoff(
                HashAlgorithm::SHA1, HashAlgoSecurity::CollisionResistance)
            .unwrap();
        let p = &P::at(sha1 - std::time::Duration::from_secs(1));

        let cert = Cert::from_bytes(
            crate::tests::key("eike-v3-v4.pgp"))?;
        dbg!(&cert);
        assert_eq!(cert.userids()
                   .with_policy(p, None)
                   .count(), 1);
        Ok(())
    }

    /// Asserts that key expiration times on direct key signatures are
    /// honored.
    #[test]
    fn issue_215() {
        let p = &P::new();
         let cert = Cert::from_bytes(crate::tests::key(
            "issue-215-expiration-on-direct-key-sig.pgp")).unwrap();
        assert_match!(
            Error::Expired(_)
                = cert.with_policy(p, None).unwrap().alive()
                .unwrap_err().downcast().unwrap());
        assert_match!(
            Error::Expired(_)
                = cert.primary_key().with_policy(p, None).unwrap()
                    .alive().unwrap_err().downcast().unwrap());
    }

    /// Tests that secrets are kept when merging.
    #[test]
    fn merge_keeps_secrets() -> Result<()> {
        let (cert_s, _) =
            CertBuilder::general_purpose(None, Some("uid")).generate()?;
        let cert_p = cert_s.clone().strip_secret_key_material();

        // Merge key into cert.
        let cert = cert_p.clone().merge_public_and_secret(cert_s.clone())?;
        assert!(cert.keys().all(|ka| ka.has_secret()));

        // Merge cert into key.
        let cert = cert_s.clone().merge_public_and_secret(cert_p.clone())?;
        assert!(cert.keys().all(|ka| ka.has_secret()));

        Ok(())
    }

    /// Tests that secrets that are merged in are preferred to
    /// existing secrets.
    #[test]
    fn merge_prefers_merged_in_secrets() -> Result<()> {
        let pw: crate::crypto::Password = "foo".into();
        let (cert_encrypted_secrets, _) =
            CertBuilder::general_purpose(None, Some("uid"))
            .set_password(Some(pw.clone()))
            .generate()?;

        let mut cert_plain_secrets = cert_encrypted_secrets.clone();
        for ka in cert_encrypted_secrets.keys().secret() {
            assert!(! ka.has_unencrypted_secret());
            let key = ka.key().clone().decrypt_secret(&pw)?;
            assert!(key.has_unencrypted_secret());

            let key: Packet = if ka.primary() {
                key.role_into_primary().into()
            } else {
                key.role_into_subordinate().into()
            };

            cert_plain_secrets =
                cert_plain_secrets.insert_packets(vec![key])?;
        }
        assert!(
            cert_plain_secrets.keys().all(|ka| ka.has_unencrypted_secret()));

        // Merge unencrypted secrets into encrypted secrets.
        let cert = cert_encrypted_secrets.clone().merge_public_and_secret(
            cert_plain_secrets.clone())?;
        assert!(cert.keys().all(|ka| ka.has_unencrypted_secret()));

        // Merge encrypted secrets into unencrypted secrets.
        let cert = cert_plain_secrets.clone().merge_public_and_secret(
            cert_encrypted_secrets.clone())?;
        assert!(cert.keys().all(|ka| ka.has_secret()
                                && ! ka.has_unencrypted_secret()));

        Ok(())
    }

    /// Tests that secrets are kept when canonicalizing.
    #[test]
    fn canonicalizing_keeps_secrets() -> Result<()> {
        let primary: Key<_, key::PrimaryRole> =
            key::Key4::generate_ecc(true, Curve::Ed25519)?.into();
        let mut primary_pair = primary.clone().into_keypair()?;
        let cert = Cert::try_from(vec![primary.clone().into()])?;

        let subkey_sec: Key<_, key::SubordinateRole> =
            key::Key4::generate_ecc(false, Curve::Cv25519)?.into();
        let subkey_pub = subkey_sec.clone().take_secret().0;
        let builder = signature::SignatureBuilder::new(SignatureType::SubkeyBinding)
            .set_key_flags(KeyFlags::empty()
                           .set_transport_encryption())?;
        let binding = subkey_sec.bind(&mut primary_pair, &cert, builder)?;

        let cert = Cert::try_from(vec![
            primary.clone().into(),
            subkey_pub.clone().into(),
            binding.clone().into(),
            subkey_sec.clone().into(),
            binding.clone().into(),
        ])?;
        assert_eq!(cert.keys().subkeys().count(), 1);
        assert_eq!(cert.keys().unencrypted_secret().subkeys().count(), 1);

        let cert = Cert::try_from(vec![
            primary.clone().into(),
            subkey_sec.clone().into(),
            binding.clone().into(),
            subkey_pub.clone().into(),
            binding.clone().into(),
        ])?;
        assert_eq!(cert.keys().subkeys().count(), 1);
        assert_eq!(cert.keys().unencrypted_secret().subkeys().count(), 1);
        Ok(())
    }

    /// Demonstrates that subkeys are kept if a userid is later added
    /// without any keyflags.
    #[test]
    fn issue_361() -> Result<()> {
        let (cert, _) = CertBuilder::new()
            .add_transport_encryption_subkey()
            .generate()?;
        let p = &P::new();
        let cert_at = cert.with_policy(p,
                                       cert.primary_key().creation_time()
                                       + time::Duration::new(300, 0))
            .unwrap();
        assert_eq!(cert_at.userids().count(), 0);
        assert_eq!(cert_at.keys().count(), 2);

        let mut primary_pair = cert.primary_key().key().clone()
            .parts_into_secret()?.into_keypair()?;
        let uid: UserID = "foo@example.org".into();
        let sig = uid.bind(
            &mut primary_pair, &cert,
            signature::SignatureBuilder::new(SignatureType::PositiveCertification))?;
        let cert = cert.insert_packets(vec![
            Packet::from(uid),
            sig.into(),
        ])?;

        let cert_at = cert.with_policy(p,
                                       cert.primary_key().creation_time()
                                       + time::Duration::new(300, 0))
            .unwrap();
        assert_eq!(cert_at.userids().count(), 1);
        assert_eq!(cert_at.keys().count(), 2);
        Ok(())
    }

    /// Demonstrates that binding signatures are considered valid even
    /// if the primary key is not marked as certification-capable.
    #[test]
    fn issue_321() -> Result<()> {
        let cert = Cert::from_bytes(
            crate::tests::file("contrib/pep/pEpkey-netpgp.asc"))?;
        assert_eq!(cert.userids().count(), 1);
        assert_eq!(cert.keys().count(), 1);

        let mut p = P::new();
        p.accept_hash(HashAlgorithm::SHA1);
        let cert_at = cert.with_policy(&p, cert.primary_key().creation_time())
            .unwrap();
        assert_eq!(cert_at.userids().count(), 1);
        assert_eq!(cert_at.keys().count(), 1);
        Ok(())
    }

    #[test]
    fn policy_uri_some() -> Result<()> {
        use crate::packet::prelude::SignatureBuilder;
        use crate::policy::StandardPolicy;

        let p = &StandardPolicy::new();

        let (alice, _) = CertBuilder::new().add_userid("Alice").generate()?;

        let sig = SignatureBuilder::from(
            alice
            .with_policy(p, None)?
            .direct_key_signature().expect("Direct key signature")
            .clone()
        )
            .set_policy_uri("https://example.org/~alice/signing-policy.txt")?;
        assert_eq!(sig.policy_uri(), Some("https://example.org/~alice/signing-policy.txt".as_bytes()));
        Ok(())
    }

    #[test]
    fn policy_uri_none() -> Result<()> {
        use crate::packet::prelude::SignatureBuilder;
        use crate::policy::StandardPolicy;

        let p = &StandardPolicy::new();

        let (alice, _) = CertBuilder::new().add_userid("Alice").generate()?;

        let sig = SignatureBuilder::from(
            alice
            .with_policy(p, None)?
            .direct_key_signature().expect("Direct key signature")
            .clone()
        );
        assert_eq!(sig.policy_uri(), None);
        Ok(())
    }

    #[test]
    fn different_preferences() -> Result<()> {
        use crate::cert::Preferences;
        let p = &crate::policy::StandardPolicy::new();

        // This key returns different preferences depending on how you
        // address it.  (It has two user ids and the user ids have
        // different preference packets on their respective self
        // signatures.)

        let cert = Cert::from_bytes(
            crate::tests::key("different-preferences.asc"))?;
        assert_eq!(cert.userids().count(), 2);

        if let Some(userid) = cert.userids().next() {
            assert_eq!(userid.userid().value(),
                       &b"Alice Confusion <alice@example.com>"[..]);

            let userid = userid.with_policy(p, None).expect("valid");

            use crate::types::SymmetricAlgorithm::*;
            assert_eq!(userid.preferred_symmetric_algorithms(),
                       Some(&[ AES256, AES192, AES128, TripleDES ][..]));

            use crate::types::HashAlgorithm::*;
            assert_eq!(userid.preferred_hash_algorithms(),
                       Some(&[ SHA512, SHA384, SHA256, SHA224, SHA1 ][..]));

            use crate::types::CompressionAlgorithm::*;
            assert_eq!(userid.preferred_compression_algorithms(),
                       Some(&[ Zlib, BZip2, Zip ][..]));

            #[allow(deprecated)] {
                assert_eq!(userid.preferred_aead_algorithms(), None);
            }

            // assert_eq!(userid.key_server_preferences(),
            //            Some(KeyServerPreferences::new(&[])));

            assert_eq!(userid.features(),
                       Some(Features::new(&[]).set_seipdv1()));
        } else {
            panic!("two user ids");
        }

        if let Some(userid) = cert.userids().next() {
            assert_eq!(userid.userid().value(),
                       &b"Alice Confusion <alice@example.com>"[..]);

            let userid = userid.with_policy(p, None).expect("valid");

            use crate::types::SymmetricAlgorithm::*;
            assert_eq!(userid.preferred_symmetric_algorithms(),
                       Some(&[ AES256, AES192, AES128, TripleDES ][..]));

            use crate::types::HashAlgorithm::*;
            assert_eq!(userid.preferred_hash_algorithms(),
                       Some(&[ SHA512, SHA384, SHA256, SHA224, SHA1 ][..]));

            use crate::types::CompressionAlgorithm::*;
            assert_eq!(userid.preferred_compression_algorithms(),
                       Some(&[ Zlib, BZip2, Zip ][..]));

            #[allow(deprecated)] {
                assert_eq!(userid.preferred_aead_algorithms(), None);
            }

            assert_eq!(userid.key_server_preferences(),
                       Some(KeyServerPreferences::new(&[0x80])));

            assert_eq!(userid.features(),
                       Some(Features::new(&[]).set_seipdv1()));

            // Using the certificate should choose the primary user
            // id, which is this one (because it is lexicographically
            // earlier).
            let cert = cert.with_policy(p, None).expect("valid");
            assert_eq!(userid.preferred_symmetric_algorithms(),
                       cert.preferred_symmetric_algorithms());
            assert_eq!(userid.preferred_hash_algorithms(),
                       cert.preferred_hash_algorithms());
            assert_eq!(userid.preferred_compression_algorithms(),
                       cert.preferred_compression_algorithms());
            #[allow(deprecated)] {
                assert_eq!(userid.preferred_aead_algorithms(),
                           cert.preferred_aead_algorithms());
            }
            assert_eq!(userid.key_server_preferences(),
                       cert.key_server_preferences());
            assert_eq!(userid.features(),
                       cert.features());
        } else {
            panic!("two user ids");
        }

        if let Some(userid) = cert.userids().nth(1) {
            assert_eq!(userid.userid().value(),
                       &b"Alice Confusion <alice@example.net>"[..]);

            let userid = userid.with_policy(p, None).expect("valid");

            use crate::types::SymmetricAlgorithm::*;
            assert_eq!(userid.preferred_symmetric_algorithms(),
                       Some(&[ AES192, AES256, AES128, TripleDES ][..]));

            use crate::types::HashAlgorithm::*;
            assert_eq!(userid.preferred_hash_algorithms(),
                       Some(&[ SHA384, SHA512, SHA256, SHA224, SHA1 ][..]));

            use crate::types::CompressionAlgorithm::*;
            assert_eq!(userid.preferred_compression_algorithms(),
                       Some(&[ BZip2, Zlib, Zip ][..]));

            #[allow(deprecated)] {
                assert_eq!(userid.preferred_aead_algorithms(), None);
            }

            assert_eq!(userid.key_server_preferences(),
                       Some(KeyServerPreferences::new(&[0x80])));

            assert_eq!(userid.features(),
                       Some(Features::new(&[]).set_seipdv1()));
        } else {
            panic!("two user ids");
        }

        Ok(())
    }

    #[test]
    fn unsigned_components() -> Result<()> {
        // We have a certificate with an unsigned User ID, User
        // Attribute, encryption-capable subkey, and signing-capable
        // subkey.  (Actually, they are signed, but the signatures are
        // bad.)  We expect that when we parse such a certificate the
        // unsigned components are not dropped and they appear when
        // iterating over the components using, e.g., Cert::userids,
        // but not when we check for valid components.

        let p = &crate::policy::StandardPolicy::new();

        let cert = Cert::from_bytes(
            crate::tests::key("certificate-with-unsigned-components.asc"))?;

        assert_eq!(cert.userids().count(), 2);
        assert_eq!(cert.userids().with_policy(p, None).count(), 1);

        assert_eq!(cert.user_attributes().count(), 2);
        assert_eq!(cert.user_attributes().with_policy(p, None).count(), 1);

        assert_eq!(cert.keys().count(), 1 + 4);
        assert_eq!(cert.keys().with_policy(p, None).count(), 1 + 2);
        Ok(())
    }

    #[test]
    fn issue_504() -> Result<()> {
        let mut keyring = crate::tests::key("testy.pgp").to_vec();
        keyring.extend_from_slice(crate::tests::key("testy-new.pgp"));

        // TryFrom<PacketPile>
        let pp = PacketPile::from_bytes(&keyring)?;
        assert!(matches!(
            Cert::try_from(pp.clone()).unwrap_err().downcast().unwrap(),
            Error::MalformedCert(_)
        ));

        // Cert::TryFrom<Vec<Packet>>
        let v: Vec<Packet> = pp.into();
        assert!(matches!(
            Cert::try_from(v.clone()).unwrap_err().downcast().unwrap(),
            Error::MalformedCert(_)
        ));

        // Cert::from_packet
        assert!(matches!(
            Cert::from_packets(v.into_iter()).unwrap_err().downcast().unwrap(),
            Error::MalformedCert(_)
        ));

        // Cert::TryFrom<PacketParserResult>
        let ppr = PacketParser::from_bytes(&keyring)?;
        assert!(matches!(
            Cert::try_from(ppr).unwrap_err().downcast().unwrap(),
            Error::MalformedCert(_)
        ));
        Ok(())
    }

    /// Tests whether the policy is applied to primary key binding
    /// signatures.
    #[test]
    fn issue_531() -> Result<()> {
        let cert =
            Cert::from_bytes(crate::tests::key("peter-sha1-backsig.pgp"))?;
        let p = &crate::policy::NullPolicy::new();
        assert_eq!(cert.with_policy(p, None)?.keys().for_signing().count(), 1);
        let mut p = crate::policy::StandardPolicy::new();
        p.reject_hash(HashAlgorithm::SHA1);
        assert_eq!(cert.with_policy(&p, None)?.keys().for_signing().count(), 0);
        Ok(())
    }

    /// Tests whether expired primary key binding signatures are
    /// rejected.
    #[test]
    fn issue_539() -> Result<()> {
        let cert =
            Cert::from_bytes(crate::tests::key("peter-expired-backsig.pgp"))?;
        let p = &crate::policy::NullPolicy::new();
        assert_eq!(cert.with_policy(p, None)?.keys().for_signing().count(), 0);
        let p = &crate::policy::StandardPolicy::new();
        assert_eq!(cert.with_policy(p, None)?.keys().for_signing().count(), 0);
        Ok(())
    }

    /// Tests whether signatures are properly deduplicated.
    #[test]
    fn issue_568() -> Result<()> {
        use crate::packet::signature::subpacket::*;

        let (cert, _) = CertBuilder::general_purpose(
            None, Some("alice@example.org")).generate().unwrap();
        assert_eq!(cert.userids().count(), 1);
        assert_eq!(cert.subkeys().count(), 2);
        assert_eq!(cert.unknowns().count(), 0);
        assert_eq!(cert.bad_signatures().count(), 0);
        assert_eq!(cert.userids().next().unwrap().self_signatures().count(), 1);
        assert_eq!(cert.subkeys().next().unwrap().self_signatures().count(), 1);
        assert_eq!(cert.subkeys().nth(1).unwrap().self_signatures().count(), 1);

        // Create a variant of cert where the signatures have
        // additional information in the unhashed area.
        let cert_b = cert.clone();
        let mut packets = crate::PacketPile::from(cert_b).into_children()
            .collect::<Vec<_>>();
        for p in packets.iter_mut() {
            if let Packet::Signature(sig) = p {
                assert_eq!(sig.hashed_area().subpackets(
                    SubpacketTag::IssuerFingerprint).count(),
                           1);
                sig.unhashed_area_mut().add(Subpacket::new(
                    SubpacketValue::Issuer("AAAA BBBB CCCC DDDD".parse()?),
                    false)?)?;
            }
        }
        let cert_b = Cert::from_packets(packets.into_iter())?;
        let cert = cert.merge_public_and_secret(cert_b)?;
        assert_eq!(cert.userids().count(), 1);
        assert_eq!(cert.subkeys().count(), 2);
        assert_eq!(cert.unknowns().count(), 0);
        assert_eq!(cert.bad_signatures().count(), 0);
        assert_eq!(cert.userids().next().unwrap().self_signatures().count(), 1);
        assert_eq!(cert.subkeys().next().unwrap().self_signatures().count(), 1);
        assert_eq!(cert.subkeys().nth(1).unwrap().self_signatures().count(), 1);

        Ok(())
    }

    /// Checks that missing or bad embedded signatures cause the
    /// signature to be considered bad.
    #[test]
    fn missing_backsig_is_bad() -> Result<()> {
        use crate::packet::{
            key::Key4,
            signature::{
                SignatureBuilder,
                subpacket::{Subpacket, SubpacketValue},
            },
        };

        // We'll study this certificate, because it contains a
        // signing-capable subkey.
        let cert = crate::Cert::from_bytes(crate::tests::key(
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"))?;
        let mut pp = crate::PacketPile::from_bytes(crate::tests::key(
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"))?;
        assert_eq!(pp.children().count(), 5);

        if let Some(Packet::Signature(sig)) = pp.path_ref_mut(&[4]) {
            // Add a bogus but plausible embedded signature subpacket.
            let key: key::SecretKey
                = Key4::generate_ecc(true, Curve::Ed25519)?.into();
            let mut pair = key.into_keypair()?;

            sig.unhashed_area_mut().replace(Subpacket::new(
                SubpacketValue::EmbeddedSignature(
                    SignatureBuilder::new(SignatureType::PrimaryKeyBinding)
                        .sign_primary_key_binding(
                            &mut pair,
                            cert.primary_key().key(),
                            cert.keys().subkeys().next().unwrap().key())?),
                false)?)?;
        } else {
            panic!("expected a signature");
        }

        // Parse into cert.
        use std::convert::TryFrom;
        let malicious_cert = Cert::try_from(pp)?;
        // The subkey binding signature should no longer check out.
        let p = &crate::policy::StandardPolicy::new();
        assert_eq!(malicious_cert.with_policy(p, None)?.keys().subkeys()
                   .for_signing().count(), 0);
        // Instead, it should be considered bad.
        assert_eq!(malicious_cert.bad_signatures().count(), 1);
        Ok(())
    }

    /// Checks that multiple embedded signatures are correctly
    /// handled.
    #[test]
    fn multiple_embedded_signatures() -> Result<()> {
        use crate::packet::{
            key::Key4,
            signature::{
                SignatureBuilder,
                subpacket::{Subpacket, SubpacketValue},
            },
        };

        // We'll study this certificate, because it contains a
        // signing-capable subkey.
        let cert = crate::Cert::from_bytes(crate::tests::key(
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"))?;

        // Add a bogus but plausible embedded signature subpacket with
        // this key.
        let key: key::SecretKey
            = Key4::generate_ecc(true, Curve::Ed25519)?.into();
        let mut pair = key.into_keypair()?;

        // Create a malicious cert to merge in.
        let mut pp = crate::PacketPile::from_bytes(crate::tests::key(
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"))?;
        assert_eq!(pp.children().count(), 5);

        if let Some(Packet::Signature(sig)) = pp.path_ref_mut(&[4]) {
            // Prepend a bad backsig.
            let backsig = sig.embedded_signatures().next().unwrap().clone();
            sig.unhashed_area_mut().replace(Subpacket::new(
                SubpacketValue::EmbeddedSignature(
                    SignatureBuilder::new(SignatureType::PrimaryKeyBinding)
                        .sign_primary_key_binding(
                            &mut pair,
                            cert.primary_key().key(),
                            cert.keys().subkeys().next().unwrap().key())?),
                false)?)?;
            sig.unhashed_area_mut().add(Subpacket::new(
                SubpacketValue::EmbeddedSignature(backsig), false)?)?;
        } else {
            panic!("expected a signature");
        }

        // Parse into cert.
        use std::convert::TryFrom;
        let malicious_cert = Cert::try_from(pp)?;
        // The subkey binding signature should still be fine.
        let p = &crate::policy::StandardPolicy::new();
        assert_eq!(malicious_cert.with_policy(p, None)?.keys().subkeys()
                   .for_signing().count(), 1);
        assert_eq!(malicious_cert.bad_signatures().count(), 0);

        // Now try to merge it in.
        let merged = cert.clone().merge_public_and_secret(malicious_cert.clone())?;
        // The subkey binding signature should still be fine.
        assert_eq!(merged.with_policy(p, None)?.keys().subkeys()
                   .for_signing().count(), 1);
        let sig = merged.with_policy(p, None)?.keys().subkeys()
            .for_signing().next().unwrap().binding_signature();
        assert_eq!(sig.embedded_signatures().count(), 2);

        // Now the other way around.
        let merged = malicious_cert.clone().merge_public_and_secret(cert.clone())?;
        // The subkey binding signature should still be fine.
        assert_eq!(merged.with_policy(p, None)?.keys().subkeys()
                   .for_signing().count(), 1);
        let sig = merged.with_policy(p, None)?.keys().subkeys()
            .for_signing().next().unwrap().binding_signature();
        assert_eq!(sig.embedded_signatures().count(), 2);
        Ok(())
    }

    /// Checks that Cert::merge(cert, cert) == cert.
    #[test]
    fn issue_579() -> Result<()> {
        use std::convert::TryFrom;
        use crate::packet::signature::subpacket::SubpacketTag;

        let mut pp = crate::PacketPile::from_bytes(crate::tests::key(
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"))?;
        assert_eq!(pp.children().count(), 5);
        // Drop issuer information from the unhashed areas.
        if let Some(Packet::Signature(sig)) = pp.path_ref_mut(&[2]) {
            sig.unhashed_area_mut().remove_all(SubpacketTag::Issuer);
        } else {
            panic!("expected a signature");
        }
        if let Some(Packet::Signature(sig)) = pp.path_ref_mut(&[4]) {
            sig.unhashed_area_mut().remove_all(SubpacketTag::Issuer);
        } else {
            panic!("expected a signature");
        }

        let cert = Cert::try_from(pp)?;
        assert_eq!(cert.clone().merge_public_and_secret(cert.clone())?, cert);

        Ok(())
    }

    /// Checks that Cert::merge_public ignores secret key material.
    #[test]
    fn merge_public() -> Result<()> {
        let cert =
            Cert::from_bytes(crate::tests::key("testy-new.pgp"))?;
        let key =
            Cert::from_bytes(crate::tests::key("testy-new-private.pgp"))?;

        assert!(! cert.is_tsk());
        assert!(key.is_tsk());

        // Secrets are ignored in `other`.
        let merged = cert.clone().merge_public(key.clone())?;
        assert!(! merged.is_tsk());
        assert_eq!(merged, cert);

        // Secrets are retained in `self`.
        let merged = key.clone().merge_public(cert.clone())?;
        assert!(merged.is_tsk());
        assert_eq!(merged, key);

        Ok(())
    }

    /// Make sure we can parse a key where the primary key is its own
    /// subkeys.
    #[test]
    fn primary_key_is_subkey() -> Result<()> {
        let p = &crate::policy::StandardPolicy::new();

        let cert =
            Cert::from_bytes(crate::tests::key("primary-key-is-also-subkey.pgp"))?;

        // There should be three keys:
        //
        //     Fingerprint: 8E8C 33FA 4626 3379 76D9  7978 069C 0C34 8DD8 2C19
        // Public-key algo: EdDSA Edwards-curve Digital Signature Algorithm
        // Public-key size: 256 bits
        //      Secret key: Unencrypted
        //   Creation time: 2018-06-11 14:12:09 UTC
        //       Key flags: certification, signing
        //
        //          Subkey: 8E8C 33FA 4626 3379 76D9  7978 069C 0C34 8DD8 2C19
        // Public-key algo: EdDSA Edwards-curve Digital Signature Algorithm
        // Public-key size: 256 bits
        //      Secret key: Unencrypted
        //   Creation time: 2018-06-11 14:12:09 UTC
        //       Key flags: certification, signing
        //
        //          Subkey: 061C 3CA4 4AFF 0EC5 8DC6  6E95 22E3 FAFE 96B5 6C32
        // Public-key algo: EdDSA Edwards-curve Digital Signature Algorithm
        // Public-key size: 256 bits
        //      Secret key: Unencrypted
        //   Creation time: 2018-08-27 10:55:43 UTC
        //       Key flags: signing
        //
        //          UserID: Emmelie Dorothea Dina Samantha Awina Ed25519
        assert_eq!(cert.keys().count(), 3);

        // Make sure there is a subkey with the same fingerprint as
        // the primary key.
        assert!(cert.keys().subkeys().any(|k| {
            k.fingerprint() == cert.primary_key().fingerprint()
        }));

        // Make sure the self sig is valid, too.
        assert_eq!(cert.keys().count(), 3);

        let vc = cert.with_policy(p, None)?;
        assert!(vc.keys().subkeys().any(|k| {
            k.fingerprint() == vc.primary_key().fingerprint()
        }));

        Ok(())
    }

    /// Makes sure that attested key signatures are correctly handled.
    #[test]
    fn attested_key_signatures() -> Result<()> {
        use crate::{
            packet::signature::SignatureBuilder,
            types::*,
        };
        let p = &crate::policy::StandardPolicy::new();

        let (alice, _) = CertBuilder::new()
            .add_userid("alice@foo.com")
            .generate()?;
        let mut alice_signer =
            alice.primary_key().key().clone().parts_into_secret()?
            .into_keypair()?;

        let (bob, _) = CertBuilder::new()
            .add_userid("bob@bar.com")
            .generate()?;
        let mut bob_signer =
            bob.primary_key().key().clone().parts_into_secret()?
            .into_keypair()?;
        let bob_pristine = bob.clone();

        // Have Alice certify the binding between "bob@bar.com" and
        // Bob's key.
        let alice_certifies_bob
            = bob.userids().next().unwrap().userid().bind(
                &mut alice_signer, &bob,
                SignatureBuilder::new(SignatureType::GenericCertification))?;
        let bob = bob.insert_packets(vec![
            alice_certifies_bob.clone(),
        ])?;

        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .certifications().count(), 1);
        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 0);

        // Have Bob attest that certification.
        #[allow(deprecated)]
        let attestations =
            bob.userids().next().unwrap().attest_certifications(
                p,
                &mut bob_signer,
                vec![&alice_certifies_bob])?;
        assert_eq!(attestations.len(), 1);
        let attestation = attestations[0].clone();

        let bob = bob.insert_packets(vec![
            attestation.clone(),
        ])?;

        assert_eq!(bob.bad_signatures().count(), 0);
        assert_eq!(bob.userids().next().unwrap().certifications().next(),
                   Some(&alice_certifies_bob));
        assert_eq!(bob.userids().next().unwrap().bundle().attestations().next().unwrap(),
                   &attestation);
        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .certifications().count(), 1);
        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 1);

        // Check that attested key signatures are kept over merges.
        let bob_ = bob.clone().merge_public(bob_pristine.clone())?;
        assert_eq!(bob_.bad_signatures().count(), 0);
        assert_eq!(bob_.userids().next().unwrap().certifications().next(),
                   Some(&alice_certifies_bob));
        assert_eq!(bob_.userids().next().unwrap().bundle().attestations().next().unwrap(),
                   &attestation);
        assert_eq!(bob_.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 1);

        // And the other way around.
        let bob_ = bob_pristine.clone().merge_public(bob.clone())?;
        assert_eq!(bob_.bad_signatures().count(), 0);
        assert_eq!(bob_.userids().next().unwrap().certifications().next(),
                   Some(&alice_certifies_bob));
        assert_eq!(bob_.userids().next().unwrap().bundle().attestations().next().unwrap(),
                   &attestation);
        assert_eq!(bob_.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 1);

        // Have Bob withdraw any prior attestations.

        #[allow(deprecated)]
        let attestations =
            bob.userids().next().unwrap().attest_certifications(
                p,
                &mut bob_signer,
                &[])?;
        assert_eq!(attestations.len(), 1);
        let attestation = attestations[0].clone();

        let bob = bob.insert_packets(vec![
            attestation.clone(),
        ])?;

        assert_eq!(bob.bad_signatures().count(), 0);
        assert_eq!(bob.userids().next().unwrap().certifications().next(),
                   Some(&alice_certifies_bob));
        assert_eq!(bob.userids().next().unwrap().bundle().attestations().next().unwrap(),
                   &attestation);
        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .certifications().count(), 1);
        assert_eq!(bob.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 0);


        Ok(())
    }

    /// Makes sure that attested key signatures are correctly handled.
    #[test]
    fn attested_key_signatures_dkgpg() -> Result<()> {
        const DUMP: bool = false;
        use crate::{
            crypto::hash::Digest,
        };
        let p = &crate::policy::StandardPolicy::new();

        let test = Cert::from_bytes(crate::tests::key("1pa3pc-dkgpg.pgp"))?;
        assert_eq!(test.bad_signatures().count(), 0);
        assert_eq!(test.userids().next().unwrap().certifications().count(),
                   1);
        assert_eq!(test.userids().next().unwrap().bundle().attestations().count(),
                   1);

        let attestation =
            test.userids().next().unwrap().bundle().attestations().next().unwrap();

        if DUMP {
            for (i, d) in attestation.attested_certifications()?.enumerate() {
                crate::fmt::hex::Dumper::new(std::io::stderr(), "")
                    .write(d, format!("expected digest {}", i))?;
            }
        }

        let digests: std::collections::HashSet<_> =
            attestation.attested_certifications()?.collect();

        for (i, certification) in
            test.userids().next().unwrap().certifications().enumerate()
        {
            // Hash the certification.
            let mut h = attestation.hash_algo().context()?;
            certification.hash_for_confirmation(&mut h);
            let digest = h.into_digest()?;

            if DUMP {
                crate::fmt::hex::Dumper::new(std::io::stderr(), "")
                    .write(&digest, format!("computed digest {}", i))?;
            }

            assert!(digests.contains(&digest[..]));
        }

        assert_eq!(test.with_policy(p, None)?.userids().next().unwrap()
                   .certifications().count(), 1);
        assert_eq!(test.with_policy(p, None)?.userids().next().unwrap()
                   .attested_certifications().count(), 1);

        Ok(())
    }

    /// Makes sure that attested key signatures are correctly reordered.
    #[test]
    fn attested_key_signature_out_of_order() -> Result<()> {
        let p = &crate::policy::StandardPolicy::new();

        let (alice, _) = CertBuilder::general_purpose(
            None, Some("alice@example.org")).generate().unwrap();
        assert!(alice.keys().subkeys().count() > 0);
        let mut alice_signer =
            alice.primary_key().key().clone().parts_into_secret()?
            .into_keypair()?;

        // Now, create new attestation signatures.
        let mut attestation_signatures = Vec::new();
        for uid in alice.userids() {
            #[allow(deprecated)]
            attestation_signatures.append(&mut uid.attest_certifications(
                p,
                &mut alice_signer,
                uid.certifications(),
            )?);
        }

        // Add the new signatures.  This appends the attestation
        // signature so that it is considered part of last component,
        // a subkey.
        let alice2 = alice.insert_packets(attestation_signatures)?;

        // Now we make sure the attestation signature was correctly reordered.
        assert_eq!(alice2.bad_signatures().count(), 0);
        assert!(alice2.keys().all(|ka| ka.attestations().count() == 0));
        let ua = alice2.userids().next().unwrap();
        assert_eq!(ua.attestations().count(), 1);

        Ok(())
    }

    /// Makes sure that marker packets are ignored when parsing certs.
    #[test]
    fn marker_packets() -> Result<()> {
        let cert = Cert::from_bytes(crate::tests::key("neal.pgp"))?;
        let mut buf = Vec::new();
        Packet::Marker(Default::default()).serialize(&mut buf)?;
        cert.serialize(&mut buf)?;

        let cert_ = Cert::from_bytes(&buf)?;
        assert_eq!(cert, cert_);
        Ok(())
    }

    /// Checks that messing with a revocation signature merely
    /// invalidates the signature and keeps the cert's revocation
    /// status unchanged.
    #[test]
    fn issue_486() -> Result<()> {
        use crate::{
            crypto::mpi,
            types::RevocationStatus::*,
            packet::signature::Signature4,
            policy::StandardPolicy,
        };
        let p = &StandardPolicy::new();

        let (cert, revocation) = CertBuilder::new().generate()?;

        // Base case.
        let c = cert.clone().insert_packets(Some(revocation.clone()))?;
        if let Revoked(_) = c.revocation_status(p, None) {
            // cert is considered revoked
        } else {
            panic!("Should be revoked, but is not: {:?}",
                   c.revocation_status(p, None));
        }

        // Breaking the revocation signature by changing the MPIs.
        let c = cert.clone().insert_packets(Some(
            Signature4::new(
                revocation.typ(),
                revocation.pk_algo(),
                revocation.hash_algo(),
                revocation.hashed_area().clone(),
                revocation.unhashed_area().clone(),
                *revocation.digest_prefix(),
                // MPI is replaced with a dummy one
                mpi::Signature::RSA {
                    s: mpi::MPI::from(vec![1, 2, 3])
                })))?;
        if let NotAsFarAsWeKnow = c.revocation_status(p, None) {
            assert_eq!(c.bad_signatures().count(), 1);
        } else {
            panic!("Should not be revoked, but is: {:?}",
                   c.revocation_status(p, None));
        }

        // Breaking the revocation signature by changing the MPIs and
        // the digest prefix.
        let c = cert.clone().insert_packets(Some(
            Signature4::new(
                revocation.typ(),
                revocation.pk_algo(),
                revocation.hash_algo(),
                revocation.hashed_area().clone(),
                revocation.unhashed_area().clone(),
                // Prefix replaced with a dummy one
                [0, 1],
                // MPI is replaced with a dummy one
                mpi::Signature::RSA {
                    s: mpi::MPI::from(vec![1, 2, 3])
                })))?;
        if let NotAsFarAsWeKnow = c.revocation_status(p, None) {
            assert_eq!(c.bad_signatures().count(), 1);
        } else {
            panic!("Should not be revoked, but is: {:?}",
                   c.revocation_status(p, None));
        }

        Ok(())
    }

    /// Tests v3 binding signatures.
    #[test]
    fn v3_binding_signature() -> Result<()> {
        if ! crate::types::PublicKeyAlgorithm::DSA.is_supported() {
            eprintln!("Skipping because DSA is not supported");
            return Ok(());
        }

        let c = Cert::from_bytes(
            crate::tests::key("pgp5-dsa-elg-v3-subkey-binding.pgp"))?;
        assert_eq!(c.bad_signatures().count(), 0);

        let np = crate::policy::NullPolicy::new();

        // The subkey is interesting because it is bound using a v3
        // signature.
        let vcert = c.with_policy(&np, None)?;
        assert_eq!(vcert.keys().subkeys().count(), 1);

        // A v3 signature has no subpackets, so there are no key
        // flags.  But, we then consider the key role and public key
        // algorithm.
        assert_eq!(vcert.keys().for_signing().count(), 1);
        assert_eq!(vcert.keys().for_transport_encryption().count(), 1);

        // The subkey is interesting because it is bound using a v3
        // signature.
        assert_eq!(c.keys().subkeys().with_policy(&np, None).count(), 1);

        // A v3 signature has no subpackets, so there are no key
        // flags.  But, we then consider the key role and public key
        // algorithm.
        assert_eq!(c.keys().with_policy(&np, None).for_signing().count(), 1);
        assert_eq!(c.keys().with_policy(&np, None)
                   .for_transport_encryption().count(), 1);

        Ok(())
    }

    /// Tests v3 revocation signatures.
    #[test]
    fn v3_revocation_signature() -> Result<()> {
        if ! crate::types::PublicKeyAlgorithm::ECDSA.is_supported()
            || ! crate::types::Curve::NistP521.is_supported()
        {
            eprintln!("Skipping because ECDSA/NistP521 is not supported");
            return Ok(());
        }

        let c = Cert::from_bytes(
            crate::tests::key("v4-revoked-by-v3.pgp"))?;
        assert_eq!(c.bad_signatures().count(), 0);

        let sp = crate::policy::StandardPolicy::new();
        assert!(matches!(c.revocation_status(&sp, None),
                         RevocationStatus::Revoked(_)));

        Ok(())
    }
}