logo
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
//! Streaming packet serialization.
//!
//! This interface provides a convenient way to create signed and/or
//! encrypted OpenPGP messages (see [Section 11.3 of RFC 4880]) and is
//! the preferred interface to generate messages using Sequoia.  It
//! takes advantage of OpenPGP's streaming nature to avoid unnecessary
//! buffering.
//!
//!   [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
//!
//! To use this interface, a sink implementing [`io::Write`] is
//! wrapped by [`Message::new`] returning a streaming [`Message`].
//! The writer stack is a structure to compose filters that create the
//! desired message structure.  There are a number of filters that can
//! be freely combined:
//!
//!   - [`Armorer`] applies ASCII-Armor to the stream,
//!   - [`Encryptor`] encrypts data fed into it,
//!   - [`Compressor`] compresses data,
//!   - [`Padder`] pads data,
//!   - [`Signer`] signs data,
//!   - [`LiteralWriter`] wraps literal data (i.e. the payload) into
//!     a literal data packet,
//!   - and finally, [`ArbitraryWriter`] can be used to create
//!     arbitrary packets for testing purposes.
//!
//!   [`io::Write`]: std::io::Write
//!   [`Message::new`]: Message::new()
//!   [`Padder`]: padding::Padder
//!
//! The most common structure is an optionally encrypted, optionally
//! compressed, and optionally signed message.  This structure is
//! [supported] by all OpenPGP implementations, and applications
//! should only create messages of that structure to increase
//! compatibility.  See the example below on how to create this
//! structure.  This is a sketch of such a message:
//!
//! ```text
//! [ encryption layer: [ compression layer: [ signature group: [ literal data ]]]]
//! ```
//!
//!   [supported]: https://tests.sequoia-pgp.org/#Unusual_Message_Structure
//!
//! # Examples
//!
//! This example demonstrates how to create the simplest possible
//! OpenPGP message (see [Section 11.3 of RFC 4880]) containing just a
//! literal data packet (see [Section 5.9 of RFC 4880]):
//!
//!   [Section 5.9 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.9
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! use std::io::Write;
//! use sequoia_openpgp as openpgp;
//! use openpgp::serialize::stream::{Message, LiteralWriter};
//!
//! let mut sink = vec![];
//! {
//!     let message = Message::new(&mut sink);
//!     let mut message = LiteralWriter::new(message).build()?;
//!     message.write_all(b"Hello world.")?;
//!     message.finalize()?;
//! }
//! assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.", sink.as_slice());
//! # Ok(()) }
//! ```
//!
//! This example demonstrates how to create the most common OpenPGP
//! message structure (see [Section 11.3 of RFC 4880]).  The plaintext
//! is first signed, then encrypted, and finally ASCII armored.
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! use std::io::Write;
//! use sequoia_openpgp as openpgp;
//! use openpgp::policy::StandardPolicy;
//! use openpgp::cert::prelude::*;
//! use openpgp::serialize::stream::{
//!     Message, Armorer, Encryptor, Signer, LiteralWriter,
//! };
//! # use openpgp::parse::Parse;
//!
//! let p = &StandardPolicy::new();
//!
//! let sender: Cert = // ...
//! #     Cert::from_bytes(&include_bytes!(
//! #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
//! let signing_keypair = sender.keys().secret()
//!     .with_policy(p, None).supported().alive().revoked(false).for_signing()
//!     .nth(0).unwrap()
//!     .key().clone().into_keypair()?;
//!
//! let recipient: Cert = // ...
//! #     sender.clone();
//! // Note: One certificate may contain several suitable encryption keys.
//! let recipients =
//!     recipient.keys().with_policy(p, None).supported().alive().revoked(false)
//!     // Or `for_storage_encryption()`, for data at rest.
//!     .for_transport_encryption();
//!
//! # let mut sink = vec![];
//! let message = Message::new(&mut sink);
//! let message = Armorer::new(message).build()?;
//! let message = Encryptor::for_recipients(message, recipients).build()?;
//! // Reduce metadata leakage by concealing the message size.
//! let message = Signer::new(message, signing_keypair)
//!     // Prevent Surreptitious Forwarding.
//!     .add_intended_recipient(&recipient)
//!     .build()?;
//! let mut message = LiteralWriter::new(message).build()?;
//! message.write_all(b"Hello world.")?;
//! message.finalize()?;
//! # Ok(()) }
//! ```

use std::fmt;
use std::io::{self, Write};
use std::time::SystemTime;

use crate::{
    armor,
    crypto,
    Error,
    Fingerprint,
    HashAlgorithm,
    KeyID,
    Result,
    crypto::Password,
    crypto::SessionKey,
    packet::prelude::*,
    packet::signature,
    packet::key,
    cert::prelude::*,
};
use crate::packet::header::CTB;
use crate::packet::header::BodyLength;
use crate::parse::HashingMode;
use super::{
    Marshal,
};
use crate::types::{
    AEADAlgorithm,
    CompressionAlgorithm,
    CompressionLevel,
    DataFormat,
    SignatureType,
    SymmetricAlgorithm,
};

pub(crate) mod writer;
#[cfg(feature = "compression-deflate")]
pub mod padding;
mod partial_body;
use partial_body::PartialBodyFilter;
mod dash_escape;
use dash_escape::DashEscapeFilter;
mod trim_whitespace;
use trim_whitespace::TrailingWSFilter;


/// Cookie must be public because the writers are.
#[derive(Debug)]
struct Cookie {
    level: usize,
    private: Private,
}

#[derive(Debug)]
enum Private {
    Nothing,
    Signer,
}

impl Cookie {
    fn new(level: usize) -> Self {
        Cookie {
            level,
            private: Private::Nothing,
        }
    }
}

impl Default for Cookie {
    fn default() -> Self {
        Cookie::new(0)
    }
}

/// Streams an OpenPGP message.
///
/// Wraps an [`io::Write`]r for use with the streaming subsystem.  The
/// `Message` is a stack of filters that create the desired message
/// structure.  Literal data must be framed using the
/// [`LiteralWriter`] filter.  Once all the has been written, the
/// `Message` must be finalized using [`Message::finalize`].
///
///   [`io::Write`]: std::io::Write
///   [`Message::finalize`]: Message::finalize()
#[derive(Debug)]
pub struct Message<'a>(writer::BoxStack<'a, Cookie>);
assert_send_and_sync!(Message<'_>);

impl<'a> Message<'a> {
    /// Starts streaming an OpenPGP message.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// # let mut sink = vec![]; // Vec<u8> implements io::Write.
    /// let message = Message::new(&mut sink);
    /// // Construct the writer stack here.
    /// let mut message = LiteralWriter::new(message).build()?;
    /// // Write literal data to `message` here.
    /// // ...
    /// // Finalize the message.
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn new<W: 'a + io::Write + Send + Sync>(w: W) -> Message<'a> {
        writer::Generic::new(w, Cookie::new(0))
    }

    /// Finalizes the topmost writer, returning the underlying writer.
    ///
    /// Finalizes the topmost writer, i.e. flushes any buffered data,
    /// and pops it of the stack.  This allows for fine-grained
    /// control of the resulting message, but must be done with great
    /// care.  If done improperly, the resulting message may be
    /// malformed.
    ///
    /// # Examples
    ///
    /// This demonstrates how to create a compressed, signed message
    /// from a detached signature.
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use std::convert::TryFrom;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::packet::{Packet, Signature, one_pass_sig::OnePassSig3};
    /// # use openpgp::parse::Parse;
    /// use openpgp::serialize::Serialize;
    /// use openpgp::serialize::stream::{Message, Compressor, LiteralWriter};
    ///
    /// let data: &[u8] = // ...
    /// # &include_bytes!(
    /// # "../../tests/data/messages/a-cypherpunks-manifesto.txt")[..];
    /// let sig: Signature = // ...
    /// # if let Packet::Signature(s) = Packet::from_bytes(&include_bytes!(
    /// # "../../tests/data/messages/a-cypherpunks-manifesto.txt.ed25519.sig")[..])?
    /// # { s } else { panic!() };
    ///
    /// # let mut sink = vec![]; // Vec<u8> implements io::Write.
    /// let message = Message::new(&mut sink);
    /// let mut message = Compressor::new(message).build()?;
    ///
    /// // First, write a one-pass-signature packet.
    /// Packet::from(OnePassSig3::try_from(&sig)?)
    ///     .serialize(&mut message)?;
    ///
    /// // Then, add the literal data.
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(data)?;
    ///
    /// // Finally, pop the `LiteralWriter` off the stack to write the
    /// // signature.
    /// let mut message = message.finalize_one()?.unwrap();
    /// Packet::from(sig).serialize(&mut message)?;
    ///
    /// // Finalize the message.
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn finalize_one(self) -> Result<Option<Message<'a>>> {
        Ok(self.0.into_inner()?.map(|bs| Self::from(bs)))
    }

    /// Finalizes the message.
    ///
    /// Finalizes all writers on the stack, flushing any buffered
    /// data.
    ///
    /// # Note
    ///
    /// Failing to finalize the message may result in corrupted
    /// messages.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// # let mut sink = vec![]; // Vec<u8> implements io::Write.
    /// let message = Message::new(&mut sink);
    /// // Construct the writer stack here.
    /// let mut message = LiteralWriter::new(message).build()?;
    /// // Write literal data to `message` here.
    /// // ...
    /// // Finalize the message.
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn finalize(self) -> Result<()> {
        let mut stack = self;
        while let Some(s) = stack.finalize_one()? {
            stack = s;
        }
        Ok(())
    }
}

impl<'a> From<&'a mut (dyn io::Write + Send + Sync)> for Message<'a> {
    fn from(w: &'a mut (dyn io::Write + Send + Sync)) -> Self {
        writer::Generic::new(w, Cookie::new(0))
    }
}


/// Applies ASCII Armor to the message.
///
/// ASCII armored data (see [Section 6 of RFC 4880]) is a OpenPGP data
/// stream that has been base64-encoded and decorated with a header,
/// footer, and optional headers representing key-value pairs.  It can
/// be safely transmitted over protocols that can only transmit
/// printable characters, and can handled by end users (e.g. copied
/// and pasted).
///
///   [Section 6 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-6
pub struct Armorer<'a> {
    kind: armor::Kind,
    headers: Vec<(String, String)>,
    inner: Message<'a>,
}
assert_send_and_sync!(Armorer<'_>);

impl<'a> Armorer<'a> {
    /// Creates a new armoring filter.
    ///
    /// By default, the type of the armored data is set to
    /// [`armor::Kind`]`::Message`.  To change it, use
    /// [`Armorer::kind`].  To add headers to the armor, use
    /// [`Armorer::add_header`].
    ///
    ///   [`armor::Kind`]: crate::armor::Kind
    ///   [`Armorer::kind`]: Armorer::kind()
    ///   [`Armorer::add_header`]: Armorer::add_header()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Armorer, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let message = Armorer::new(message)
    ///         // Customize the `Armorer` here.
    ///         .build()?;
    ///     let mut message = LiteralWriter::new(message).build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!("-----BEGIN PGP MESSAGE-----\n\
    ///             \n\
    ///             yxJiAAAAAABIZWxsbyB3b3JsZC4=\n\
    ///             =6nHv\n\
    ///             -----END PGP MESSAGE-----\n",
    ///            std::str::from_utf8(&sink)?);
    /// # Ok(()) }
    pub fn new(inner: Message<'a>) -> Self {
        Self {
            kind: armor::Kind::Message,
            headers: Vec::with_capacity(0),
            inner,
        }
    }

    /// Changes the kind of armoring.
    ///
    /// The armor header and footer changes depending on the type of
    /// wrapped data.  See [`armor::Kind`] for the possible values.
    ///
    ///   [`armor::Kind`]: crate::armor::Kind
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::armor;
    /// use openpgp::serialize::stream::{Message, Armorer, Signer};
    /// # use sequoia_openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::crypto::KeyPair;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    /// # let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair
    /// #     = cert.keys().secret()
    /// #           .with_policy(p, None).alive().revoked(false).for_signing()
    /// #           .nth(0).unwrap()
    /// #           .key().clone().into_keypair()?;
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let message = Armorer::new(message)
    ///         .kind(armor::Kind::Signature)
    ///         .build()?;
    ///     let mut signer = Signer::new(message, signing_keypair)
    ///         .detached()
    ///         .build()?;
    ///
    ///     // Write the data directly to the `Signer`.
    ///     signer.write_all(b"Make it so, number one!")?;
    ///     // In reality, just io::copy() the file to be signed.
    ///     signer.finalize()?;
    /// }
    ///
    /// assert!(std::str::from_utf8(&sink)?
    ///         .starts_with("-----BEGIN PGP SIGNATURE-----\n"));
    /// # Ok(()) }
    pub fn kind(mut self, kind: armor::Kind) -> Self {
        self.kind = kind;
        self
    }

    /// Adds a header to the armor block.
    ///
    /// There are a number of defined armor header keys (see [Section
    /// 6 of RFC 4880]), but in practice, any key may be used, as
    /// implementations should simply ignore unknown keys.
    ///
    ///   [Section 6 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-6
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Armorer, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let message = Armorer::new(message)
    ///         .add_header("Comment", "No comment.")
    ///         .build()?;
    ///     let mut message = LiteralWriter::new(message).build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!("-----BEGIN PGP MESSAGE-----\n\
    ///             Comment: No comment.\n\
    ///             \n\
    ///             yxJiAAAAAABIZWxsbyB3b3JsZC4=\n\
    ///             =6nHv\n\
    ///             -----END PGP MESSAGE-----\n",
    ///            std::str::from_utf8(&sink)?);
    /// # Ok(()) }
    pub fn add_header<K, V>(mut self, key: K, value: V) -> Self
        where K: AsRef<str>,
              V: AsRef<str>,
    {
        self.headers.push((key.as_ref().to_string(),
                           value.as_ref().to_string()));
        self
    }

    /// Builds the armor writer, returning the writer stack.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Armorer, LiteralWriter};
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Armorer::new(message)
    ///     // Customize the `Armorer` here.
    ///     .build()?;
    /// # Ok(()) }
    pub fn build(self) -> Result<Message<'a>> {
        let level = self.inner.as_ref().cookie_ref().level;
        writer::Armorer::new(
            self.inner,
            Cookie::new(level + 1),
            self.kind,
            self.headers,
        )
    }
}

impl<'a> fmt::Debug for Armorer<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Armorer")
            .field("inner", &self.inner)
            .field("kind", &self.kind)
            .field("headers", &self.headers)
            .finish()
    }
}


/// Writes an arbitrary packet.
///
/// This writer can be used to construct arbitrary OpenPGP packets.
/// This is mainly useful for testing.  The body will be written using
/// partial length encoding, or, if the body is short, using full
/// length encoding.
pub struct ArbitraryWriter<'a> {
    inner: writer::BoxStack<'a, Cookie>,
}
assert_send_and_sync!(ArbitraryWriter<'_>);

#[allow(clippy::new_ret_no_self)]
impl<'a> ArbitraryWriter<'a> {
    /// Creates a new writer with the given tag.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::packet::Tag;
    /// use openpgp::serialize::stream::{Message, ArbitraryWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = ArbitraryWriter::new(message, Tag::Literal)?;
    ///     message.write_all(b"t")?;                   // type
    ///     message.write_all(b"\x00")?;                // filename length
    ///     message.write_all(b"\x00\x00\x00\x00")?;    // date
    ///     message.write_all(b"Hello world.")?;        // body
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x12t\x00\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    pub fn new(mut inner: Message<'a>, tag: Tag)
               -> Result<Message<'a>> {
        let level = inner.as_ref().cookie_ref().level + 1;
        CTB::new(tag).serialize(&mut inner)?;
        Ok(Message::from(Box::new(ArbitraryWriter {
            inner: PartialBodyFilter::new(inner, Cookie::new(level)).into()
        })))
    }
}

impl<'a> fmt::Debug for ArbitraryWriter<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ArbitraryWriter")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<'a> Write for ArbitraryWriter<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl<'a> writer::Stackable<'a, Cookie> for ArbitraryWriter<'a> {
    fn into_inner(self: Box<Self>) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        Box::new(self.inner).into_inner()
    }
    fn pop(&mut self) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        unreachable!("Only implemented by Signer")
    }
    /// Sets the inner stackable.
    fn mount(&mut self, _new: writer::BoxStack<'a, Cookie>) {
        unreachable!("Only implemented by Signer")
    }
    fn inner_ref(&self) -> Option<&(dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_ref())
    }
    fn inner_mut(&mut self) -> Option<&mut (dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_mut())
    }
    fn cookie_set(&mut self, cookie: Cookie) -> Cookie {
        self.inner.cookie_set(cookie)
    }
    fn cookie_ref(&self) -> &Cookie {
        self.inner.cookie_ref()
    }
    fn cookie_mut(&mut self) -> &mut Cookie {
        self.inner.cookie_mut()
    }
    fn position(&self) -> u64 {
        self.inner.position()
    }
}

/// Signs a message.
///
/// Signs a message with every [`crypto::Signer`] added to the
/// streaming signer.
///
///   [`crypto::Signer`]: super::super::crypto::Signer
pub struct Signer<'a> {
    // The underlying writer.
    //
    // Because this writer implements `Drop`, we cannot move the inner
    // writer out of this writer.  We therefore wrap it with `Option`
    // so that we can `take()` it.
    //
    // Furthermore, the LiteralWriter will pop us off the stack, and
    // take our inner reader.  If that happens, we only update the
    // digests.
    inner: Option<writer::BoxStack<'a, Cookie>>,
    signers: Vec<Box<dyn crypto::Signer + Send + Sync + 'a>>,
    intended_recipients: Vec<Fingerprint>,
    mode: SignatureMode,
    template: signature::SignatureBuilder,
    creation_time: Option<SystemTime>,
    hash: HashingMode<Box<dyn crypto::hash::Digest>>,
    cookie: Cookie,
    position: u64,
}
assert_send_and_sync!(Signer<'_>);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SignatureMode {
    Inline,
    Detached,
    Cleartext,
}

impl<'a> Signer<'a> {
    /// Creates a signer.
    ///
    /// Signs the message with the given [`crypto::Signer`].  To
    /// create more than one signature, add more [`crypto::Signer`]s
    /// using [`Signer::add_signer`].  Properties of the signatures
    /// can be tweaked using the methods of this type.  Notably, to
    /// generate a detached signature (see [Section 11.4 of RFC
    /// 4880]), use [`Signer::detached`].  For even more control over
    /// the generated signatures, use [`Signer::with_template`].
    ///
    ///   [`crypto::Signer`]: super::super::crypto::Signer
    ///   [`Signer::add_signer`]: Signer::add_signer()
    ///   [Section 11.4 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.4
    ///   [`Signer::detached`]: Signer::detached()
    ///   [`Signer::with_template`]: Signer::with_template()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::{Read, Write};
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// let p = &StandardPolicy::new();
    /// let cert: Cert = // ...
    /// #     Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// let signing_keypair = cert.keys().secret()
    ///     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    ///     .nth(0).unwrap()
    ///     .key().clone().into_keypair()?;
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let message = Signer::new(message, signing_keypair)
    ///         // Customize the `Signer` here.
    ///         .build()?;
    ///     let mut message = LiteralWriter::new(message).build()?;
    ///     message.write_all(b"Make it so, number one!")?;
    ///     message.finalize()?;
    /// }
    ///
    /// // Now check the signature.
    /// struct Helper<'a>(&'a openpgp::Cert);
    /// impl<'a> VerificationHelper for Helper<'a> {
    ///     fn get_certs(&mut self, _: &[openpgp::KeyHandle])
    ///                        -> openpgp::Result<Vec<openpgp::Cert>> {
    ///         Ok(vec![self.0.clone()])
    ///     }
    ///
    ///     fn check(&mut self, structure: MessageStructure)
    ///              -> openpgp::Result<()> {
    ///         if let MessageLayer::SignatureGroup { ref results } =
    ///             structure.iter().nth(0).unwrap()
    ///         {
    ///             results.get(0).unwrap().as_ref().unwrap();
    ///             Ok(())
    ///         } else { panic!() }
    ///     }
    /// }
    ///
    /// let mut verifier = VerifierBuilder::from_bytes(&sink)?
    ///     .with_policy(p, None, Helper(&cert))?;
    ///
    /// let mut message = String::new();
    /// verifier.read_to_string(&mut message)?;
    /// assert_eq!(&message, "Make it so, number one!");
    /// # Ok(()) }
    /// ```
    pub fn new<S>(inner: Message<'a>, signer: S) -> Self
        where S: crypto::Signer + Send + Sync + 'a
    {
        Self::with_template(inner, signer,
                            signature::SignatureBuilder::new(SignatureType::Binary))
    }

    /// Creates a signer with a given signature template.
    ///
    /// Signs the message with the given [`crypto::Signer`] like
    /// [`Signer::new`], but allows more control over the generated
    /// signatures.  The given [`signature::SignatureBuilder`] is used to
    /// create all the signatures.
    ///
    /// For every signature, the creation time is set to the current
    /// time or the one specified using [`Signer::creation_time`], the
    /// intended recipients are added (see
    /// [`Signer::add_intended_recipient`]), the issuer and issuer
    /// fingerprint subpackets are set according to the signing key,
    /// and the hash algorithm set using [`Signer::hash_algo`] is used
    /// to create the signature.
    ///
    ///   [`crypto::Signer`]: super::super::crypto::Signer
    ///   [`Signer::new`]: Message::new()
    ///   [`signature::SignatureBuilder`]: crate::packet::signature::SignatureBuilder
    ///   [`Signer::creation_time`]: Signer::creation_time()
    ///   [`Signer::hash_algo`]: Signer::hash_algo()
    ///   [`Signer::add_intended_recipient`]: Signer::add_intended_recipient()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::{Read, Write};
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::SignatureType;
    /// use openpgp::packet::signature;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// # use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    /// #
    /// # let p = &StandardPolicy::new();
    /// # let cert: Cert = // ...
    /// #     Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair = cert.keys().secret()
    /// #     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #     .nth(0).unwrap()
    /// #     .key().clone().into_keypair()?;
    /// # let mut sink = vec![];
    ///
    /// let message = Message::new(&mut sink);
    /// let message = Signer::with_template(
    ///     message, signing_keypair,
    ///     signature::SignatureBuilder::new(SignatureType::Text)
    ///         .add_notation("issuer@starfleet.command", "Jean-Luc Picard",
    ///                       None, true)?)
    ///     // Further customize the `Signer` here.
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Make it so, number one!")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn with_template<S, T>(inner: Message<'a>, signer: S, template: T)
                               -> Self
        where S: crypto::Signer + Send + Sync + 'a,
              T: Into<signature::SignatureBuilder>,
    {
        let inner = writer::BoxStack::from(inner);
        let level = inner.cookie_ref().level + 1;
        Signer {
            inner: Some(inner),
            signers: vec![Box::new(signer)],
            intended_recipients: Vec::new(),
            mode: SignatureMode::Inline,
            template: template.into(),
            creation_time: None,
            hash: HashingMode::Binary(
                HashAlgorithm::default().context().unwrap()),
            cookie: Cookie {
                level,
                private: Private::Signer,
            },
            position: 0,
        }
    }

    /// Creates a signer for a detached signature.
    ///
    /// Changes the `Signer` to create a detached signature (see
    /// [Section 11.4 of RFC 4880]).  Note that the literal data *must
    /// not* be wrapped using the [`LiteralWriter`].
    ///
    /// This overrides any prior call to [`Signer::cleartext`].
    ///
    ///   [Section 11.4 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.4
    ///   [`Signer::cleartext`]: Signer::cleartext()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Signer};
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::crypto::KeyPair;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair
    /// #     = cert.keys().secret()
    /// #           .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #           .nth(0).unwrap()
    /// #           .key().clone().into_keypair()?;
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut signer = Signer::new(message, signing_keypair)
    ///         .detached()
    ///         // Customize the `Signer` here.
    ///         .build()?;
    ///
    ///     // Write the data directly to the `Signer`.
    ///     signer.write_all(b"Make it so, number one!")?;
    ///     // In reality, just io::copy() the file to be signed.
    ///     signer.finalize()?;
    /// }
    ///
    /// // Now check the signature.
    /// struct Helper<'a>(&'a openpgp::Cert);
    /// impl<'a> VerificationHelper for Helper<'a> {
    ///     fn get_certs(&mut self, _: &[openpgp::KeyHandle])
    ///                        -> openpgp::Result<Vec<openpgp::Cert>> {
    ///         Ok(vec![self.0.clone()])
    ///     }
    ///
    ///     fn check(&mut self, structure: MessageStructure)
    ///              -> openpgp::Result<()> {
    ///         if let MessageLayer::SignatureGroup { ref results } =
    ///             structure.iter().nth(0).unwrap()
    ///         {
    ///             results.get(0).unwrap().as_ref().unwrap();
    ///             Ok(())
    ///         } else { panic!() }
    ///     }
    /// }
    ///
    /// let mut verifier = DetachedVerifierBuilder::from_bytes(&sink)?
    ///     .with_policy(p, None, Helper(&cert))?;
    ///
    /// verifier.verify_bytes(b"Make it so, number one!")?;
    /// # Ok(()) }
    /// ```
    pub fn detached(mut self) -> Self {
        self.mode = SignatureMode::Detached;
        self
    }

    /// Creates a signer for a cleartext signed message.
    ///
    /// Changes the `Signer` to create a cleartext signed message (see
    /// [Section 7 of RFC 4880]).  Note that the literal data *must
    /// not* be wrapped using the [`LiteralWriter`].  This implies
    /// ASCII armored output, *do not* add an [`Armorer`] to the
    /// stack.
    ///
    /// Note:
    ///
    /// - The cleartext signature framework does not hash trailing
    ///   whitespace (in this case, space and tab, see [Section 7.1 of
    ///   RFC 4880] for more information).  We align what we emit and
    ///   what is being signed by trimming whitespace off of line
    ///   endings.
    ///
    /// - That means that you can not recover a byte-accurate copy of
    ///   the signed message if your message contains either a line
    ///   with trailing whitespace, or no final newline.  This is a
    ///   limitation of the Cleartext Signature Framework, which is
    ///   not designed to be reversible (see [Section 7 of RFC 4880]).
    ///
    /// This overrides any prior call to [`Signer::detached`].
    ///
    ///   [Section 7 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-7
    ///   [Section 7.1 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-7.1
    ///   [`Signer::detached`]: Signer::detached()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::{Write, Read};
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Signer};
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::crypto::KeyPair;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair
    /// #     = cert.keys().secret()
    /// #           .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #           .nth(0).unwrap()
    /// #           .key().clone().into_keypair()?;
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut signer = Signer::new(message, signing_keypair)
    ///         .cleartext()
    ///         // Customize the `Signer` here.
    ///         .build()?;
    ///
    ///     // Write the data directly to the `Signer`.
    ///     signer.write_all(b"Make it so, number one!")?;
    ///     // In reality, just io::copy() the file to be signed.
    ///     signer.finalize()?;
    /// }
    ///
    /// // Now check the signature.
    /// struct Helper<'a>(&'a openpgp::Cert);
    /// impl<'a> VerificationHelper for Helper<'a> {
    ///     fn get_certs(&mut self, _: &[openpgp::KeyHandle])
    ///                        -> openpgp::Result<Vec<openpgp::Cert>> {
    ///         Ok(vec![self.0.clone()])
    ///     }
    ///
    ///     fn check(&mut self, structure: MessageStructure)
    ///              -> openpgp::Result<()> {
    ///         if let MessageLayer::SignatureGroup { ref results } =
    ///             structure.iter().nth(0).unwrap()
    ///         {
    ///             results.get(0).unwrap().as_ref().unwrap();
    ///             Ok(())
    ///         } else { panic!() }
    ///     }
    /// }
    ///
    /// let mut verifier = VerifierBuilder::from_bytes(&sink)?
    ///     .with_policy(p, None, Helper(&cert))?;
    ///
    /// let mut content = Vec::new();
    /// verifier.read_to_end(&mut content)?;
    /// assert_eq!(content, b"Make it so, number one!");
    /// # Ok(()) }
    /// ```
    //
    // Some notes on the implementation:
    //
    // There are a few pitfalls when implementing the CSF.  We
    // separate concerns as much as possible.
    //
    // - Trailing whitespace must be stripped.  We do this using the
    //   TrailingWSFilter before the data hits this streaming signer.
    //   This filter also adds a final newline, if missing.
    //
    // - We hash what we get from the TrailingWSFilter.
    //
    // - We write into the DashEscapeFilter, which takes care of the
    //   dash-escaping.
    pub fn cleartext(mut self) -> Self {
        self.mode = SignatureMode::Cleartext;
        self
    }

    /// Adds an additional signer.
    ///
    /// Can be used multiple times.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// # use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// # let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair = cert.keys().secret()
    /// #     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #     .nth(0).unwrap()
    /// #     .key().clone().into_keypair()?;
    /// # let additional_signing_keypair = cert.keys().secret()
    /// #     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #     .nth(0).unwrap()
    /// #     .key().clone().into_keypair()?;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Signer::new(message, signing_keypair)
    ///     .add_signer(additional_signing_keypair)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Make it so, number one!")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn add_signer<S>(mut self, signer: S) -> Self
        where S: crypto::Signer + Send + Sync + 'a
    {
        self.signers.push(Box::new(signer));
        self
    }

    /// Adds an intended recipient.
    ///
    /// Indicates that the given certificate is an intended recipient
    /// of this message.  Can be used multiple times.  This prevents
    /// [*Surreptitious Forwarding*] of encrypted and signed messages,
    /// i.e. forwarding a signed message using a different encryption
    /// context.
    ///
    ///   [*Surreptitious Forwarding*]: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// # use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::crypto::KeyPair;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// # let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair = cert.keys().secret()
    /// #     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #     .nth(0).unwrap()
    /// #     .key().clone().into_keypair()?;
    /// let recipient: Cert = // ...
    /// #     Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy.pgp")[..])?;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Signer::new(message, signing_keypair)
    ///     .add_intended_recipient(&recipient)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Make it so, number one!")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn add_intended_recipient(mut self, recipient: &Cert) -> Self {
        self.intended_recipients.push(recipient.fingerprint());
        self
    }

    /// Sets the hash algorithm to use for the signatures.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::HashAlgorithm;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// # use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// # let p = &StandardPolicy::new();
    /// # let cert = Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair = cert.keys().secret()
    /// #     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #     .nth(0).unwrap()
    /// #     .key().clone().into_keypair()?;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Signer::new(message, signing_keypair)
    ///     .hash_algo(HashAlgorithm::SHA384)?
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Make it so, number one!")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn hash_algo(mut self, algo: HashAlgorithm) -> Result<Self> {
        self.hash = HashingMode::Binary(algo.context()?);
        Ok(self)
    }

    /// Sets the signature's creation time to `time`.
    ///
    /// Note: it is up to the caller to make sure the signing keys are
    /// actually valid as of `time`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::Timestamp;
    /// use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// let p = &StandardPolicy::new();
    /// let cert: Cert = // ...
    /// #     Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// let signing_key = cert.keys().secret()
    ///     .with_policy(p, None).supported().alive().revoked(false).for_signing()
    ///     .nth(0).unwrap()
    ///     .key();
    /// let signing_keypair = signing_key.clone().into_keypair()?;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Signer::new(message, signing_keypair)
    ///     .creation_time(Timestamp::now()
    ///                    .round_down(None, signing_key.creation_time())?)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Make it so, number one!")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn creation_time<T: Into<SystemTime>>(mut self, creation_time: T)
                                              -> Self
    {
        self.creation_time = Some(creation_time.into());
        self
    }

    /// Builds the signer, returning the writer stack.
    ///
    /// The most useful filter to push to the writer stack next is the
    /// [`LiteralWriter`].  Note, if you are creating a signed OpenPGP
    /// message (see [Section 11.3 of RFC 4880]), literal data *must*
    /// be wrapped using the [`LiteralWriter`].  On the other hand, if
    /// you are creating a detached signature (see [Section 11.4 of
    /// RFC 4880]), the literal data *must not* be wrapped using the
    /// [`LiteralWriter`].
    ///
    ///   [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
    ///   [Section 11.4 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.4
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::Timestamp;
    /// use openpgp::serialize::stream::{Message, Signer};
    /// # use openpgp::policy::StandardPolicy;
    /// # use openpgp::{Result, Cert};
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::parse::Parse;
    /// # use openpgp::parse::stream::*;
    ///
    /// # let p = &StandardPolicy::new();
    /// # let cert: Cert = // ...
    /// #     Cert::from_bytes(&include_bytes!(
    /// #     "../../tests/data/keys/testy-new-private.pgp")[..])?;
    /// # let signing_keypair
    /// #     = cert.keys().secret()
    /// #           .with_policy(p, None).supported().alive().revoked(false).for_signing()
    /// #           .nth(0).unwrap()
    /// #           .key().clone().into_keypair()?;
    /// #
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Signer::new(message, signing_keypair)
    ///     // Customize the `Signer` here.
    ///     .build()?;
    /// # Ok(()) }
    /// ```
    pub fn build(mut self) -> Result<Message<'a>>
    {
        assert!(!self.signers.is_empty(), "The constructor adds a signer.");
        assert!(self.inner.is_some(), "The constructor adds an inner writer.");

        let mut acceptable_hashes = crate::crypto::hash::DEFAULT_HASHES.to_vec();

        let is_sorted = |data: &[HashAlgorithm]| {
            data.windows(2).all(|w| w[0] <= w[1])
        };

        for signer in &self.signers {
            let mut signer_hashes = signer.acceptable_hashes();
            let mut signer_hashes_;
            if ! is_sorted(signer_hashes) {
                signer_hashes_ = signer_hashes.to_vec();
                signer_hashes_.sort();
                signer_hashes = &signer_hashes_;
            }
            acceptable_hashes.retain(|hash| signer_hashes.binary_search(hash).is_ok());
        }

        if let Some(hash) = acceptable_hashes.first() {
            let ctx = hash.context().unwrap();
            self.hash = if self.template.typ() == SignatureType::Text
                || self.mode == SignatureMode::Cleartext
            {
                HashingMode::Text(ctx)
            } else {
                HashingMode::Binary(ctx)
            };
        } else {
            return Err(Error::NoAcceptableHash.into());
        }

        match self.mode {
            SignatureMode::Inline => {
                // For every key we collected, build and emit a one pass
                // signature packet.
                for (i, keypair) in self.signers.iter().enumerate() {
                    let key = keypair.public();
                    let mut ops = OnePassSig3::new(self.template.typ());
                    ops.set_pk_algo(key.pk_algo());
                    ops.set_hash_algo(self.hash.as_ref().algo());
                    ops.set_issuer(key.keyid());
                    ops.set_last(i == self.signers.len() - 1);
                    Packet::OnePassSig(ops.into())
                        .serialize(self.inner.as_mut().unwrap())?;
                }
            },
            SignatureMode::Detached => (), // Do nothing.
            SignatureMode::Cleartext => {
                // Cleartext signatures are always text signatures.
                self.template = self.template.set_type(SignatureType::Text);

                // Write the header.
                let mut sink = self.inner.take().unwrap();
                writeln!(sink, "-----BEGIN PGP SIGNED MESSAGE-----")?;
                writeln!(sink, "Hash: {}",
                         self.hash.as_ref().algo().text_name()?)?;
                writeln!(sink)?;

                // We now install two filters.  See the comment on
                // Signer::cleartext.

                // Install the filter dash-escaping the text below us.
                self.inner =
                    Some(writer::BoxStack::from(
                        DashEscapeFilter::new(Message::from(sink),
                                              Default::default())));

                // Install the filter trimming the trailing whitespace
                // above us.
                return Ok(TrailingWSFilter::new(Message::from(Box::new(self)),
                                                Default::default()));
            },
        }

        Ok(Message::from(Box::new(self)))
    }

    fn emit_signatures(&mut self) -> Result<()> {
        if self.mode == SignatureMode::Cleartext {
            // Pop off the DashEscapeFilter.
            let mut inner =
                self.inner.take().expect("It's the DashEscapeFilter")
                .into_inner()?.expect("It's the DashEscapeFilter");

            // Add the separating newline that is not part of the message.
            writeln!(inner)?;

            // And install an armorer.
            self.inner =
                Some(writer::BoxStack::from(
                    writer::Armorer::new(Message::from(inner),
                                         Default::default(),
                                         armor::Kind::Signature,
                                         Option::<(&str, &str)>::None)?));
        }

        if let Some(ref mut sink) = self.inner {
            // Emit the signatures in reverse, so that the
            // one-pass-signature and signature packets "bracket" the
            // message.
            for signer in self.signers.iter_mut().rev() {
                // Part of the signature packet is hashed in,
                // therefore we need to clone the hash.
                let hash = self.hash.clone();

                // Make and hash a signature packet.
                let mut sig = self.template.clone()
                    .set_signature_creation_time(
                        self.creation_time
                            .unwrap_or_else(crate::now))?;

                if ! self.intended_recipients.is_empty() {
                    sig = sig.set_intended_recipients(
                        self.intended_recipients.clone())?;
                }

                // Compute the signature.
                let sig = sig.sign_hash(signer.as_mut(),
                                        hash.into_inner())?;

                // And emit the packet.
                Packet::Signature(sig).serialize(sink)?;
            }
        }
        Ok(())
    }
}

impl<'a> fmt::Debug for Signer<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Signer")
            .field("inner", &self.inner)
            .field("cookie", &self.cookie)
            .field("mode", &self.mode)
            .finish()
    }
}

impl<'a> Write for Signer<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Shortcut empty writes.  This is important for the code
        // below that delays hashing newlines when creating cleartext
        // signed messages.
        if buf.is_empty() {
            return Ok(0);
        }

        use SignatureMode::*;
        let written = match (self.inner.as_mut(), self.mode) {
            // If we are creating a normal signature, pass data
            // through.
            (Some(ref mut w), Inline) => w.write(buf),
            // If we are creating a detached signature, just hash all
            // bytes.
            (Some(_), Detached) => Ok(buf.len()),
            // If we are creating a cleartext signed message, just
            // write through (the DashEscapeFilter takes care of the
            // encoding), and hash all bytes as is.
            (Some(ref mut w), Cleartext) => w.write(buf),
            // When we are popped off the stack, we have no inner
            // writer.  Just hash all bytes.
            (None, _) => Ok(buf.len()),
        };

        if let Ok(amount) = written {
            let data = &buf[..amount];
            self.hash.update(data);
            self.position += amount as u64;
        }

        written
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.inner.as_mut() {
            Some(ref mut w) => w.flush(),
            // When we are popped off the stack, we have no inner
            // writer.  Just do nothing.
            None => Ok(()),
        }
    }
}

impl<'a> writer::Stackable<'a, Cookie> for Signer<'a> {
    fn pop(&mut self) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        Ok(self.inner.take())
    }
    fn mount(&mut self, new: writer::BoxStack<'a, Cookie>) {
        self.inner = Some(new);
    }
    fn inner_mut(&mut self) -> Option<&mut (dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        if let Some(ref mut i) = self.inner {
            Some(i)
        } else {
            None
        }
    }
    fn inner_ref(&self) -> Option<&(dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        self.inner.as_ref().map(|r| r.as_ref())
    }
    fn into_inner(mut self: Box<Self>)
                  -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        self.emit_signatures()?;
        Ok(self.inner.take())
    }
    fn cookie_set(&mut self, cookie: Cookie) -> Cookie {
        ::std::mem::replace(&mut self.cookie, cookie)
    }
    fn cookie_ref(&self) -> &Cookie {
        &self.cookie
    }
    fn cookie_mut(&mut self) -> &mut Cookie {
        &mut self.cookie
    }
    fn position(&self) -> u64 {
        self.position
    }
}


/// Writes a literal data packet.
///
/// Literal data, i.e. the payload or plaintext, must be wrapped in a
/// literal data packet to be transported over OpenPGP (see [Section
/// 5.9 of RFC 4880]).  The body will be written using partial length
/// encoding, or, if the body is short, using full length encoding.
///
///   [Section 5.9 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.9
///
/// # Note on metadata
///
/// A literal data packet can communicate some metadata: a hint as to
/// what kind of data is transported, the original file name, and a
/// timestamp.  Note that this metadata will not be authenticated by
/// signatures (but will be authenticated by a SEIP/MDC container),
/// and are therefore unreliable and should not be trusted.
///
/// Therefore, it is good practice not to set this metadata when
/// creating a literal data packet, and not to interpret it when
/// consuming one.
pub struct LiteralWriter<'a> {
    template: Literal,
    inner: writer::BoxStack<'a, Cookie>,
    signature_writer: Option<writer::BoxStack<'a, Cookie>>,
}
assert_send_and_sync!(LiteralWriter<'_>);

impl<'a> LiteralWriter<'a> {
    /// Creates a new literal writer.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = LiteralWriter::new(message)
    ///         // Customize the `LiteralWriter` here.
    ///         .build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn new(inner: Message<'a>) -> Self {
        LiteralWriter {
            template: Literal::new(DataFormat::default()),
            inner: writer::BoxStack::from(inner),
            signature_writer: None,
        }
    }

    /// Sets the data format.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::DataFormat;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = LiteralWriter::new(message)
    ///         .format(DataFormat::Text)
    ///         .build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x12t\x00\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn format(mut self, format: DataFormat) -> Self {
        self.template.set_format(format);
        self
    }

    /// Sets the filename.
    ///
    /// The standard does not specify the encoding.  Filenames must
    /// not be longer than 255 bytes.  Returns an error if the given
    /// name is longer than that.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = LiteralWriter::new(message)
    ///         .filename("foobar")?
    ///         .build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x18b\x06foobar\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn filename<B: AsRef<[u8]>>(mut self, filename: B) -> Result<Self> {
        self.template.set_filename(filename.as_ref())?;
        Ok(self)
    }

    /// Sets the date.
    ///
    /// This date may be the modification date or the creation date.
    /// Returns an error if the given date is not representable by
    /// OpenPGP.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::Timestamp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = LiteralWriter::new(message)
    ///         .date(Timestamp::from(1585925313))?
    ///         .build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x12b\x00\x5e\x87\x4c\xc1Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn date<T: Into<SystemTime>>(mut self, timestamp: T) -> Result<Self>
    {
        self.template.set_date(Some(timestamp.into()))?;
        Ok(self)
    }

    /// Builds the literal writer, returning the writer stack.
    ///
    /// The next step is to write the payload to the writer stack.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, LiteralWriter};
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let mut message = LiteralWriter::new(message)
    ///         // Customize the `LiteralWriter` here.
    ///         .build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn build(mut self) -> Result<Message<'a>> {
        let level = self.inner.cookie_ref().level + 1;

        // For historical reasons, signatures over literal data
        // packets only include the body without metadata or framing.
        // Therefore, we check whether the writer is a
        // Signer, and if so, we pop it off the stack and
        // store it in 'self.signature_writer'.
        let signer_above =
            matches!(self.inner.cookie_ref(), &Cookie {
                private: Private::Signer{..},
                ..
            });

        if signer_above {
            let stack = self.inner.pop()?;
            // We know a signer has an inner stackable.
            let stack = stack.unwrap();
            self.signature_writer = Some(self.inner);
            self.inner = stack;
        }

        // Not hashed by the signature_writer (see above).
        CTB::new(Tag::Literal).serialize(&mut self.inner)?;

        // Neither is any framing added by the PartialBodyFilter.
        self.inner
            = PartialBodyFilter::new(Message::from(self.inner),
                                     Cookie::new(level)).into();

        // Nor the headers.
        self.template.serialize_headers(&mut self.inner, false)?;

        Ok(Message::from(Box::new(self)))
    }
}

impl<'a> fmt::Debug for LiteralWriter<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("LiteralWriter")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<'a> Write for LiteralWriter<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = self.inner.write(buf);

        // Any successful written bytes needs to be hashed too.
        if let (&Ok(ref amount), &mut Some(ref mut sig))
            = (&written, &mut self.signature_writer) {
                sig.write_all(&buf[..*amount])?;
            };
        written
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl<'a> writer::Stackable<'a, Cookie> for LiteralWriter<'a> {
    fn into_inner(mut self: Box<Self>)
                  -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        let signer = self.signature_writer.take();
        let stack = self.inner
            .into_inner()?.unwrap(); // Peel off the PartialBodyFilter.

        if let Some(mut signer) = signer {
            // We stashed away a Signer.  Reattach it to the
            // stack and return it.
            signer.mount(stack);
            Ok(Some(signer))
        } else {
            Ok(Some(stack))
        }
    }

    fn pop(&mut self) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        unreachable!("Only implemented by Signer")
    }
    /// Sets the inner stackable.
    fn mount(&mut self, _new: writer::BoxStack<'a, Cookie>) {
        unreachable!("Only implemented by Signer")
    }
    fn inner_ref(&self) -> Option<&(dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_ref())
    }
    fn inner_mut(&mut self) -> Option<&mut (dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_mut())
    }
    fn cookie_set(&mut self, cookie: Cookie) -> Cookie {
        self.inner.cookie_set(cookie)
    }
    fn cookie_ref(&self) -> &Cookie {
        self.inner.cookie_ref()
    }
    fn cookie_mut(&mut self) -> &mut Cookie {
        self.inner.cookie_mut()
    }
    fn position(&self) -> u64 {
        self.inner.position()
    }
}

/// Compresses a message.
///
/// Writes a compressed data packet containing all packets written to
/// this writer.
pub struct Compressor<'a> {
    algo: CompressionAlgorithm,
    level: CompressionLevel,
    inner: writer::BoxStack<'a, Cookie>,
}
assert_send_and_sync!(Compressor<'_>);

impl<'a> Compressor<'a> {
    /// Creates a new compressor using the default algorithm and
    /// compression level.
    ///
    /// To change the compression algorithm use [`Compressor::algo`].
    /// Use [`Compressor::level`] to change the compression level.
    ///
    ///   [`Compressor::algo`]: Compressor::algo()
    ///   [`Compressor::level`]: Compressor::level()
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Compressor, LiteralWriter};
    /// use openpgp::types::CompressionAlgorithm;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Compressor::new(message)
    ///     // Customize the `Compressor` here.
    /// #   .algo(CompressionAlgorithm::Uncompressed)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn new(inner: Message<'a>) -> Self {
        Self {
            algo: Default::default(),
            level: Default::default(),
            inner: inner.into(),
        }
    }

    /// Sets the compression algorithm.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Compressor, LiteralWriter};
    /// use openpgp::types::CompressionAlgorithm;
    ///
    /// let mut sink = vec![];
    /// {
    ///     let message = Message::new(&mut sink);
    ///     let message = Compressor::new(message)
    ///         .algo(CompressionAlgorithm::Uncompressed)
    ///         .build()?;
    ///     let mut message = LiteralWriter::new(message).build()?;
    ///     message.write_all(b"Hello world.")?;
    ///     message.finalize()?;
    /// }
    /// assert_eq!(b"\xc8\x15\x00\xcb\x12b\x00\x00\x00\x00\x00Hello world.",
    ///            sink.as_slice());
    /// # Ok(()) }
    /// ```
    pub fn algo(mut self, algo: CompressionAlgorithm) -> Self {
        self.algo = algo;
        self
    }

    /// Sets the compression level.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Compressor, LiteralWriter};
    /// use openpgp::types::{CompressionAlgorithm, CompressionLevel};
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Compressor::new(message)
    /// #   .algo(CompressionAlgorithm::Uncompressed)
    ///     .level(CompressionLevel::fastest())
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn level(mut self, level: CompressionLevel) -> Self {
        self.level = level;
        self
    }

    /// Builds the compressor, returning the writer stack.
    ///
    /// The most useful filter to push to the writer stack next is the
    /// [`Signer`] or the [`LiteralWriter`].  Finally, literal data
    /// *must* be wrapped using the [`LiteralWriter`].
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{Message, Compressor, LiteralWriter};
    /// use openpgp::types::CompressionAlgorithm;
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Compressor::new(message)
    ///     // Customize the `Compressor` here.
    /// #   .algo(CompressionAlgorithm::Uncompressed)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn build(mut self) -> Result<Message<'a>> {
        let level = self.inner.cookie_ref().level + 1;

        // Packet header.
        CTB::new(Tag::CompressedData).serialize(&mut self.inner)?;
        let inner: Message<'a>
            = PartialBodyFilter::new(Message::from(self.inner),
                                     Cookie::new(level));

        Self::new_naked(inner, self.algo, self.level, level)
    }


    /// Creates a new compressor using the given algorithm.
    pub(crate) // For CompressedData::serialize.
    fn new_naked(mut inner: Message<'a>,
                 algo: CompressionAlgorithm,
                 compression_level: CompressionLevel,
                 level: usize)
                 -> Result<Message<'a>>
    {
        // Compressed data header.
        inner.as_mut().write_u8(algo.into())?;

        // Create an appropriate filter.
        let inner: Message<'a> = match algo {
            CompressionAlgorithm::Uncompressed => {
                // Avoid warning about unused value if compiled
                // without any compression support.
                let _ = compression_level;
                writer::Identity::new(inner, Cookie::new(level))
            },
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zip =>
                writer::ZIP::new(inner, Cookie::new(level), compression_level),
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zlib =>
                writer::ZLIB::new(inner, Cookie::new(level), compression_level),
            #[cfg(feature = "compression-bzip2")]
            CompressionAlgorithm::BZip2 =>
                writer::BZ::new(inner, Cookie::new(level), compression_level),
            a =>
                return Err(Error::UnsupportedCompressionAlgorithm(a).into()),
        };

        Ok(Message::from(Box::new(Self {
            algo,
            level: compression_level,
            inner: inner.into(),
        })))
    }
}

impl<'a> fmt::Debug for Compressor<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Compressor")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<'a> io::Write for Compressor<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl<'a> writer::Stackable<'a, Cookie> for Compressor<'a> {
    fn into_inner(self: Box<Self>) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        Box::new(self.inner).into_inner()?.unwrap().into_inner()
    }
    fn pop(&mut self) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        unreachable!("Only implemented by Signer")
    }
    /// Sets the inner stackable.
    fn mount(&mut self, _new: writer::BoxStack<'a, Cookie>) {
        unreachable!("Only implemented by Signer")
    }
    fn inner_ref(&self) -> Option<&(dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_ref())
    }
    fn inner_mut(&mut self) -> Option<&mut (dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(self.inner.as_mut())
    }
    fn cookie_set(&mut self, cookie: Cookie) -> Cookie {
        self.inner.cookie_set(cookie)
    }
    fn cookie_ref(&self) -> &Cookie {
        self.inner.cookie_ref()
    }
    fn cookie_mut(&mut self) -> &mut Cookie {
        self.inner.cookie_mut()
    }
    fn position(&self) -> u64 {
        self.inner.position()
    }
}

/// A recipient of an encrypted message.
///
/// OpenPGP messages are encrypted with the subkeys of recipients,
/// identified by the keyid of said subkeys in the [`recipient`] field
/// of [`PKESK`] packets (see [Section 5.1 of RFC 4880]).  The keyid
/// may be a wildcard (as returned by [`KeyID::wildcard()`]) to
/// obscure the identity of the recipient.
///
///   [`recipient`]: crate::packet::PKESK#method.recipient
///   [`PKESK`]: crate::packet::PKESK
///   [Section 5.1 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.1
///   [`KeyID::wildcard()`]: crate::KeyID::wildcard()
///
/// Note that several subkeys in a certificate may be suitable
/// encryption subkeys.  OpenPGP does not specify what should happen
/// in this case.  Some implementations arbitrarily pick one
/// encryption subkey, while others use all of them.  This crate does
/// not dictate a policy, but allows for arbitrary policies.  We do,
/// however, suggest to encrypt to all suitable subkeys.
#[derive(Debug)]
pub struct Recipient<'a> {
    keyid: KeyID,
    key: &'a Key<key::PublicParts, key::UnspecifiedRole>,
}
assert_send_and_sync!(Recipient<'_>);

impl<'a, P, R> From<&'a Key<P, R>> for Recipient<'a>
    where P: key::KeyParts,
          R: key::KeyRole,
{
    fn from(key: &'a Key<P, R>) -> Self {
        Self::new(key.keyid(), key.parts_as_public().role_as_unspecified())
    }
}

impl<'a, P, R, R2> From<ValidKeyAmalgamation<'a, P, R, R2>>
    for Recipient<'a>
    where P: key::KeyParts,
          R: key::KeyRole,
          R2: Copy,
{
    fn from(ka: ValidKeyAmalgamation<'a, P, R, R2>) -> Self {
        ka.key().into()
    }
}

impl<'a> Recipient<'a> {
    /// Creates a new recipient with an explicit recipient keyid.
    ///
    /// Note: If you don't want to change the recipient keyid,
    /// `Recipient`s can be created from [`Key`] and
    /// [`ValidKeyAmalgamation`] using [`From`].
    ///
    ///   [`Key`]: crate::packet::Key
    ///   [`ValidKeyAmalgamation`]: crate::cert::amalgamation::key::ValidKeyAmalgamation
    ///   [`From`]: std::convert::From
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::{
    ///     Recipient, Message, Encryptor,
    /// };
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      xjMEWlNvABYJKwYBBAHaRw8BAQdA+EC2pvebpEbzPA9YplVgVXzkIG5eK+7wEAez
    /// #    lcBgLJrNMVRlc3R5IE1jVGVzdGZhY2UgKG15IG5ldyBrZXkpIDx0ZXN0eUBleGFt
    /// #    cGxlLm9yZz7CkAQTFggAOBYhBDnRAKtn1b2MBAECBfs3UfFYfa7xBQJaU28AAhsD
    /// #    BQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEPs3UfFYfa7xJHQBAO4/GABMWUcJ
    /// #    5D/DZ9b+6YiFnysSjCT/gILJgxMgl7uoAPwJherI1pAAh49RnPHBR1IkWDtwzX65
    /// #    CJG8sDyO2FhzDs44BFpTbwASCisGAQQBl1UBBQEBB0B+A0GRHuBgdDX50T1nePjb
    /// #    mKQ5PeqXJbWEtVrUtVJaPwMBCAfCeAQYFggAIBYhBDnRAKtn1b2MBAECBfs3UfFY
    /// #    fa7xBQJaU28AAhsMAAoJEPs3UfFYfa7xzjIBANX2/FgDX3WkmvwpEHg/sn40zACM
    /// #    W2hrBY5x0sZ8H7JlAP47mCfCuRVBqyaePuzKbxLJeLe2BpDdc0n2izMVj8t9Cg==
    /// #    =QetZ
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption()
    ///     .map(|ka| Recipient::new(ka.key().keyid(), ka.key()));
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Encryptor::for_recipients(message, recipients).build()?;
    /// # let _ = message;
    /// # Ok(()) }
    /// ```
    pub fn new<P, R>(keyid: KeyID, key: &'a Key<P, R>) -> Recipient<'a>
        where P: key::KeyParts,
              R: key::KeyRole,
    {
        Recipient {
            keyid,
            key: key.parts_as_public().role_as_unspecified(),
        }
    }

    /// Gets the recipient keyid.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::Recipient;
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      xjMEWlNvABYJKwYBBAHaRw8BAQdA+EC2pvebpEbzPA9YplVgVXzkIG5eK+7wEAez
    /// #    lcBgLJrNMVRlc3R5IE1jVGVzdGZhY2UgKG15IG5ldyBrZXkpIDx0ZXN0eUBleGFt
    /// #    cGxlLm9yZz7CkAQTFggAOBYhBDnRAKtn1b2MBAECBfs3UfFYfa7xBQJaU28AAhsD
    /// #    BQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEPs3UfFYfa7xJHQBAO4/GABMWUcJ
    /// #    5D/DZ9b+6YiFnysSjCT/gILJgxMgl7uoAPwJherI1pAAh49RnPHBR1IkWDtwzX65
    /// #    CJG8sDyO2FhzDs44BFpTbwASCisGAQQBl1UBBQEBB0B+A0GRHuBgdDX50T1nePjb
    /// #    mKQ5PeqXJbWEtVrUtVJaPwMBCAfCeAQYFggAIBYhBDnRAKtn1b2MBAECBfs3UfFY
    /// #    fa7xBQJaU28AAhsMAAoJEPs3UfFYfa7xzjIBANX2/FgDX3WkmvwpEHg/sn40zACM
    /// #    W2hrBY5x0sZ8H7JlAP47mCfCuRVBqyaePuzKbxLJeLe2BpDdc0n2izMVj8t9Cg==
    /// #    =QetZ
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption()
    ///     .map(Into::into)
    ///     .collect::<Vec<Recipient>>();
    ///
    /// assert_eq!(recipients[0].keyid(),
    ///            &"8BD8 8E94 C0D2 0333".parse()?);
    /// # Ok(()) }
    /// ```
    pub fn keyid(&self) -> &KeyID {
        &self.keyid
    }

    /// Sets the recipient keyid.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::KeyID;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::{
    ///     Recipient, Message, Encryptor,
    /// };
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      xjMEWlNvABYJKwYBBAHaRw8BAQdA+EC2pvebpEbzPA9YplVgVXzkIG5eK+7wEAez
    /// #    lcBgLJrNMVRlc3R5IE1jVGVzdGZhY2UgKG15IG5ldyBrZXkpIDx0ZXN0eUBleGFt
    /// #    cGxlLm9yZz7CkAQTFggAOBYhBDnRAKtn1b2MBAECBfs3UfFYfa7xBQJaU28AAhsD
    /// #    BQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEPs3UfFYfa7xJHQBAO4/GABMWUcJ
    /// #    5D/DZ9b+6YiFnysSjCT/gILJgxMgl7uoAPwJherI1pAAh49RnPHBR1IkWDtwzX65
    /// #    CJG8sDyO2FhzDs44BFpTbwASCisGAQQBl1UBBQEBB0B+A0GRHuBgdDX50T1nePjb
    /// #    mKQ5PeqXJbWEtVrUtVJaPwMBCAfCeAQYFggAIBYhBDnRAKtn1b2MBAECBfs3UfFY
    /// #    fa7xBQJaU28AAhsMAAoJEPs3UfFYfa7xzjIBANX2/FgDX3WkmvwpEHg/sn40zACM
    /// #    W2hrBY5x0sZ8H7JlAP47mCfCuRVBqyaePuzKbxLJeLe2BpDdc0n2izMVj8t9Cg==
    /// #    =QetZ
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption()
    ///     .map(|ka| Recipient::from(ka)
    ///         // Set the recipient keyid to the wildcard id.
    ///         .set_keyid(KeyID::wildcard())
    ///     );
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Encryptor::for_recipients(message, recipients).build()?;
    /// # let _ = message;
    /// # Ok(()) }
    /// ```
    pub fn set_keyid(mut self, keyid: KeyID) -> Self {
        self.keyid = keyid;
        self
    }
}

/// Encrypts a message.
///
/// The stream will be encrypted using a generated session key, which
/// will be encrypted using the given passwords, and for all given
/// recipients.
///
/// An [`Recipient`] is an encryption-capable (sub)key.  Note that a
/// certificate may have more than one encryption-capable subkey, and
/// even the primary key may be encryption-capable.
///
///
/// To encrypt for more than one certificate, iterate over the
/// certificates and select encryption-capable keys, making sure that
/// at least one key is selected from each certificate.
///
/// # Examples
///
/// This demonstrates encrypting for multiple certificates.
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// # use std::io::Write;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::parse::Parse;
/// use openpgp::serialize::stream::{
///     Message, Encryptor, LiteralWriter,
/// };
/// use openpgp::policy::StandardPolicy;
/// let p = &StandardPolicy::new();
///
/// # let (cert_0, _) =
/// #     CertBuilder::general_purpose(None, Some("Mr. Pink ☮☮☮"))
/// #     .generate()?;
/// # let (cert_1, _) =
/// #     CertBuilder::general_purpose(None, Some("Mr. Pink ☮☮☮"))
/// #     .generate()?;
/// let recipient_certs = vec![cert_0, cert_1];
/// let mut recipients = Vec::new();
/// for cert in recipient_certs.iter() {
///     // Make sure we add at least one subkey from every
///     // certificate.
///     let mut found_one = false;
///     for key in cert.keys().with_policy(p, None)
///         .supported().alive().revoked(false).for_transport_encryption()
///     {
///         recipients.push(key);
///         found_one = true;
///     }
///
///     if ! found_one {
///         return Err(anyhow::anyhow!("No suitable encryption subkey for {}",
///                                    cert));
///     }
/// }
/// # assert_eq!(recipients.len(), 2);
///
/// # let mut sink = vec![];
/// let message = Message::new(&mut sink);
/// let message = Encryptor::for_recipients(message, recipients).build()?;
/// let mut w = LiteralWriter::new(message).build()?;
/// w.write_all(b"Hello world.")?;
/// w.finalize()?;
/// # Ok(()) }
/// ```
pub struct Encryptor<'a> {
    inner: writer::BoxStack<'a, Cookie>,
    session_key: Option<SessionKey>,
    recipients: Vec<Recipient<'a>>,
    passwords: Vec<Password>,
    sym_algo: SymmetricAlgorithm,
    aead_algo: Option<AEADAlgorithm>,
    hash: Box<dyn crypto::hash::Digest>,
    cookie: Cookie,
}
assert_send_and_sync!(Encryptor<'_>);

impl<'a> Encryptor<'a> {
    /// Creates a new encryptor for the given recipients.
    ///
    /// To add more recipients, use [`Encryptor::add_recipients`].  To
    /// add passwords, use [`Encryptor::add_passwords`].  To change
    /// the symmetric encryption algorithm, use
    /// [`Encryptor::symmetric_algo`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      xjMEWlNvABYJKwYBBAHaRw8BAQdA+EC2pvebpEbzPA9YplVgVXzkIG5eK+7wEAez
    /// #    lcBgLJrNMVRlc3R5IE1jVGVzdGZhY2UgKG15IG5ldyBrZXkpIDx0ZXN0eUBleGFt
    /// #    cGxlLm9yZz7CkAQTFggAOBYhBDnRAKtn1b2MBAECBfs3UfFYfa7xBQJaU28AAhsD
    /// #    BQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEPs3UfFYfa7xJHQBAO4/GABMWUcJ
    /// #    5D/DZ9b+6YiFnysSjCT/gILJgxMgl7uoAPwJherI1pAAh49RnPHBR1IkWDtwzX65
    /// #    CJG8sDyO2FhzDs44BFpTbwASCisGAQQBl1UBBQEBB0B+A0GRHuBgdDX50T1nePjb
    /// #    mKQ5PeqXJbWEtVrUtVJaPwMBCAfCeAQYFggAIBYhBDnRAKtn1b2MBAECBfs3UfFY
    /// #    fa7xBQJaU28AAhsMAAoJEPs3UfFYfa7xzjIBANX2/FgDX3WkmvwpEHg/sn40zACM
    /// #    W2hrBY5x0sZ8H7JlAP47mCfCuRVBqyaePuzKbxLJeLe2BpDdc0n2izMVj8t9Cg==
    /// #    =QetZ
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption();
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Encryptor::for_recipients(message, recipients).build()?;
    /// let mut w = LiteralWriter::new(message).build()?;
    /// w.write_all(b"Hello world.")?;
    /// w.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn for_recipients<R>(inner: Message<'a>, recipients: R) -> Self
        where R: IntoIterator,
              R::Item: Into<Recipient<'a>>,
    {
        Self {
            inner: inner.into(),
            session_key: None,
            recipients: recipients.into_iter().map(|r| r.into()).collect(),
            passwords: Vec::new(),
            sym_algo: Default::default(),
            aead_algo: Default::default(),
            hash: HashAlgorithm::SHA1.context().unwrap(),
            cookie: Default::default(), // Will be fixed in build.
        }
    }

    /// Creates a new encryptor for the given passwords.
    ///
    /// To add more passwords, use [`Encryptor::add_passwords`].  To
    /// add recipients, use [`Encryptor::add_recipients`].  To change
    /// the symmetric encryption algorithm, use
    /// [`Encryptor::symmetric_algo`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message = Encryptor::with_passwords(
    ///     message, Some("совершенно секретно")).build()?;
    /// let mut w = LiteralWriter::new(message).build()?;
    /// w.write_all(b"Hello world.")?;
    /// w.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn with_passwords<P>(inner: Message<'a>, passwords: P) -> Self
        where P: IntoIterator,
              P::Item: Into<Password>,
    {
        Self {
            inner: inner.into(),
            session_key: None,
            recipients: Vec::new(),
            passwords: passwords.into_iter().map(|p| p.into()).collect(),
            sym_algo: Default::default(),
            aead_algo: Default::default(),
            hash: HashAlgorithm::SHA1.context().unwrap(),
            cookie: Default::default(), // Will be fixed in build.
        }
    }

    /// Creates a new encryptor for the given algorithm and session
    /// key.
    ///
    /// Usually, the encryptor creates a session key and decrypts it
    /// for the given recipients and passwords.  Using this function,
    /// the session key can be supplied instead.  There are two main
    /// use cases for this:
    ///
    ///   - Replying to an encrypted message usually requires the
    ///     encryption (sub)keys for every recipient.  If even one key
    ///     is not available, it is not possible to encrypt the new
    ///     session key.  Rather than falling back to replying
    ///     unencrypted, one can reuse the original message's session
    ///     key that was encrypted for every recipient and reuse the
    ///     original [`PKESK`](crate::packet::PKESK)s.
    ///
    ///   - Using the encryptor if the session key is transmitted or
    ///     derived using a scheme not supported by Sequoia.
    ///
    /// To add more passwords, use [`Encryptor::add_passwords`].  To
    /// add recipients, use [`Encryptor::add_recipients`].
    ///
    /// # Examples
    ///
    /// This example demonstrates how to fall back to the original
    /// message's session key in order to encrypt a reply.
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// # use std::io::{self, Write};
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, KeyID, Fingerprint, Result};
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::packet::prelude::*;
    /// # use openpgp::crypto::{KeyPair, SessionKey};
    /// # use openpgp::types::SymmetricAlgorithm;
    /// # use openpgp::parse::{Parse, stream::*};
    /// # use openpgp::serialize::{Serialize, stream::*};
    /// # use openpgp::policy::{Policy, StandardPolicy};
    /// # let p = &StandardPolicy::new();
    /// #
    /// // Generate two keys.
    /// let (alice, _) = CertBuilder::general_purpose(
    ///         None, Some("Alice Lovelace <alice@example.org>")).generate()?;
    /// let (bob, _) = CertBuilder::general_purpose(
    ///         None, Some("Bob Babbage <bob@example.org>")).generate()?;
    ///
    /// // Encrypt a message for both keys.
    /// let recipients = vec![&alice, &bob].into_iter().flat_map(|cert| {
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///         .for_transport_encryption()
    /// });
    ///
    /// let mut original = vec![];
    /// let message = Message::new(&mut original);
    /// let message = Encryptor::for_recipients(message, recipients).build()?;
    /// let mut w = LiteralWriter::new(message).build()?;
    /// w.write_all(b"Original message")?;
    /// w.finalize()?;
    ///
    /// // Decrypt original message using Alice's key.
    /// let mut decryptor = DecryptorBuilder::from_bytes(&original)?
    ///     .with_policy(p, None, Helper::new(alice))?;
    /// io::copy(&mut decryptor, &mut io::sink())?;
    /// let (algo, sk, pkesks) = decryptor.into_helper().recycling_bin.unwrap();
    ///
    /// // Compose the reply using the same session key.
    /// let mut reply = vec![];
    /// let mut message = Message::new(&mut reply);
    /// for p in pkesks { // Emit the stashed PKESK packets.
    ///     Packet::from(p).serialize(&mut message)?;
    /// }
    /// let message = Encryptor::with_session_key(message, algo, sk)?.build()?;
    /// let mut w = LiteralWriter::new(message).build()?;
    /// w.write_all(b"Encrypted reply")?;
    /// w.finalize()?;
    ///
    /// // Check that Bob can decrypt it.
    /// let mut decryptor = DecryptorBuilder::from_bytes(&reply)?
    ///     .with_policy(p, None, Helper::new(bob))?;
    /// io::copy(&mut decryptor, &mut io::sink())?;
    ///
    /// /// Decrypts the message preserving algo, session key, and PKESKs.
    /// struct Helper {
    ///     key: Cert,
    ///     recycling_bin: Option<(SymmetricAlgorithm, SessionKey, Vec<PKESK>)>,
    /// }
    ///
    /// # impl Helper {
    /// #     fn new(key: Cert) -> Self {
    /// #         Helper { key, recycling_bin: None, }
    /// #     }
    /// # }
    /// #
    /// impl DecryptionHelper for Helper {
    ///     fn decrypt<D>(&mut self, pkesks: &[PKESK], _skesks: &[SKESK],
    ///                   sym_algo: Option<SymmetricAlgorithm>, mut decrypt: D)
    ///                   -> Result<Option<Fingerprint>>
    ///         where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
    ///     {
    ///         let p = &StandardPolicy::new();
    ///         let mut encryption_context = None;
    ///
    ///         for pkesk in pkesks { // Try each PKESK until we succeed.
    ///             for ka in self.key.keys().with_policy(p, None)
    ///                 .supported().unencrypted_secret()
    ///                 .key_handle(pkesk.recipient())
    ///                 .for_storage_encryption().for_transport_encryption()
    ///             {
    ///                 let mut pair = ka.key().clone().into_keypair().unwrap();
    ///                 if pkesk.decrypt(&mut pair, sym_algo)
    ///                     .map(|(algo, session_key)| {
    ///                         let success = decrypt(algo, &session_key);
    ///                         if success {
    ///                             // Copy algor, session key, and PKESKs.
    ///                             encryption_context =
    ///                                 Some((algo, session_key.clone(),
    ///                                       pkesks.iter().cloned().collect()));
    ///                         }
    ///                         success
    ///                     })
    ///                     .unwrap_or(false)
    ///                 {
    ///                     break; // Decryption successful.
    ///                 }
    ///             }
    ///         }
    ///
    ///         self.recycling_bin = encryption_context; // Store for the reply.
    ///         Ok(Some(self.key.fingerprint()))
    ///     }
    /// }
    ///
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new()) // Lookup certificates here.
    /// #   }
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(()) // Implement your verification policy here.
    /// #   }
    /// }
    /// # Ok(()) }
    /// ```
    pub fn with_session_key(inner: Message<'a>,
                            sym_algo: SymmetricAlgorithm,
                            session_key: SessionKey)
                            -> Result<Self>
    {
        let sym_key_size = sym_algo.key_size()?;
        if session_key.len() != sym_key_size {
            return Err(Error::InvalidArgument(
                format!("{} requires a {} bit key, but session key has {}",
                        sym_algo, sym_key_size, session_key.len())).into());
        }

        Ok(Self {
            inner: inner.into(),
            session_key: Some(session_key),
            recipients: Vec::new(),
            passwords: Vec::with_capacity(0),
            sym_algo,
            aead_algo: Default::default(),
            hash: HashAlgorithm::SHA1.context().unwrap(),
            cookie: Default::default(), // Will be fixed in build.
        })
    }

    /// Adds recipients.
    ///
    /// The resulting message can be encrypted by any recipient and
    /// with any password.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      mQENBFpxtsABCADZcBa1Q3ZLZnju18o0+t8LoQuIIeyeUQ0H45y6xUqyrD5HSkVM
    /// #    VGQs6IHLq70mAizBJ4VznUVqVOh/NhOlapXi6/TKpjHvttdg45o6Pgqa0Kx64luT
    /// #    ZY+TEKyILcdBdhr3CzsEILnQst5jadgMvU9fnT/EkJIvxtWPlUzU5R7nnALO626x
    /// #    2M5Pj3k0h3ZNHMmYQQtReX/RP/xUh2SfOYG6i/MCclIlee8BXHB9k0bW2NAX2W7H
    /// #    rLDGPm1LzmyqxFGDvDvfPlYZ5nN2cbGsv3w75LDzv75kMhVnkZsrUjnHjVRzFq7q
    /// #    fSIpxlvJMEMKSIJ/TFztQoOBO5OlBb5qzYPpABEBAAG0F+G8iM+BzrnPg8+Ezr/P
    /// #    hM6tzrvOt8+CiQFUBBMBCAA+FiEEfcpYtU6xQxad3uFfJH9tq8hJFP4FAlpxtsAC
    /// #    GwMFCQPCZwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQJH9tq8hJFP49hgf+
    /// #    IKvec0RkD9EHSLFc6AKDm/knaI4AIH0isZTz9jRCF8H/j3h8QVUE+/0jtCcyvR6F
    /// #    TGVSfO3pelDPYGIjDFI3aA6H/UlhZWzYRXZ+QQRrV0zwvLna3XjiW8ib3Ky+5bpQ
    /// #    0uVeee30u+U3SnaCL9QB4+UvwVvAxRuk49Z0Q8TsRrQyQNYpeZDN7uNrvA134cf6
    /// #    6pLUvzPG4lMLIvSXFuHou704EhT7NS3wAzFtjMrsLLieVqtbEi/kBaJTQSZQwjVB
    /// #    sE/Z8lp1heKw/33Br3cB63n4cTf0FdoFywDBhCAMU7fKboU5xBpm5bQJ4ck6j6w+
    /// #    BKG1FiQRR6PCUeb6GjxVOrkBDQRacbbAAQgAw538MMb/pRdpt7PTgBCedw+rU9fh
    /// #    onZYKwmCO7wz5VrVf8zIVvWKxhX6fBTSAy8mxaYbeL/3woQ9Leuo8f0PQNs9zw1N
    /// #    mdH+cnm2KQmL9l7/HQKMLgEAu/0C/q7ii/j8OMYitaMUyrwy+OzW3nCal/uJHIfj
    /// #    bdKx29MbKgF/zaBs8mhTvf/Tu0rIVNDPEicwijDEolGSGebZxdGdHJA31uayMHDK
    /// #    /mwySJViMZ8b+Lzc/dRgNbQoY6yjsjso7U9OZpQK1fooHOSQS6iLsSSsZLcGPD+7
    /// #    m7j3jwq68SIJPMsu0O8hdjFWL4Cfj815CwptAxRGkp00CIusAabO7m8DzwARAQAB
    /// #    iQE2BBgBCAAgFiEEfcpYtU6xQxad3uFfJH9tq8hJFP4FAlpxtsACGwwACgkQJH9t
    /// #    q8hJFP5rmQgAoYOUXolTiQmWipJTdMG/VZ5X7mL8JiBWAQ11K1o01cZCMlziyHnJ
    /// #    xJ6Mqjb6wAFpYBtqysJG/vfjc/XEoKgfFs7+zcuEnt41xJQ6tl/L0VTxs+tEwjZu
    /// #    Rp/owB9GCkqN9+xNEnlH77TLW1UisW+l0F8CJ2WFOj4lk9rcXcLlEdGmXfWIlVCb
    /// #    2/o0DD+HDNsF8nWHpDEy0mcajkgIUTvXQaDXKbccX6Wgep8dyBP7YucGmRPd9Z6H
    /// #    bGeT3KvlJlH5kthQ9shsmT14gYwGMR6rKpNUXmlpetkjqUK7pGVaHGgJWUZ9QPGU
    /// #    awwPdWWvZSyXJAPZ9lC5sTKwMJDwIxILug==
    /// #    =lAie
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption();
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message =
    ///     Encryptor::with_passwords(message, Some("совершенно секретно"))
    ///     .add_recipients(recipients)
    ///     .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn add_recipients<R>(mut self, recipients: R) -> Self
        where R: IntoIterator,
              R::Item: Into<Recipient<'a>>,
    {
        for r in recipients {
            self.recipients.push(r.into());
        }
        self
    }

    /// Adds passwords to encrypt with.
    ///
    /// The resulting message can be encrypted with any password and
    /// by any recipient.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    /// use openpgp::policy::StandardPolicy;
    /// # use openpgp::parse::Parse;
    /// let p = &StandardPolicy::new();
    ///
    /// let cert = Cert::from_bytes(
    /// #   // We do some acrobatics here to abbreviate the Cert.
    ///     "-----BEGIN PGP PUBLIC KEY BLOCK-----
    ///
    ///      mQENBFpxtsABCADZcBa1Q3ZLZnju18o0+t8LoQuIIeyeUQ0H45y6xUqyrD5HSkVM
    /// #    VGQs6IHLq70mAizBJ4VznUVqVOh/NhOlapXi6/TKpjHvttdg45o6Pgqa0Kx64luT
    /// #    ZY+TEKyILcdBdhr3CzsEILnQst5jadgMvU9fnT/EkJIvxtWPlUzU5R7nnALO626x
    /// #    2M5Pj3k0h3ZNHMmYQQtReX/RP/xUh2SfOYG6i/MCclIlee8BXHB9k0bW2NAX2W7H
    /// #    rLDGPm1LzmyqxFGDvDvfPlYZ5nN2cbGsv3w75LDzv75kMhVnkZsrUjnHjVRzFq7q
    /// #    fSIpxlvJMEMKSIJ/TFztQoOBO5OlBb5qzYPpABEBAAG0F+G8iM+BzrnPg8+Ezr/P
    /// #    hM6tzrvOt8+CiQFUBBMBCAA+FiEEfcpYtU6xQxad3uFfJH9tq8hJFP4FAlpxtsAC
    /// #    GwMFCQPCZwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQJH9tq8hJFP49hgf+
    /// #    IKvec0RkD9EHSLFc6AKDm/knaI4AIH0isZTz9jRCF8H/j3h8QVUE+/0jtCcyvR6F
    /// #    TGVSfO3pelDPYGIjDFI3aA6H/UlhZWzYRXZ+QQRrV0zwvLna3XjiW8ib3Ky+5bpQ
    /// #    0uVeee30u+U3SnaCL9QB4+UvwVvAxRuk49Z0Q8TsRrQyQNYpeZDN7uNrvA134cf6
    /// #    6pLUvzPG4lMLIvSXFuHou704EhT7NS3wAzFtjMrsLLieVqtbEi/kBaJTQSZQwjVB
    /// #    sE/Z8lp1heKw/33Br3cB63n4cTf0FdoFywDBhCAMU7fKboU5xBpm5bQJ4ck6j6w+
    /// #    BKG1FiQRR6PCUeb6GjxVOrkBDQRacbbAAQgAw538MMb/pRdpt7PTgBCedw+rU9fh
    /// #    onZYKwmCO7wz5VrVf8zIVvWKxhX6fBTSAy8mxaYbeL/3woQ9Leuo8f0PQNs9zw1N
    /// #    mdH+cnm2KQmL9l7/HQKMLgEAu/0C/q7ii/j8OMYitaMUyrwy+OzW3nCal/uJHIfj
    /// #    bdKx29MbKgF/zaBs8mhTvf/Tu0rIVNDPEicwijDEolGSGebZxdGdHJA31uayMHDK
    /// #    /mwySJViMZ8b+Lzc/dRgNbQoY6yjsjso7U9OZpQK1fooHOSQS6iLsSSsZLcGPD+7
    /// #    m7j3jwq68SIJPMsu0O8hdjFWL4Cfj815CwptAxRGkp00CIusAabO7m8DzwARAQAB
    /// #    iQE2BBgBCAAgFiEEfcpYtU6xQxad3uFfJH9tq8hJFP4FAlpxtsACGwwACgkQJH9t
    /// #    q8hJFP5rmQgAoYOUXolTiQmWipJTdMG/VZ5X7mL8JiBWAQ11K1o01cZCMlziyHnJ
    /// #    xJ6Mqjb6wAFpYBtqysJG/vfjc/XEoKgfFs7+zcuEnt41xJQ6tl/L0VTxs+tEwjZu
    /// #    Rp/owB9GCkqN9+xNEnlH77TLW1UisW+l0F8CJ2WFOj4lk9rcXcLlEdGmXfWIlVCb
    /// #    2/o0DD+HDNsF8nWHpDEy0mcajkgIUTvXQaDXKbccX6Wgep8dyBP7YucGmRPd9Z6H
    /// #    bGeT3KvlJlH5kthQ9shsmT14gYwGMR6rKpNUXmlpetkjqUK7pGVaHGgJWUZ9QPGU
    /// #    awwPdWWvZSyXJAPZ9lC5sTKwMJDwIxILug==
    /// #    =lAie
    /// #    -----END PGP PUBLIC KEY BLOCK-----"
    /// #    /*
    ///      ...
    ///      -----END PGP PUBLIC KEY BLOCK-----"
    /// #    */
    /// )?;
    ///
    /// let recipients =
    ///     cert.keys().with_policy(p, None).supported().alive().revoked(false)
    ///     // Or `for_storage_encryption()`, for data at rest.
    ///     .for_transport_encryption();
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message =
    ///     Encryptor::for_recipients(message, recipients)
    ///         .add_passwords(Some("совершенно секретно"))
    ///         .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn add_passwords<P>(mut self, passwords: P) -> Self
        where P: IntoIterator,
              P::Item: Into<Password>,
    {
        for p in passwords {
            self.passwords.push(p.into());
        }
        self
    }

    /// Sets the symmetric algorithm to use.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::SymmetricAlgorithm;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message =
    ///     Encryptor::with_passwords(message, Some("совершенно секретно"))
    ///         .symmetric_algo(SymmetricAlgorithm::AES128)
    ///         .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn symmetric_algo(mut self, algo: SymmetricAlgorithm) -> Self {
        self.sym_algo = algo;
        self
    }

    /// Enables AEAD and sets the AEAD algorithm to use.
    ///
    /// This feature is [experimental](super::super#experimental-features).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::types::AEADAlgorithm;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message =
    ///     Encryptor::with_passwords(message, Some("совершенно секретно"))
    ///         .aead_algo(AEADAlgorithm::default())
    ///         .build()?;
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    // Function hidden from the public API due to
    // https://gitlab.com/sequoia-pgp/sequoia/-/issues/550
    // It is used only for tests so that it does not bit-rot.
    #[cfg(test)]
    pub fn aead_algo(mut self, algo: AEADAlgorithm) -> Self {
        self.aead_algo = Some(algo);
        self
    }

    // The default chunk size.
    //
    // A page, 3 per mille overhead.
    const AEAD_CHUNK_SIZE : usize = 4096;

    /// Builds the encryptor, returning the writer stack.
    ///
    /// The most useful filters to push to the writer stack next are
    /// the [`Padder`] or [`Compressor`], and after that the
    /// [`Signer`].  Finally, literal data *must* be wrapped using the
    /// [`LiteralWriter`].
    ///
    ///   [`Padder`]: padding::Padder
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::Write;
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::serialize::stream::{
    ///     Message, Encryptor, LiteralWriter,
    /// };
    ///
    /// # let mut sink = vec![];
    /// let message = Message::new(&mut sink);
    /// let message =
    ///     Encryptor::with_passwords(message, Some("совершенно секретно"))
    ///         // Customize the `Encryptor` here.
    ///         .build()?;
    ///
    /// // Optionally add a `Padder` or `Compressor` here.
    /// // Optionally add a `Signer` here.
    ///
    /// let mut message = LiteralWriter::new(message).build()?;
    /// message.write_all(b"Hello world.")?;
    /// message.finalize()?;
    /// # Ok(()) }
    /// ```
    pub fn build(mut self) -> Result<Message<'a>> {
        if self.recipients.len() + self.passwords.len() == 0
            && self.session_key.is_none()
        {
            return Err(Error::InvalidOperation(
                "Neither recipients, passwords, nor session key given".into()
            ).into());
        }

        struct AEADParameters {
            algo: AEADAlgorithm,
            chunk_size: usize,
            nonce: Box<[u8]>,
        }

        let aead = if let Some(algo) = self.aead_algo {
            let mut nonce = vec![0; algo.nonce_size()?];
            crypto::random(&mut nonce);
            Some(AEADParameters {
                algo,
                chunk_size: Self::AEAD_CHUNK_SIZE,
                nonce: nonce.into_boxed_slice(),
            })
        } else {
            None
        };

        let mut inner = self.inner;
        let level = inner.as_ref().cookie_ref().level + 1;

        // Reuse existing session key or generate a new one.
        let sym_key_size = self.sym_algo.key_size()?;
        let sk = self.session_key.take()
            .unwrap_or_else(|| SessionKey::new(sym_key_size));
        if sk.len() != sym_key_size {
            return Err(Error::InvalidOperation(
                format!("{} requires a {} bit key, but session key has {}",
                        self.sym_algo, sym_key_size, sk.len())).into());
        }

        // Write the PKESK packet(s).
        for recipient in self.recipients.iter() {
            let mut pkesk =
                PKESK3::for_recipient(self.sym_algo, &sk, recipient.key)?;
            pkesk.set_recipient(recipient.keyid.clone());
            Packet::PKESK(pkesk.into()).serialize(&mut inner)?;
        }

        // Write the SKESK packet(s).
        for password in self.passwords.iter() {
            if let Some(aead) = aead.as_ref() {
                let skesk = SKESK5::with_password(self.sym_algo,
                                                  self.sym_algo,
                                                  aead.algo,
                                                  Default::default(),
                                                  &sk, password).unwrap();
                Packet::SKESK(skesk.into()).serialize(&mut inner)?;
            } else {
                let skesk = SKESK4::with_password(self.sym_algo,
                                                  self.sym_algo,
                                                  Default::default(),
                                                  &sk, password).unwrap();
                Packet::SKESK(skesk.into()).serialize(&mut inner)?;
            }
        }

        if let Some(aead) = aead {
            // Write the AED packet.
            CTB::new(Tag::AED).serialize(&mut inner)?;
            let mut inner = PartialBodyFilter::new(Message::from(inner),
                                                   Cookie::new(level));
            let aed = AED1::new(self.sym_algo, aead.algo,
                                aead.chunk_size as u64, aead.nonce)?;
            aed.serialize_headers(&mut inner)?;

            use crate::crypto::aead::AEDv1Schedule;
            let schedule = AEDv1Schedule::new(
                aed.symmetric_algo(), aed.aead(), aead.chunk_size, aed.iv())?;

            writer::AEADEncryptor::new(
                inner,
                Cookie::new(level),
                aed.symmetric_algo(),
                aed.aead(),
                aead.chunk_size,
                schedule,
                sk,
            )
        } else {
            // Write the SEIP packet.
            CTB::new(Tag::SEIP).serialize(&mut inner)?;
            let mut inner = PartialBodyFilter::new(Message::from(inner),
                                                   Cookie::new(level));
            inner.write_all(&[1])?; // Version.

            // Install encryptor.
            self.inner = writer::Encryptor::new(
                inner,
                Cookie::new(level),
                self.sym_algo,
                &sk,
            )?.into();
            self.cookie = Cookie::new(level);

            // Write the initialization vector, and the quick-check
            // bytes.  The hash for the MDC must include the
            // initialization vector, hence we must write this to
            // self after installing the encryptor at self.inner.
            let mut iv = vec![0; self.sym_algo.block_size()?];
            crypto::random(&mut iv);
            self.write_all(&iv)?;
            self.write_all(&iv[iv.len() - 2..])?;

            Ok(Message::from(Box::new(self)))
        }
    }

    /// Emits the MDC packet and recovers the original writer.
    fn emit_mdc(mut self) -> Result<writer::BoxStack<'a, Cookie>> {
        let mut w = self.inner;

        // Write the MDC, which must be the last packet inside the
        // encrypted packet stream.  The hash includes the MDC's
        // CTB and length octet.
        let mut header = Vec::new();
        CTB::new(Tag::MDC).serialize(&mut header)?;
        BodyLength::Full(20).serialize(&mut header)?;

        self.hash.update(&header);
        #[allow(deprecated)]
        Packet::MDC(MDC::from(self.hash.clone())).serialize(&mut w)?;

        // Now recover the original writer.  First, strip the
        // Encryptor.
        let w = w.into_inner()?.unwrap();
        // And the partial body filter.
        let w = w.into_inner()?.unwrap();

        Ok(w)
    }
}

impl<'a> fmt::Debug for Encryptor<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Encryptor")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<'a> Write for Encryptor<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = self.inner.write(buf);
        if let Ok(amount) = written {
            self.hash.update(&buf[..amount]);
        }
        written
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl<'a> writer::Stackable<'a, Cookie> for Encryptor<'a> {
    fn pop(&mut self) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        unreachable!("Only implemented by Signer")
    }
    /// Sets the inner stackable.
    fn mount(&mut self, _new: writer::BoxStack<'a, Cookie>) {
        unreachable!("Only implemented by Signer")
    }
    fn inner_ref(&self) -> Option<&(dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(&self.inner)
    }
    fn inner_mut(&mut self) -> Option<&mut (dyn writer::Stackable<'a, Cookie> + Send + Sync)> {
        Some(&mut self.inner)
    }
    fn into_inner(self: Box<Self>) -> Result<Option<writer::BoxStack<'a, Cookie>>> {
        Ok(Some(self.emit_mdc()?))
    }
    fn cookie_set(&mut self, cookie: Cookie) -> Cookie {
        ::std::mem::replace(&mut self.cookie, cookie)
    }
    fn cookie_ref(&self) -> &Cookie {
        &self.cookie
    }
    fn cookie_mut(&mut self) -> &mut Cookie {
        &mut self.cookie
    }
    fn position(&self) -> u64 {
        self.inner.position()
    }
}

#[cfg(test)]
mod test {
    use std::io::Read;
    use crate::{Packet, PacketPile, packet::CompressedData};
    use crate::parse::{Parse, PacketParserResult, PacketParser};
    use super::*;
    use crate::types::DataFormat::Text as T;
    use crate::policy::Policy;
    use crate::policy::StandardPolicy as P;

    #[test]
    fn arbitrary() {
        let mut o = vec![];
        {
            let m = Message::new(&mut o);
            let mut ustr = ArbitraryWriter::new(m, Tag::Literal).unwrap();
            ustr.write_all(b"t").unwrap(); // type
            ustr.write_all(b"\x00").unwrap(); // fn length
            ustr.write_all(b"\x00\x00\x00\x00").unwrap(); // date
            ustr.write_all(b"Hello world.").unwrap(); // body
            ustr.finalize().unwrap();
        }

        let mut pp = PacketParser::from_bytes(&o).unwrap().unwrap();
        if let Packet::Literal(ref l) = pp.packet {
                assert_eq!(l.format(), DataFormat::Text);
                assert_eq!(l.filename(), None);
                assert_eq!(l.date(), None);
        } else {
            panic!("Unexpected packet type.");
        }

        let mut body = vec![];
        pp.read_to_end(&mut body).unwrap();
        assert_eq!(&body, b"Hello world.");

        // Make sure it is the only packet.
        let (_, ppr) = pp.recurse().unwrap();
        assert!(ppr.is_eof());
    }

    // Create some crazy nesting structures, serialize the messages,
    // reparse them, and make sure we get the same result.
    #[test]
    fn stream_0() {
        // 1: CompressedData(CompressedData { algo: 0 })
        //  1: Literal(Literal { body: "one (3 bytes)" })
        //  2: Literal(Literal { body: "two (3 bytes)" })
        // 2: Literal(Literal { body: "three (5 bytes)" })
        let mut one = Literal::new(T);
        one.set_body(b"one".to_vec());
        let mut two = Literal::new(T);
        two.set_body(b"two".to_vec());
        let mut three = Literal::new(T);
        three.set_body(b"three".to_vec());
        let mut reference = Vec::new();
        reference.push(
            CompressedData::new(CompressionAlgorithm::Uncompressed)
                .push(one.into())
                .push(two.into())
                .into());
        reference.push(three.into());

        let mut o = vec![];
        {
            let m = Message::new(&mut o);
            let c = Compressor::new(m)
                .algo(CompressionAlgorithm::Uncompressed).build().unwrap();
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "one").unwrap();
            let c = ls.finalize_one().unwrap().unwrap(); // Pop the LiteralWriter.
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "two").unwrap();
            let c = ls.finalize_one().unwrap().unwrap(); // Pop the LiteralWriter.
            let c = c.finalize_one().unwrap().unwrap(); // Pop the Compressor.
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "three").unwrap();
            ls.finalize().unwrap();
        }

        let pile = PacketPile::from(reference);
        let pile2 = PacketPile::from_bytes(&o).unwrap();
        if pile != pile2 {
            eprintln!("REFERENCE...");
            pile.pretty_print();
            eprintln!("REPARSED...");
            pile2.pretty_print();
            panic!("Reparsed packet does not match reference packet!");
        }
    }

    // Create some crazy nesting structures, serialize the messages,
    // reparse them, and make sure we get the same result.
    #[test]
    fn stream_1() {
        // 1: CompressedData(CompressedData { algo: 0 })
        //  1: CompressedData(CompressedData { algo: 0 })
        //   1: Literal(Literal { body: "one (3 bytes)" })
        //   2: Literal(Literal { body: "two (3 bytes)" })
        //  2: CompressedData(CompressedData { algo: 0 })
        //   1: Literal(Literal { body: "three (5 bytes)" })
        //   2: Literal(Literal { body: "four (4 bytes)" })
        let mut one = Literal::new(T);
        one.set_body(b"one".to_vec());
        let mut two = Literal::new(T);
        two.set_body(b"two".to_vec());
        let mut three = Literal::new(T);
        three.set_body(b"three".to_vec());
        let mut four = Literal::new(T);
        four.set_body(b"four".to_vec());
        let mut reference = Vec::new();
        reference.push(
            CompressedData::new(CompressionAlgorithm::Uncompressed)
                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
                      .push(one.into())
                      .push(two.into())
                      .into())
                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
                      .push(three.into())
                      .push(four.into())
                      .into())
                .into());

        let mut o = vec![];
        {
            let m = Message::new(&mut o);
            let c0 = Compressor::new(m)
                .algo(CompressionAlgorithm::Uncompressed).build().unwrap();
            let c = Compressor::new(c0)
                .algo(CompressionAlgorithm::Uncompressed).build().unwrap();
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "one").unwrap();
            let c = ls.finalize_one().unwrap().unwrap();
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "two").unwrap();
            let c = ls.finalize_one().unwrap().unwrap();
            let c0 = c.finalize_one().unwrap().unwrap();
            let c = Compressor::new(c0)
                .algo(CompressionAlgorithm::Uncompressed).build().unwrap();
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "three").unwrap();
            let c = ls.finalize_one().unwrap().unwrap();
            let mut ls = LiteralWriter::new(c).format(T).build().unwrap();
            write!(ls, "four").unwrap();
            ls.finalize().unwrap();
        }

        let pile = PacketPile::from(reference);
        let pile2 = PacketPile::from_bytes(&o).unwrap();
        if pile != pile2 {
            eprintln!("REFERENCE...");
            pile.pretty_print();
            eprintln!("REPARSED...");
            pile2.pretty_print();
            panic!("Reparsed packet does not match reference packet!");
        }
    }

    #[cfg(feature = "compression-bzip2")]
    #[test]
    fn stream_big() {
        let zeros = vec![0; 1024 * 1024 * 4];
        let mut o = vec![];
        {
            let m = Message::new(&mut o);
            let c = Compressor::new(m)
                .algo(CompressionAlgorithm::BZip2).build().unwrap();
            let mut ls = LiteralWriter::new(c).build().unwrap();
            // Write 64 megabytes of zeroes.
            for _ in 0 .. 16 {
                ls.write_all(&zeros).unwrap();
            }
        }
        assert!(o.len() < 1024);
    }

    #[test]
    fn signature() {
        let p = &P::new();
        use crate::crypto::KeyPair;
        use std::collections::HashMap;
        use crate::Fingerprint;

        let mut keys: HashMap<Fingerprint, key::UnspecifiedPublic> = HashMap::new();
        for tsk in &[
            Cert::from_bytes(crate::tests::key("testy-private.pgp")).unwrap(),
            Cert::from_bytes(crate::tests::key("testy-new-private.pgp")).unwrap(),
        ] {
            for key in tsk.keys().with_policy(p, crate::frozen_time())
                .for_signing().map(|ka| ka.key())
            {
                keys.insert(key.fingerprint(), key.clone());
            }
        }

        let mut o = vec![];
        {
            let mut signers = keys.iter().map(|(_, key)| {
                key.clone().parts_into_secret().unwrap().into_keypair()
                    .expect("expected unencrypted secret key")
            }).collect::<Vec<KeyPair>>();

            let m = Message::new(&mut o);
            let mut signer = Signer::new(m, signers.pop().unwrap());
            for s in signers.into_iter() {
                signer = signer.add_signer(s);
            }
            let signer = signer.build().unwrap();
            let mut ls = LiteralWriter::new(signer).build().unwrap();
            ls.write_all(b"Tis, tis, tis.  Tis is important.").unwrap();
            let _ = ls.finalize().unwrap();
        }

        let mut ppr = PacketParser::from_bytes(&o).unwrap();
        let mut good = 0;
        while let PacketParserResult::Some(mut pp) = ppr {
            if let Packet::Signature(sig) = &mut pp.packet {
                let key = keys.get(sig.issuer_fingerprints().next().unwrap())
                    .unwrap();
                sig.verify(key).unwrap();
                good += 1;
            }

            // Get the next packet.
            ppr = pp.recurse().unwrap().1;
        }
        assert_eq!(good, 2);
    }

    #[test]
    fn encryptor() {
        let passwords = vec!["streng geheim".into(),
                             "top secret".into()];
        let message = b"Hello world.";

        // Write a simple encrypted message...
        let mut o = vec![];
        {
            let m = Message::new(&mut o);
            let encryptor = Encryptor::with_passwords(m, passwords.clone())
                .build().unwrap();
            let mut literal = LiteralWriter::new(encryptor).build()
                .unwrap();
            literal.write_all(message).unwrap();
            literal.finalize().unwrap();
        }

        // ... and recover it...
        #[derive(Debug, PartialEq)]
        enum State {
            Start,
            Decrypted(Vec<(SymmetricAlgorithm, SessionKey)>),
            Deciphered,
            MDC,
            Done,
        }

        // ... with every password.
        for password in &passwords {
            let mut state = State::Start;
            let mut ppr = PacketParser::from_bytes(&o).unwrap();
            while let PacketParserResult::Some(mut pp) = ppr {
                state = match state {
                    // Look for the SKESK packet.
                    State::Start =>
                        if let Packet::SKESK(ref skesk) = pp.packet {
                            match skesk.decrypt(password) {
                                Ok((algo, key))
                                    => State::Decrypted(
                                        vec![(algo, key)]),
                                Err(e) =>
                                    panic!("Decryption failed: {}", e),
                            }
                        } else {
                            panic!("Unexpected packet: {:?}", pp.packet)
                        },

                    // Look for the SEIP packet.
                    State::Decrypted(mut keys) =>
                        match pp.packet {
                            Packet::SEIP(_) =>
                                loop {
                                    if let Some((algo, key)) = keys.pop() {
                                        let r = pp.decrypt(algo, &key);
                                        if r.is_ok() {
                                            break State::Deciphered;
                                        }
                                    } else {
                                        panic!("seip decryption failed");
                                    }
                                },
                            Packet::SKESK(ref skesk) =>
                                match skesk.decrypt(password) {
                                    Ok((algo, key)) => {
                                        keys.push((algo, key));
                                        State::Decrypted(keys)
                                    },
                                    Err(e) =>
                                        panic!("Decryption failed: {}", e),
                                },
                            _ =>
                                panic!("Unexpected packet: {:?}", pp.packet),
                        },

                    // Look for the literal data packet.
                    State::Deciphered =>
                        if let Packet::Literal(_) = pp.packet {
                            let mut body = Vec::new();
                            pp.read_to_end(&mut body).unwrap();
                            assert_eq!(&body, message);
                            State::MDC
                        } else {
                            panic!("Unexpected packet: {:?}", pp.packet)
                        },

                    // Look for the MDC packet.
                    #[allow(deprecated)]
                    State::MDC =>
                        if let Packet::MDC(ref mdc) = pp.packet {
                            assert_eq!(mdc.digest(), mdc.computed_digest());
                            State::Done
                        } else {
                            panic!("Unexpected packet: {:?}", pp.packet)
                        },

                    State::Done =>
                        panic!("Unexpected packet: {:?}", pp.packet),
                };

                // Next?
                ppr = pp.recurse().unwrap().1;
            }
            assert_eq!(state, State::Done);
        }
    }

    #[test]
    fn aead_eax() -> Result<()> {
        test_aead_messages(AEADAlgorithm::EAX)
    }

    #[test]
    fn aead_ocb() -> Result<()> {
        test_aead_messages(AEADAlgorithm::OCB)
    }

    #[test]
    fn aead_gcm() -> Result<()> {
        test_aead_messages(AEADAlgorithm::GCM)
    }

    fn test_aead_messages(algo: AEADAlgorithm) -> Result<()> {
        if ! algo.is_supported() {
            eprintln!("Skipping because {} is not supported.", algo);
            return Ok(());
        }

        // AEAD data is of the form:
        //
        //   [ chunk1 ][ tag1 ] ... [ chunkN ][ tagN ][ tag ]
        //
        // All chunks are the same size except for the last chunk, which may
        // be shorter.
        //
        // In `Decryptor::read_helper`, we read a chunk and a tag worth of
        // data at a time.  Because only the last chunk can be shorter, if
        // the amount read is less than `chunk_size + tag_size`, then we know
        // that we've read the last chunk.
        //
        // Unfortunately, this is not sufficient: if the last chunk is
        // `chunk_size - tag size` bytes large, then when we read it, we'll
        // read `chunk_size + tag_size` bytes, because we'll have also read
        // the final tag!
        //
        // Make sure we handle this situation correctly.

        use std::cmp;

        use crate::parse::{
            stream::{
                DecryptorBuilder,
                DecryptionHelper,
                VerificationHelper,
                MessageStructure,
            },
        };
        use crate::cert::prelude::*;

        let (tsk, _) = CertBuilder::new()
            .set_cipher_suite(CipherSuite::Cv25519)
            .add_transport_encryption_subkey()
            .generate().unwrap();

        struct Helper<'a> {
            policy: &'a dyn Policy,
            tsk: &'a Cert,
        }
        impl<'a> VerificationHelper for Helper<'a> {
            fn get_certs(&mut self, _ids: &[crate::KeyHandle])
                               -> Result<Vec<Cert>> {
                Ok(Vec::new())
            }
            fn check(&mut self, _structure: MessageStructure) -> Result<()> {
                Ok(())
            }
            fn inspect(&mut self, pp: &PacketParser<'_>) -> Result<()> {
                assert!(! matches!(&pp.packet, Packet::Unknown(_)));
                eprintln!("Parsed {:?}", pp.packet);
                Ok(())
            }
        }
        impl<'a> DecryptionHelper for Helper<'a> {
            fn decrypt<D>(&mut self, pkesks: &[PKESK], _skesks: &[SKESK],
                          sym_algo: Option<SymmetricAlgorithm>,
                          mut decrypt: D) -> Result<Option<crate::Fingerprint>>
                where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
            {
                let mut keypair = self.tsk.keys().with_policy(self.policy, None)
                    .for_transport_encryption()
                    .map(|ka| ka.key()).next().unwrap()
                    .clone().parts_into_secret().unwrap()
                    .into_keypair().unwrap();
                pkesks[0].decrypt(&mut keypair, sym_algo)
                    .map(|(algo, session_key)| decrypt(algo, &session_key));
                Ok(None)
            }
        }

        let p = &P::new();

        for chunks in 0..3 {
            for msg_len in
                      cmp::max(24, chunks * Encryptor::AEAD_CHUNK_SIZE) - 24
                          ..chunks * Encryptor::AEAD_CHUNK_SIZE + 24
            {
                eprintln!("Encrypting message of size: {}", msg_len);

                let mut content : Vec<u8> = Vec::new();
                for i in 0..msg_len {
                    content.push(b'0' + ((i % 10) as u8));
                }

                let mut msg = vec![];
                {
                    let m = Message::new(&mut msg);
                    let recipients = tsk
                        .keys().with_policy(p, None)
                        .for_storage_encryption().for_transport_encryption();
                    let encryptor = Encryptor::for_recipients(m, recipients)
                        .aead_algo(algo)
                        .build().unwrap();
                    let mut literal = LiteralWriter::new(encryptor).build()
                        .unwrap();
                    literal.write_all(&content).unwrap();
                    literal.finalize().unwrap();
                }

                for &read_len in &[
                    37,
                    Encryptor::AEAD_CHUNK_SIZE - 1,
                    Encryptor::AEAD_CHUNK_SIZE,
                    100 * Encryptor::AEAD_CHUNK_SIZE
                ] {
                    for &do_err in &[ false, true ] {
                        let mut msg = msg.clone();
                        if do_err {
                            let l = msg.len() - 1;
                            if msg[l] == 0 {
                                msg[l] = 1;
                            } else {
                                msg[l] = 0;
                            }
                        }

                        let h = Helper { policy: p, tsk: &tsk };
                        // Note: a corrupted message is only guaranteed
                        // to error out before it returns EOF.
                        let mut v = match DecryptorBuilder::from_bytes(&msg)?
                            .with_policy(p, None, h)
                        {
                            Ok(v) => v,
                            Err(_) if do_err => continue,
                            Err(err) => panic!("Decrypting message: {}", err),
                        };

                        let mut buffer = Vec::new();
                        buffer.resize(read_len, 0);

                        let mut decrypted_content = Vec::new();
                        loop {
                            match v.read(&mut buffer[..read_len]) {
                                Ok(0) if do_err =>
                                    panic!("Expected an error, got EOF"),
                                Ok(0) => break,
                                Ok(len) =>
                                    decrypted_content.extend_from_slice(
                                        &buffer[..len]),
                                Err(_) if do_err => break,
                                Err(err) =>
                                    panic!("Decrypting data: {:?}", err),
                            }
                        }

                        if do_err {
                            // If we get an error once, we should get
                            // one again.
                            for _ in 0..3 {
                                assert!(v.read(&mut buffer[..read_len]).is_err());
                            }
                        }

                        // We only corrupted the final tag, so we
                        // should get all of the content.
                        assert_eq!(msg_len, decrypted_content.len());
                        assert_eq!(content, decrypted_content);
                    }
                }
            }
        }
        Ok(())
    }

    #[test]
    fn signature_at_time() {
        // Generates a signature with a specific Signature Creation
        // Time.
        use crate::cert::prelude::*;
        use crate::serialize::stream::{LiteralWriter, Message};
        use crate::crypto::KeyPair;

        let p = &P::new();

        let (cert, _) = CertBuilder::new()
            .add_signing_subkey()
            .set_cipher_suite(CipherSuite::Cv25519)
            .generate().unwrap();

        // What we're going to sign with.
        let ka = cert.keys().with_policy(p, None).for_signing().next().unwrap();

        // A timestamp later than the key's creation.
        let timestamp = ka.key().creation_time()
            + std::time::Duration::from_secs(14 * 24 * 60 * 60);
        assert!(ka.key().creation_time() < timestamp);

        let mut o = vec![];
        {
            let signer_keypair : KeyPair =
                ka.key().clone().parts_into_secret().unwrap().into_keypair()
                    .expect("expected unencrypted secret key");

            let m = Message::new(&mut o);
            let signer = Signer::new(m, signer_keypair);
            let signer = signer.creation_time(timestamp);
            let signer = signer.build().unwrap();

            let mut ls = LiteralWriter::new(signer).build().unwrap();
            ls.write_all(b"Tis, tis, tis.  Tis is important.").unwrap();
            let signer = ls.finalize_one().unwrap().unwrap();
            let _ = signer.finalize_one().unwrap().unwrap();
        }

        let mut ppr = PacketParser::from_bytes(&o).unwrap();
        let mut good = 0;
        while let PacketParserResult::Some(mut pp) = ppr {
            if let Packet::Signature(sig) = &mut pp.packet {
                assert_eq!(sig.signature_creation_time(), Some(timestamp));
                sig.verify(ka.key()).unwrap();
                good += 1;
            }

            // Get the next packet.
            ppr = pp.recurse().unwrap().1;
        }
        assert_eq!(good, 1);
    }

    /// Checks that newlines are properly normalized when verifying
    /// text signatures.
    #[test]
    fn issue_530_signing() -> Result<()> {
        use std::io::Write;
        use crate::*;
        use crate::packet::signature;
        use crate::serialize::stream::{Message, Signer};

        use crate::policy::StandardPolicy;
        use crate::{Result, Cert};
        use crate::parse::Parse;
        use crate::parse::stream::*;

        let normalized_data = b"one\r\ntwo\r\nthree";

        let p = &StandardPolicy::new();
        let cert: Cert =
            Cert::from_bytes(crate::tests::key("testy-new-private.pgp"))?;

        for data in &[
            &b"one\r\ntwo\r\nthree"[..], // dos
            b"one\ntwo\nthree",          // unix
            b"one\ntwo\r\nthree",        // mixed
            b"one\r\ntwo\nthree",
            b"one\rtwo\rthree",          // classic mac
        ] {
            eprintln!("{:?}", String::from_utf8(data.to_vec())?);
            let signing_keypair = cert.keys().secret()
                .with_policy(p, None).supported()
                .alive().revoked(false).for_signing().next().unwrap()
                .key().clone().into_keypair()?;
            let mut signature = vec![];
            {
                let message = Message::new(&mut signature);
                let mut message = Signer::with_template(
                    message, signing_keypair,
                    signature::SignatureBuilder::new(SignatureType::Text)
                ).detached().build()?;
                message.write_all(data)?;
                message.finalize()?;
            }

            struct Helper {}
            impl VerificationHelper for Helper {
                fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>>
                {
                    Ok(vec![
                        Cert::from_bytes(crate::tests::key("testy-new.pgp"))?])
                }
                fn check(&mut self, structure: MessageStructure) -> Result<()> {
                    for (i, layer) in structure.iter().enumerate() {
                        assert_eq!(i, 0);
                        if let MessageLayer::SignatureGroup { results } = layer
                        {
                            assert_eq!(results.len(), 1);
                            results[0].as_ref().unwrap();
                            assert!(results[0].is_ok());
                            return Ok(());
                        } else {
                            unreachable!();
                        }
                    }
                    unreachable!()
                }
            }

            let h = Helper {};
            let mut v = DetachedVerifierBuilder::from_bytes(&signature)?
                .with_policy(p, None, h)?;

            v.verify_bytes(data)?;
            v.verify_bytes(normalized_data)?;
        }

        Ok(())
    }

    struct BadSigner;

    impl crypto::Signer for BadSigner {
        fn public(&self) -> &Key<key::PublicParts, key::UnspecifiedRole> {
            panic!("public not impl")
        }

        /// Returns a list of hashes that this signer accepts.
        fn acceptable_hashes(&self) -> &[HashAlgorithm] {
            &[]
        }

        fn sign(&mut self, _hash_algo: HashAlgorithm, _digest: &[u8])
        -> Result<crypto::mpi::Signature> {
            panic!("sign not impl")
        }
    }

    struct GoodSigner(Vec<HashAlgorithm>, Key<key::PublicParts, key::UnspecifiedRole>);

    impl crypto::Signer for GoodSigner {
        fn public(&self) -> &Key<key::PublicParts, key::UnspecifiedRole> {
            &self.1
        }

        /// Returns a list of hashes that this signer accepts.
        fn acceptable_hashes(&self) -> &[HashAlgorithm] {
            &self.0
        }

        fn sign(&mut self, _hash_algo: HashAlgorithm, _digest: &[u8])
        -> Result<crypto::mpi::Signature> {
            unimplemented!()
        }
    }

    impl Default for GoodSigner {
        fn default() -> Self {
            let p = &P::new();

            let (cert, _) = CertBuilder::new().generate().unwrap();

            let ka = cert.keys().with_policy(p, None).next().unwrap();

            Self(vec![HashAlgorithm::default()], ka.key().clone())
        }
    }

    #[test]
    fn overlapping_hashes() {
        let mut signature = vec![];
        let message = Message::new(&mut signature);

        Signer::new(message, GoodSigner::default()).build().unwrap();
    }

    #[test]
    fn no_overlapping_hashes() {
        let mut signature = vec![];
        let message = Message::new(&mut signature);
        let signer = Signer::new(message, BadSigner);

        if let Err(e) = signer.build() {
            assert_eq!(e.downcast_ref::<Error>(), Some(&Error::NoAcceptableHash));
        } else {
            unreachable!();
        };
    }

    #[test]
    fn no_overlapping_hashes_for_new_signer() {
        let mut signature = vec![];
        let message = Message::new(&mut signature);

        let mut signer = Signer::new(message, GoodSigner::default());
        signer = signer.add_signer(BadSigner);

        if let Err(e) = signer.build() {
            assert_eq!(e.downcast_ref::<Error>(), Some(&Error::NoAcceptableHash));
        } else {
            unreachable!();
        };
    }

    /// Tests that multiple signatures are in the correct order.
    #[test]
    fn issue_816() -> Result<()> {
        use crate::{
            packet::key::{Key4, PrimaryRole},
            types::Curve,
            KeyHandle,
        };

        let signer_a =
            Key4::<_, PrimaryRole>::generate_ecc(true, Curve::Ed25519)?
            .into_keypair()?;

        let signer_b =
            Key4::<_, PrimaryRole>::generate_ecc(true, Curve::Ed25519)?
            .into_keypair()?;

        let mut sink = Vec::new();
        let message = Message::new(&mut sink);
        let message = Signer::new(message, signer_a)
            .add_signer(signer_b)
            .build()?;
        let mut message = LiteralWriter::new(message).build()?;
        message.write_all(b"Make it so, number one!")?;
        message.finalize()?;

        let pp = crate::PacketPile::from_bytes(&sink)?;
        assert_eq!(pp.children().count(), 5);

        let first_signer: KeyHandle =
            if let Packet::OnePassSig(ops) = pp.path_ref(&[0]).unwrap() {
                ops.issuer().into()
            } else {
                panic!("expected ops packet")
            };

        let second_signer: KeyHandle =
            if let Packet::OnePassSig(ops) = pp.path_ref(&[1]).unwrap() {
                ops.issuer().into()
            } else {
                panic!("expected ops packet")
            };

        assert!(matches!(pp.path_ref(&[2]).unwrap(), Packet::Literal(_)));

        // OPS and Signature packets "bracket" the literal, i.e. the
        // last occurring ops packet is met by the first occurring
        // signature packet.
        if let Packet::Signature(sig) = pp.path_ref(&[3]).unwrap() {
            assert!(sig.get_issuers()[0].aliases(&second_signer));
        } else {
            panic!("expected sig packet")
        }

        if let Packet::Signature(sig) = pp.path_ref(&[4]).unwrap() {
            assert!(sig.get_issuers()[0].aliases(&first_signer));
        } else {
            panic!("expected sig packet")
        }

        Ok(())
    }

    // Example copied from `Encryptor::aead_algo` and slightly
    // adjusted since the doctest from `Encryptor::aead_algo` does not
    // run.  Additionally this test case utilizes
    // `AEADAlgorithm::const_default` to detect which algorithm to
    // use.
    #[test]
    fn experimental_aead_encryptor() -> Result<()> {
        use std::io::Write;
        use crate::types::AEADAlgorithm;
        use crate::policy::StandardPolicy;
        use crate::serialize::stream::{
            Message, Encryptor, LiteralWriter,
        };
        use crate::parse::stream::{
            DecryptorBuilder, VerificationHelper,
            DecryptionHelper, MessageStructure,
        };

        let mut sink = vec![];
        let message = Message::new(&mut sink);
        let message =
          Encryptor::with_passwords(message, Some("совершенно секретно"))
              .aead_algo(AEADAlgorithm::const_default())
              .build()?;
        let mut message = LiteralWriter::new(message).build()?;
        message.write_all(b"Hello world.")?;
        message.finalize()?;

        struct Helper;

        impl VerificationHelper for Helper {
            fn get_certs(&mut self, _ids: &[crate::KeyHandle]) -> Result<Vec<Cert>> where {
                Ok(Vec::new())
            }

            fn check(&mut self, _structure: MessageStructure) -> Result<()> {
                Ok(())
            }
        }

        impl DecryptionHelper for Helper {
            fn decrypt<D>(&mut self, _: &[PKESK], skesks: &[SKESK],
                          _sym_algo: Option<SymmetricAlgorithm>,
                          mut decrypt: D) -> Result<Option<crate::Fingerprint>>
            where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
            {
                skesks[0].decrypt(&"совершенно секретно".into())
                    .map(|(algo, session_key)| decrypt(algo, &session_key))?;
                Ok(None)
            }
        }

        let p = &StandardPolicy::new();
        let mut v = DecryptorBuilder::from_bytes(&sink)?.with_policy(p, None, Helper)?;
        let mut content = vec![];
        v.read_to_end(&mut content)?;
        assert_eq!(content, b"Hello world.");
        Ok(())
    }

    /// Signs using our set of public keys.
    #[test]
    fn signer() -> Result<()> {
        use crate::policy::StandardPolicy;
        use crate::parse::stream::{
            VerifierBuilder,
            test::VHelper,
        };

        let p = StandardPolicy::new();
        for alg in &[
            "rsa", "dsa",
            "nistp256", "nistp384", "nistp521",
            "brainpoolP256r1", "brainpoolP384r1", "brainpoolP512r1",
            "secp256k1",
        ] {
            eprintln!("Test vector {:?}...", alg);
            let key = Cert::from_bytes(crate::tests::key(
                &format!("signing/{}.gpg", alg)))?;
            if let Some(k) = key.with_policy(&p, None).ok()
                .and_then(|vcert| vcert.keys().for_signing().supported().next())
            {
                use crate::crypto::mpi::PublicKey;
                match k.mpis() {
                    PublicKey::ECDSA { curve, .. } |
                    PublicKey::EdDSA { curve, .. }
                    if ! curve.is_supported() => {
                        eprintln!("Skipping {} because we don't support \
                                   the curve {}", alg, curve);
                        continue;
                    },
                    _ => (),
                }
            } else {
                eprintln!("Skipping {} because we don't support the algorithm",
                          alg);
                continue;
            }

            let signing_keypair = key.keys().secret()
                .with_policy(&p, None).supported()
                .alive().revoked(false).for_signing()
                .nth(0).unwrap()
                .key().clone().into_keypair()?;

            let mut sink = vec![];
            let message = Message::new(&mut sink);
            let message = Signer::new(message, signing_keypair)
                .build()?;
            let mut message = LiteralWriter::new(message).build()?;
            message.write_all(b"Hello world.")?;
            message.finalize()?;

            let h = VHelper::new(1, 0, 0, 0, vec![key]);
            let mut d = VerifierBuilder::from_bytes(&sink)?
                .with_policy(&p, None, h)?;
            assert!(d.message_processed());

            let mut content = Vec::new();
            d.read_to_end(&mut content).unwrap();
            assert_eq!(&b"Hello world."[..], &content[..]);
        }

        Ok(())
    }

    /// Encrypts using public key cryptography.
    #[test]
    fn pk_encryptor() -> Result<()> {
        use crate::policy::StandardPolicy;
        use crate::parse::stream::{
            DecryptorBuilder,
            test::VHelper,
        };

        let p = StandardPolicy::new();
        for path in [
            "rsa", "elg", "cv25519", "cv25519.unclamped",
            "nistp256", "nistp384", "nistp521",
            "brainpoolP256r1", "brainpoolP384r1", "brainpoolP512r1",
            "secp256k1",
        ].iter().map(|alg| format!("messages/encrypted/{}.sec.pgp", alg))
        {
            eprintln!("Test vector {:?}...", path);
            let key = Cert::from_bytes(crate::tests::file(&path))?;
            if let Some(k) =
                key.with_policy(&p, None)?.keys().subkeys().supported().next()
            {
                use crate::crypto::mpi::PublicKey;
                match k.mpis() {
                    PublicKey::ECDH { curve, .. } if ! curve.is_supported() => {
                        eprintln!("Skipping {} because we don't support \
                                   the curve {}", path, curve);
                        continue;
                    },
                    _ => (),
                }
            } else {
                eprintln!("Skipping {} because we don't support the algorithm",
                          path);
                continue;
            }

            let recipients =
                key.with_policy(&p, None)?.keys().for_storage_encryption();

            let mut sink = vec![];
            let message = Message::new(&mut sink);
            let message =
                Encryptor::for_recipients(message, recipients)
                .build()?;
            let mut message = LiteralWriter::new(message).build()?;
            message.write_all(b"Hello world.")?;
            message.finalize()?;

            let h = VHelper::for_decryption(0, 0, 0, 0, Vec::new(),
                                            vec![key], Vec::new());
            let mut d = DecryptorBuilder::from_bytes(&sink)?
                .with_policy(&p, None, h)?;
            assert!(d.message_processed());

            let mut content = Vec::new();
            d.read_to_end(&mut content).unwrap();
            assert_eq!(&b"Hello world."[..], &content[..]);
        }

        Ok(())
    }
}