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
//! Streaming decryption and verification.
//!
//! This module provides convenient filters for decryption and
//! verification of OpenPGP messages (see [Section 11.3 of RFC 4880]).
//! It is the preferred interface to process OpenPGP messages:
//!
//!   [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
//!
//!   - Use the [`Verifier`] to verify a signed message,
//!   - [`DetachedVerifier`] to verify a detached signature,
//!   - or [`Decryptor`] to decrypt and verify an encrypted and
//!     possibly signed message.
//!
//!   [`Verifier`]: struct.Verifier.html
//!   [`DetachedVerifier`]: struct.DetachedVerifier.html
//!   [`Decryptor`]: struct.Decryptor.html
//!
//! Consuming OpenPGP messages is more difficult than producing them.
//! When we produce the message, we control the packet structure being
//! generated using our programs control flow.  However, when we
//! consume a message, the control flow is determined by the message
//! being processed.
//!
//! To use Sequoia's streaming [`Verifier`] and [`Decryptor`], you
//! need to provide an object that implements [`VerificationHelper`],
//! and for the [`Decryptor`] also [`DecryptionHelper`].
//!
//! [`VerificationHelper`]: trait.VerificationHelper.html
//! [`DecryptionHelper`]: trait.DecryptionHelper.html
//!
//! The [`VerificationHelper`] trait give certificates for the
//! signature verification to the [`Verifier`] or [`Decryptor`], let
//! you inspect the message structure (see [Section 11.3 of RFC
//! 4880]), and implements the signature verification policy.
//!
//! The [`DecryptionHelper`] trait is concerned with producing the
//! session key to decrypt a message, most commonly by decrypting one
//! of the messages' [`PKESK`] or [`SKESK`] packets.  It could also
//! use a cached session key, or one that has been explicitly provided
//! to the decryption operation.
//!
//!   [`PKESK`]: ../../packet/enum.PKESK.html
//!   [`SKESK`]: ../../packet/enum.SKESK.html
//!
//! The [`Verifier`] and [`Decryptor`] are filters: they consume
//! OpenPGP data from a reader, file, or bytes, and implement
//! [`io::Read`] that can be used to read the verified and/or
//! decrypted data.
//!
//!   [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
//!
//! [`DetachedVerifier`] does not provide the [`io::Read`] interface,
//! because in this case, the data to be verified is easily available
//! without any transformation.  Not providing a filter-like interface
//! allows for a very performant implementation of the verification.
//!
//! # Examples
//!
//! This example demonstrates how to use the streaming interface using
//! the [`Verifier`].  For brevity, no certificates are fed to the
//! verifier, and the message structure is not verified, i.e. this
//! merely extracts the literal data.  See the [`Verifier` examples]
//! and the [`Decryptor` examples] for how to verify the message and
//! its structure.
//!
//!   [`Verifier` examples]: struct.Verifier.html#examples
//!   [`Decryptor` examples]: struct.Decryptor.html#examples
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! use std::io::Read;
//! use sequoia_openpgp as openpgp;
//! use openpgp::{KeyHandle, Cert, Result};
//! use openpgp::parse::{Parse, stream::*};
//! use openpgp::policy::StandardPolicy;
//!
//! let p = &StandardPolicy::new();
//!
//! // This fetches keys and computes the validity of the verification.
//! struct Helper {};
//! impl VerificationHelper for Helper {
//!     fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
//!         Ok(Vec::new()) // Feed the Certs to the verifier here...
//!     }
//!     fn check(&mut self, structure: MessageStructure) -> Result<()> {
//!         Ok(()) // Implement your verification policy here.
//!     }
//! }
//!
//! let message =
//!    b"-----BEGIN PGP MESSAGE-----
//!
//!      xA0DAAoWBpwMNI3YLBkByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoAJwWCW37P
//!      8RahBI6MM/pGJjN5dtl5eAacDDSN2CwZCZAGnAw0jdgsGQAAeZQA/2amPbBXT96Q
//!      O7PFms9DRuehsVVrFkaDtjN2WSxI4RGvAQDq/pzNdCMpy/Yo7AZNqZv5qNMtDdhE
//!      b2WH5lghfKe/AQ==
//!      =DjuO
//!      -----END PGP MESSAGE-----";
//!
//! let h = Helper {};
//! let mut v = VerifierBuilder::from_bytes(&message[..])?
//!     .with_policy(p, None, h)?;
//!
//! let mut content = Vec::new();
//! v.read_to_end(&mut content)?;
//! assert_eq!(content, b"Hello World!");
//! # Ok(()) }
//! ```
use std::cmp;
use std::io::{self, Read};
use std::path::Path;
use std::time;

use buffered_reader::BufferedReader;
use crate::{
    Error,
    Fingerprint,
    types::{
        AEADAlgorithm,
        CompressionAlgorithm,
        RevocationStatus,
        SymmetricAlgorithm,
    },
    packet::{
        key,
        OnePassSig,
        PKESK,
        SKESK,
    },
    KeyID,
    Packet,
    Result,
    packet,
    packet::Signature,
    cert::prelude::*,
    crypto::SessionKey,
    policy::Policy,
};
use crate::parse::{
    Cookie,
    HashingMode,
    PacketParser,
    PacketParserBuilder,
    PacketParserResult,
    Parse,
};

/// Whether to trace execution by default (on stderr).
const TRACE : bool = false;

/// How much data to buffer before giving it to the caller.
///
/// Signature verification and detection of ciphertext tampering
/// requires processing the whole message first.  Therefore, OpenPGP
/// implementations supporting streaming operations necessarily must
/// output unverified data.  This has been a source of problems in the
/// past.  To alleviate this, we buffer the message first (up to 25
/// megabytes of net message data by default), and verify the
/// signatures if the message fits into our buffer.  Nevertheless it
/// is important to treat the data as unverified and untrustworthy
/// until you have seen a positive verification.
///
/// The default can be changed using [`VerifierBuilder::buffer_size`]
/// and [`DecryptorBuilder::buffer_size`].
///
///   [`VerifierBuilder::buffer_size`]: struct.VerifierBuilder.html#method.buffer_size
///   [`DecryptorBuilder::buffer_size`]: struct.DecryptorBuilder.html#method.buffer_size
pub const DEFAULT_BUFFER_SIZE: usize = 25 * 1024 * 1024;

/// Result of a signature verification.
///
/// A signature verification is either successful yielding a
/// [`GoodChecksum`], or there was some [`VerificationError`]
/// explaining the verification failure.
///
///  [`GoodChecksum`]: struct.GoodChecksum.html
///  [`VerificationError`]: enum.VerificationError.html
pub type VerificationResult<'a> =
    std::result::Result<GoodChecksum<'a>, VerificationError<'a>>;

/// A good signature.
///
/// Represents the result of a successful signature verification.  It
/// includes the signature and the signing key with all the necessary
/// context (i.e. certificate, time, policy) to evaluate the
/// trustworthiness of the signature using a trust model.
///
/// `GoodChecksum` is used in [`VerificationResult`].  See also
/// [`VerificationError`].
///
///   [`VerificationResult`]: type.VerificationResult.html
///   [`VerificationError`]: enum.VerificationError.html
///
/// A signature is considered good if and only if all of the following
/// conditions are met:
///
///   - The signature has a Signature Creation Time subpacket.
///
///   - The signature is alive at the specified time (the time
///     parameter passed to, e.g., [`VerifierBuilder::with_policy`]).
///
///       [`VerifierBuilder::with_policy`]: struct.VerifierBuilder.html#method.with_policy
///
///   - The certificate is alive and not revoked as of the signature's
///     creation time.
///
///   - The signing key is alive, not revoked, and signing capable as
///     of the signature's creation time.
///
///   - The signature was generated by the signing key.
///
/// **Note**: This doesn't mean that the key that generated the
/// signature is in anyway trustworthy in the sense that it
/// belongs to the person or entity that the user thinks it
/// belongs to.  This property can only be evaluated within a
/// trust model, such as the [web of trust] (WoT).  This policy is
/// normally implemented in the [`VerificationHelper::check`]
/// method.
///
///   [web of trust]: https://en.wikipedia.org/wiki/Web_of_trust
///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
#[derive(Debug)]
pub struct GoodChecksum<'a> {
    /// The signature.
    pub sig: &'a Signature,

    /// The signing key that made the signature.
    ///
    /// The amalgamation of the signing key includes the necessary
    /// context (i.e. certificate, time, policy) to evaluate the
    /// trustworthiness of the signature using a trust model.
    pub ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
}

/// A bad signature.
///
/// Represents the result of an unsuccessful signature verification.
/// It contains all the context that could be gathered until the
/// verification process failed.
///
/// `VerificationError` is used in [`VerificationResult`].  See also
/// [`GoodChecksum`].
///
///   [`VerificationResult`]: type.VerificationResult.html
///   [`GoodChecksum`]: struct.GoodChecksum.html
///
/// You can either explicitly match on the variants, or convert to
/// [`Error`] using [`From`].
///
///   [`Error`]: ../../enum.Error.html
///   [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
pub enum VerificationError<'a> {
    /// Malformed signature (no signature creation subpacket, etc.)
    MalformedSignature {
        /// The signature.
        sig: &'a Signature,

        /// The reason why the signature is malformed.
        error: anyhow::Error,
    },
    /// Missing Key
    MissingKey {
        /// The signature.
        sig: &'a Signature,
    },
    /// Unbound key.
    ///
    /// There is no valid binding signature at the time the signature
    /// was created under the given policy.
    UnboundKey {
        /// The signature.
        sig: &'a Signature,

        /// The certificate that made the signature.
        cert: &'a Cert,

        /// The reason why the key is not bound.
        error: anyhow::Error,
    },
    /// Bad key (have a key, but it is not alive, etc.)
    BadKey {
        /// The signature.
        sig: &'a Signature,

        /// The signing key that made the signature.
        ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,

        /// The reason why the key is bad.
        error: anyhow::Error,
    },
    /// Bad signature (have a valid key, but the signature didn't check out)
    BadSignature {
        /// The signature.
        sig: &'a Signature,

        /// The signing key that made the signature.
        ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,

        /// The reason why the signature is bad.
        error: anyhow::Error,
    },
}

impl<'a> std::fmt::Display for VerificationError<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use self::VerificationError::*;
        match self {
            MalformedSignature { error, .. } =>
                write!(f, "Malformed signature: {}", error),
            MissingKey { sig } =>
                if let Some(issuer) = sig.get_issuers().get(0) {
                    write!(f, "Missing key: {}", issuer)
                } else {
                    write!(f, "Missing key")
                },
            UnboundKey { cert, error, .. } =>
                write!(f, "Subkey of {} not bound: {}", cert, error),
            BadKey { ka, error, .. } =>
                write!(f, "Subkey of {} is bad: {}", ka.cert(), error),
            BadSignature { error, .. } =>
                write!(f, "Bad signature: {}", error),
        }
    }
}

impl<'a> From<VerificationError<'a>> for Error {
    fn from(e: VerificationError<'a>) -> Self {
        use self::VerificationError::*;
        match e {
            MalformedSignature { .. } =>
                Error::MalformedPacket(e.to_string()),
            MissingKey { .. } =>
                Error::InvalidKey(e.to_string()),
            UnboundKey { .. } =>
                Error::InvalidKey(e.to_string()),
            BadKey { .. } =>
                Error::InvalidKey(e.to_string()),
            BadSignature { .. } =>
                Error::BadSignature(e.to_string()),
        }
    }
}

/// Like VerificationError, but without referencing the signature.
///
/// This avoids borrowing the signature, so that we can continue to
/// mutably borrow the signature trying other keys.  After all keys
/// are tried, we attach the reference to the signature, yielding a
/// `VerificationError`.
enum VerificationErrorInternal<'a> {
    // MalformedSignature is not used, so it is omitted here.

    /// Missing Key
    MissingKey {
    },
    /// Unbound key.
    ///
    /// There is no valid binding signature at the time the signature
    /// was created under the given policy.
    UnboundKey {
        /// The certificate that made the signature.
        cert: &'a Cert,

        /// The reason why the key is not bound.
        error: anyhow::Error,
    },
    /// Bad key (have a key, but it is not alive, etc.)
    BadKey {
        /// The signing key that made the signature.
        ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,

        /// The reason why the key is bad.
        error: anyhow::Error,
    },
    /// Bad signature (have a valid key, but the signature didn't check out)
    BadSignature {
        /// The signing key that made the signature.
        ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,

        /// The reason why the signature is bad.
        error: anyhow::Error,
    },
}

impl<'a> VerificationErrorInternal<'a> {
    fn attach_sig(self, sig: &'a Signature) -> VerificationError<'a> {
        use self::VerificationErrorInternal::*;
        match self {
            MissingKey {} =>
                VerificationError::MissingKey { sig },
            UnboundKey { cert, error } =>
                VerificationError::UnboundKey { sig, cert, error },
            BadKey { ka, error } =>
                VerificationError::BadKey { sig, ka, error },
            BadSignature { ka, error } =>
                VerificationError::BadSignature { sig, ka, error },
        }
    }
}

/// Communicates the message structure to the VerificationHelper.
///
/// A valid OpenPGP message contains one literal data packet with
/// optional [encryption, signing, and compression layers] freely
/// combined on top.  This structure is passed to
/// [`VerificationHelper::check`] for verification.
///
///  [encryption, signing, and compression layers]: enum.MessageLayer.html
///  [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
///
/// The most common structure is an optionally encrypted, optionally
/// compressed, and optionally signed message, i.e. if the message is
/// encrypted, then the encryption is the outermost layer; if the
/// message is signed, then the signature group is the innermost
/// layer.  This is a sketch of such a message:
///
/// ```text
/// [ encryption layer: [ compression layer: [ signature group: [ literal data ]]]]
/// ```
///
/// However, OpenPGP allows encryption, signing, and compression
/// operations to be freely combined (see [Section 11.3 of RFC 4880]).
/// This is represented as a stack of [`MessageLayer`]s, where
/// signatures of the same level (i.e. those over the same data:
/// either directly over the literal data, or over other signatures
/// and the literal data) are grouped into one layer.  See also
/// [`Signature::level`].
///
///   [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
///   [`MessageLayer`]: enum.MessageLayer.html
///   [`Signature::level`]: ../../packet/enum.Signature.html#method.level
///
/// Consider the following structure.  This is a set of notarizing
/// signatures *N* over a set of signatures *S* over the literal data:
///
/// ```text
/// [ signature group: [ signature group: [ literal data ]]]
/// ```
///
/// The notarizing signatures *N* are said to be of level 1,
/// i.e. signatures over the signatures *S* and the literal data.  The
/// signatures *S* are level 0 signatures, i.e. signatures over the
/// literal data.
///
/// OpenPGP's flexibility allows adaption to new use cases, but also
/// presents a challenge to implementations and downstream users.  The
/// message structure must be both validated, and possibly
/// communicated to the application's user.  Note that if
/// compatibility is a concern, generated messages must be restricted
/// to a narrow subset of possible structures, see this [test of
/// unusual message structures].
///
///   [test of unusual message structures]: https://tests.sequoia-pgp.org/#Unusual_Message_Structure
#[derive(Debug)]
pub struct MessageStructure<'a>(Vec<MessageLayer<'a>>);

impl<'a> MessageStructure<'a> {
    fn new() -> Self {
        MessageStructure(Vec::new())
    }

    fn new_compression_layer(&mut self, algo: CompressionAlgorithm) {
        self.0.push(MessageLayer::Compression {
            algo,
        })
    }

    fn new_encryption_layer(&mut self, sym_algo: SymmetricAlgorithm,
                            aead_algo: Option<AEADAlgorithm>) {
        self.0.push(MessageLayer::Encryption {
            sym_algo: sym_algo,
            aead_algo: aead_algo,
        })
    }

    fn new_signature_group(&mut self) {
        self.0.push(MessageLayer::SignatureGroup {
            results: Vec::new(),
        })
    }

    fn push_verification_result(&mut self, sig: VerificationResult<'a>) {
        if let Some(MessageLayer::SignatureGroup { ref mut results }) =
            self.0.iter_mut().last()
        {
            results.push(sig);
        } else {
            panic!("cannot push to encryption or compression layer");
        }
    }
}

impl<'a> std::ops::Deref for MessageStructure<'a> {
    type Target = [MessageLayer<'a>];

    fn deref(&self) -> &Self::Target {
        &self.0[..]
    }
}

impl<'a> IntoIterator for MessageStructure<'a> {
    type Item = MessageLayer<'a>;
    type IntoIter = std::vec::IntoIter<MessageLayer<'a>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Represents a layer of the message structure.
///
/// A valid OpenPGP message contains one literal data packet with
/// optional encryption, signing, and compression layers freely
/// combined on top (see [Section 11.3 of RFC 4880]).  This enum
/// represents the layers.  The [`MessageStructure`] is communicated
/// to the [`VerificationHelper::check`].  Iterating over the
/// [`MessageStructure`] yields the individual message layers.
///
///   [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
///   [`MessageStructure`]: struct.MessageStructure.html
///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
#[derive(Debug)]
pub enum MessageLayer<'a> {
    /// Represents an compression container.
    ///
    /// Compression is usually transparent in OpenPGP, though it may
    /// sometimes be interesting for advanced users to indicate that
    /// the message was compressed, and how (see [Section 5.6 of RFC
    /// 4880]).
    ///
    ///   [Section 5.6 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.6
    Compression {
        /// Compression algorithm used.
        algo: CompressionAlgorithm,
    },
    /// Represents an encryption container.
    ///
    /// Indicates the fact that the message was encrypted (see
    /// [Section 5.13 of RFC 4880]).  If you expect encrypted
    /// messages, make sure that there is at least one encryption
    /// container present.
    ///
    ///   [Section 5.13 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.13
    Encryption {
        /// Symmetric algorithm used.
        sym_algo: SymmetricAlgorithm,
        /// AEAD algorithm used, if any.
        ///
        /// This feature is [experimental](../../index.html#experimental-features).
        aead_algo: Option<AEADAlgorithm>,
    },
    /// Represents a signature group.
    ///
    /// A signature group consists of all signatures with the same
    /// level (see [Section 5.2 of RFC 4880]).  Each
    /// [`VerificationResult`] represents the result of a single
    /// signature verification.  In your [`VerificationHelper::check`]
    /// method, iterate over the verification results, see if it meets
    /// your policies' demands, and communicate it to the user, if
    /// applicable.
    ///
    ///   [Section 5.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2
    ///   [`VerificationResult`]: type.VerificationResult.html
    ///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
    SignatureGroup {
        /// The results of the signature verifications.
        results: Vec<VerificationResult<'a>>,
    }
}

/// Internal version of the message structure.
///
/// In contrast to MessageStructure, this owns unverified
/// signature packets.
#[derive(Debug)]
struct IMessageStructure {
    layers: Vec<IMessageLayer>,

    // We insert a SignatureGroup layer every time we see a OnePassSig
    // packet with the last flag.
    //
    // However, we need to make sure that we insert a SignatureGroup
    // layer even if the OnePassSig packet has the last flag set to
    // false.  To do that, we keep track of the fact that we saw such
    // a OPS packet.
    sig_group_counter: usize,
}

impl IMessageStructure {
    fn new() -> Self {
        IMessageStructure {
            layers: Vec::new(),
            sig_group_counter: 0,
        }
    }

    fn new_compression_layer(&mut self, algo: CompressionAlgorithm) {
        self.insert_missing_signature_group();
        self.layers.push(IMessageLayer::Compression {
            algo,
        });
    }

    fn new_encryption_layer(&mut self, sym_algo: SymmetricAlgorithm,
                            aead_algo: Option<AEADAlgorithm>) {
        self.insert_missing_signature_group();
        self.layers.push(IMessageLayer::Encryption {
            sym_algo: sym_algo,
            aead_algo: aead_algo,
        });
    }

    /// Makes sure that we insert a signature group even if the
    /// previous OPS packet had the last flag set to false.
    fn insert_missing_signature_group(&mut self) {
        if self.sig_group_counter > 0 {
            self.layers.push(IMessageLayer::SignatureGroup {
                sigs: Vec::new(),
                count: self.sig_group_counter,
            });
        }
        self.sig_group_counter = 0;
    }

    fn push_ops(&mut self, ops: &OnePassSig) {
        self.sig_group_counter += 1;
        if ops.last() {
            self.layers.push(IMessageLayer::SignatureGroup {
                sigs: Vec::new(),
                count: self.sig_group_counter,
            });
            self.sig_group_counter = 0;
        }
    }

    fn push_signature(&mut self, sig: Signature) {
        for layer in self.layers.iter_mut().rev() {
            match layer {
                IMessageLayer::SignatureGroup {
                    ref mut sigs, ref mut count,
                } if *count > 0 => {
                    sigs.push(sig);
                    *count -= 1;
                    return;
                },
                _ => (),
            }
        }
        panic!("signature unaccounted for");
    }

    fn push_bare_signature(&mut self, sig: Signature) {
        if let Some(IMessageLayer::SignatureGroup { .. }) = self.layers.iter().last() {
            // The last layer is a SignatureGroup.  We will append the
            // signature there without accounting for it.
        } else {
            // The last layer is not a SignatureGroup, or there is no
            // layer at all.  Create one.
            self.layers.push(IMessageLayer::SignatureGroup {
                sigs: Vec::new(),
                count: 0,
            });
        }

        if let IMessageLayer::SignatureGroup { ref mut sigs, .. } =
            self.layers.iter_mut().last().expect("just checked or created")
        {
            sigs.push(sig);
        } else {
            unreachable!("just checked or created")
        }
    }

}

/// Internal version of a layer of the message structure.
///
/// In contrast to MessageLayer, this owns unverified signature packets.
#[derive(Debug)]
enum IMessageLayer {
    Compression {
        algo: CompressionAlgorithm,
    },
    Encryption {
        sym_algo: SymmetricAlgorithm,
        aead_algo: Option<AEADAlgorithm>,
    },
    SignatureGroup {
        sigs: Vec<Signature>,
        count: usize,
    }
}

/// Helper for signature verification.
///
/// This trait abstracts over signature and message structure
/// verification.  It allows us to provide the [`Verifier`],
/// [`DetachedVerifier`], and [`Decryptor`] without imposing a policy
/// on how certificates for signature verification are looked up, or
/// what message structure is considered acceptable.
///
///   [`Verifier`]: struct.Verifier.html
///   [`DetachedVerifier`]: struct.DetachedVerifier.html
///   [`Decryptor`]: struct.Decryptor.html
///
/// It also allows you to inspect each packet that is processed during
/// verification or decryption, optionally providing a [`Map`] for
/// each packet.
///
///   [`Map`]: ../map/struct.Map.html
pub trait VerificationHelper {
    /// Inspects the message.
    ///
    /// Called once per packet.  Can be used to inspect and dump
    /// packets in encrypted messages.
    ///
    /// The default implementation does nothing.
    fn inspect(&mut self, pp: &PacketParser) -> Result<()> {
        // Do nothing.
        let _ = pp;
        Ok(())
    }

    /// Retrieves the certificates containing the specified keys.
    ///
    /// When implementing this method, you should return as many
    /// certificates corresponding to the `ids` as you can.
    ///
    /// If an identifier is ambiguous, because, for instance, there
    /// are multiple certificates with the same Key ID, then you
    /// should return all of them.
    ///
    /// You should only return an error if processing should be
    /// aborted.  In general, you shouldn't return an error if you
    /// don't have a certificate for a given identifier: if there are
    /// multiple signatures, then, depending on your policy, verifying
    /// a subset of them may be sufficient.
    ///
    /// This method will be called at most once per message.
    ///
    /// # Examples
    ///
    /// This example demonstrates how to look up the certificates for
    /// the signature verification given the list of signature
    /// issuers.
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::stream::*;
    /// # fn lookup_cert_by_handle(_: &KeyHandle) -> Result<Cert> {
    /// #     unimplemented!()
    /// # }
    ///
    /// struct Helper { /* ... */ };
    /// impl VerificationHelper for Helper {
    ///     fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    ///         let mut certs = Vec::new();
    ///         for id in ids {
    ///             certs.push(lookup_cert_by_handle(id)?);
    ///         }
    ///         Ok(certs)
    ///     }
    ///     // ...
    /// #    fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #        unimplemented!()
    /// #    }
    /// }
    /// ```
    fn get_certs(&mut self, ids: &[crate::KeyHandle]) -> Result<Vec<Cert>>;

    /// Validates the message structure.
    ///
    /// This function must validate the message's structure according
    /// to an application specific policy.  For example, it could
    /// check that the required number of signatures or notarizations
    /// were confirmed as good, and evaluate every signature's
    /// validity under an trust model.
    ///
    /// A valid OpenPGP message contains one literal data packet with
    /// optional encryption, signing, and compression layers on top.
    /// Notably, the message structure contains the results of
    /// signature verifications.  See [`MessageStructure`] for more
    /// information.
    ///
    /// [`MessageStructure`]: struct.MessageStructure.html
    ///
    /// When verifying a message, this callback will be called exactly
    /// once per message *after* the last signature has been verified
    /// and *before* all of the data has been returned.  Any error
    /// returned by this function will abort reading, and the error
    /// will be propagated via the [`io::Read`] operation.
    ///
    ///   [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
    ///
    /// After this method was called, [`Verifier::message_processed`]
    /// and [`Decryptor::message_processed`] return `true`.
    ///
    ///   [`Verifier::message_processed`]: struct.Verifier.html#method.message_processed
    ///   [`Decryptor::message_processed`]: struct.Decryptor.html#method.message_processed
    ///
    /// When verifying a detached signature using the
    /// [`DetachedVerifier`], this method will be called with a
    /// [`MessageStructure`] containing exactly one layer, a signature
    /// group.
    ///
    ///   [`DetachedVerifier`]: struct.DetachedVerifier.html
    ///
    /// # Examples
    ///
    /// This example demonstrates how to verify that the message is an
    /// encrypted, optionally compressed, and signed message that has
    /// at least one valid signature.
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::stream::*;
    ///
    /// struct Helper { /* ... */ };
    /// impl VerificationHelper for Helper {
    /// #    fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #        unimplemented!();
    /// #    }
    ///     fn check(&mut self, structure: MessageStructure) -> Result<()> {
    ///         for (i, layer) in structure.into_iter().enumerate() {
    ///             match layer {
    ///                 MessageLayer::Encryption { .. } if i == 0 => (),
    ///                 MessageLayer::Compression { .. } if i == 1 => (),
    ///                 MessageLayer::SignatureGroup { ref results }
    ///                     if i == 1 || i == 2 =>
    ///                 {
    ///                     if ! results.iter().any(|r| r.is_ok()) {
    ///                         return Err(anyhow::anyhow!(
    ///                                        "No valid signature"));
    ///                     }
    ///                 }
    ///                 _ => return Err(anyhow::anyhow!(
    ///                                     "Unexpected message structure")),
    ///             }
    ///         }
    ///         Ok(())
    ///     }
    ///     // ...
    /// }
    /// ```
    fn check(&mut self, structure: MessageStructure) -> Result<()>;
}

/// Wraps a VerificationHelper and adds a non-functional
/// DecryptionHelper implementation.
struct NoDecryptionHelper<V: VerificationHelper> {
    v: V,
}

impl<V: VerificationHelper> VerificationHelper for NoDecryptionHelper<V> {
    fn get_certs(&mut self, ids: &[crate::KeyHandle]) -> Result<Vec<Cert>>
    {
        self.v.get_certs(ids)
    }
    fn check(&mut self, structure: MessageStructure) -> Result<()>
    {
        self.v.check(structure)
    }
}

impl<V: VerificationHelper> DecryptionHelper for NoDecryptionHelper<V> {
    fn decrypt<D>(&mut self, _: &[PKESK], _: &[SKESK],
                  _: Option<SymmetricAlgorithm>,
                  _: D) -> Result<Option<Fingerprint>>
        where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
    {
        unreachable!("This is not used for verifications")
    }
}

/// Verifies a signed OpenPGP message.
///
/// To create a `Verifier`, create a [`VerifierBuilder`] using
/// [`Parse`], and customize it to your needs.
///
///   [`VerifierBuilder`]: struct.VerifierBuilder.html
///   [`Parse`]: ../trait.Parse.html
///
/// Signature verification requires processing the whole message
/// first.  Therefore, OpenPGP implementations supporting streaming
/// operations necessarily must output unverified data.  This has been
/// a source of problems in the past.  To alleviate this, we buffer
/// the message first (up to 25 megabytes of net message data by
/// default, see [`DEFAULT_BUFFER_SIZE`]), and verify the signatures
/// if the message fits into our buffer.  Nevertheless it is important
/// to treat the data as unverified and untrustworthy until you have
/// seen a positive verification.  See [`Verifier::message_processed`]
/// for more information.
///
///   [`DEFAULT_BUFFER_SIZE`]: constant.DEFAULT_BUFFER_SIZE.html
///   [`Verifier::message_processed`]: #method.message_processed
///
/// See [`GoodChecksum`] for what it means for a signature to be
/// considered valid.
///
///   [`GoodChecksum`]: struct.GoodChecksum.html
///
/// # Examples
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use std::io::Read;
/// use sequoia_openpgp as openpgp;
/// use openpgp::{KeyHandle, Cert, Result};
/// use openpgp::parse::{Parse, stream::*};
/// use openpgp::policy::StandardPolicy;
/// # fn lookup_cert_by_handle(_: &KeyHandle) -> Result<Cert> {
/// #     Cert::from_bytes(
/// #       &b"-----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-----"[..])
/// # }
///
/// let p = &StandardPolicy::new();
///
/// // This fetches keys and computes the validity of the verification.
/// struct Helper {};
/// impl VerificationHelper for Helper {
///     fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
///         let mut certs = Vec::new();
///         for id in ids {
///             certs.push(lookup_cert_by_handle(id)?);
///         }
///         Ok(certs)
///     }
///
///     fn check(&mut self, structure: MessageStructure) -> Result<()> {
///         for (i, layer) in structure.into_iter().enumerate() {
///             match layer {
///                 MessageLayer::Encryption { .. } if i == 0 => (),
///                 MessageLayer::Compression { .. } if i == 1 => (),
///                 MessageLayer::SignatureGroup { ref results } => {
///                     if ! results.iter().any(|r| r.is_ok()) {
///                         return Err(anyhow::anyhow!(
///                                        "No valid signature"));
///                     }
///                 }
///                 _ => return Err(anyhow::anyhow!(
///                                     "Unexpected message structure")),
///             }
///         }
///         Ok(())
///     }
/// }
///
/// let message =
///    b"-----BEGIN PGP MESSAGE-----
///
///      xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
///      AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
///      UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
///      YmAFv/UfO0vYBw==
///      =+l94
///      -----END PGP MESSAGE-----
///      ";
///
/// let h = Helper {};
/// let mut v = VerifierBuilder::from_bytes(&message[..])?
///     .with_policy(p, None, h)?;
///
/// let mut content = Vec::new();
/// v.read_to_end(&mut content)?;
/// assert_eq!(content, b"Hello World!");
/// # Ok(()) }
pub struct Verifier<'a, H: VerificationHelper> {
    decryptor: Decryptor<'a, NoDecryptionHelper<H>>,
}

/// A builder for `Verifier`.
///
/// This allows the customization of [`Verifier`], which can
/// be built using [`VerifierBuilder::with_policy`].
///
///   [`Verifier`]: struct.Verifier.html
///   [`VerifierBuilder::with_policy`]: struct.VerifierBuilder.html#method.with_policy
pub struct VerifierBuilder<'a> {
    message: Box<dyn BufferedReader<Cookie> + 'a>,
    buffer_size: usize,
    mapping: bool,
}

impl<'a> Parse<'a, VerifierBuilder<'a>>
    for VerifierBuilder<'a>
{
    fn from_reader<R>(reader: R) -> Result<VerifierBuilder<'a>>
        where R: io::Read + 'a,
    {
        VerifierBuilder::new(buffered_reader::Generic::with_cookie(
            reader, None, Default::default()))
    }

    fn from_file<P>(path: P) -> Result<VerifierBuilder<'a>>
        where P: AsRef<Path>,
    {
        VerifierBuilder::new(buffered_reader::File::with_cookie(
            path, Default::default())?)
    }

    fn from_bytes<D>(data: &'a D) -> Result<VerifierBuilder<'a>>
        where D: AsRef<[u8]> + ?Sized,
    {
        VerifierBuilder::new(buffered_reader::Memory::with_cookie(
            data.as_ref(), Default::default()))
    }
}

impl<'a> VerifierBuilder<'a> {
    fn new<B>(signatures: B) -> Result<Self>
        where B: buffered_reader::BufferedReader<Cookie> + 'a
    {
        Ok(VerifierBuilder {
            message: Box::new(signatures),
            buffer_size: DEFAULT_BUFFER_SIZE,
            mapping: false,
        })
    }

    /// Changes the amount of buffered data.
    ///
    /// By default, we buffer up to 25 megabytes of net message data
    /// (see [`DEFAULT_BUFFER_SIZE`]).  This changes the default.
    ///
    ///   [`DEFAULT_BUFFER_SIZE`]: constant.DEFAULT_BUFFER_SIZE.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = VerifierBuilder::from_bytes(message)?
    ///     .buffer_size(1 << 12)
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }

    /// Enables mapping.
    ///
    /// If mapping is enabled, the packet parser will create a [`Map`]
    /// of the packets that can be inspected in
    /// [`VerificationHelper::inspect`].  Note that this buffers the
    /// packets contents, and is not recommended unless you know that
    /// the packets are small.
    ///
    ///   [`Map`]: ../map/struct.Map.html
    ///   [`VerificationHelper::inspect`]: trait.VerificationHelper.html#tymethod.inspect
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = VerifierBuilder::from_bytes(message)?
    ///     .mapping(true)
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn mapping(mut self, enabled: bool) -> Self {
        self.mapping = enabled;
        self
    }

    /// Creates the `Verifier`.
    ///
    /// Signature verifications are done under the given `policy` and
    /// relative to time `time`, or the current time, if `time` is
    /// `None`.  `helper` is the [`VerificationHelper`] to use.
    ///
    ///   [`VerificationHelper`]: trait.VerificationHelper.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = VerifierBuilder::from_bytes(message)?
    ///     // Customize the `Verifier` here.
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
                             -> Result<Verifier<'a, H>>
        where H: VerificationHelper,
              T: Into<Option<time::SystemTime>>,
    {
        // Do not eagerly map `t` to the current time.
        let t = time.into();
        Ok(Verifier {
            decryptor: Decryptor::from_buffered_reader(
                policy,
                self.message,
                NoDecryptionHelper { v: helper, },
                t, Mode::Verify, self.buffer_size, self.mapping)?,
        })
    }
}

impl<'a, H: VerificationHelper> Verifier<'a, H> {
    /// Returns a reference to the helper.
    pub fn helper_ref(&self) -> &H {
        &self.decryptor.helper_ref().v
    }

    /// Returns a mutable reference to the helper.
    pub fn helper_mut(&mut self) -> &mut H {
        &mut self.decryptor.helper_mut().v
    }

    /// Recovers the helper.
    pub fn into_helper(self) -> H {
        self.decryptor.into_helper().v
    }

    /// Returns true if the whole message has been processed and
    /// authenticated.
    ///
    /// If the function returns `true`, the whole message has been
    /// processed, the signatures are verified, and the message
    /// structure has been passed to [`VerificationHelper::check`].
    /// Data read from this `Verifier` using [`io::Read`] has been
    /// authenticated.
    ///
    ///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
    ///   [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
    ///
    /// If the function returns `false`, the message did not fit into
    /// the internal buffer, and therefore data read from this
    /// `Verifier` using [`io::Read`] has **not yet been
    /// authenticated**.  It is important to treat this data as
    /// attacker controlled and not use it until it has been
    /// authenticated.
    ///
    /// # Examples
    ///
    /// This example demonstrates how to verify a message in a
    /// streaming fashion, writing the data to a temporary file and
    /// only commit the result once the data is authenticated.
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::{Read, Seek, SeekFrom};
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    /// #
    /// # // Mock of `tempfile::tempfile`.
    /// # mod tempfile {
    /// #     pub fn tempfile() -> sequoia_openpgp::Result<std::fs::File> {
    /// #         unimplemented!()
    /// #     }
    /// # }
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// // This fetches keys and computes the validity of the verification.
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #   fn check(&mut self, _: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let mut source =
    ///    // ...
    /// #  std::io::Cursor::new(&b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..]);
    ///
    /// fn consume(r: &mut dyn Read) -> Result<()> {
    ///    // ...
    /// #   let _ = r; Ok(())
    /// }
    ///
    /// let h = Helper {};
    /// let mut v = VerifierBuilder::from_reader(&mut source)?
    ///     .with_policy(p, None, h)?;
    ///
    /// if v.message_processed() {
    ///     // The data has been authenticated.
    ///     consume(&mut v)?;
    /// } else {
    ///     let mut tmp = tempfile::tempfile()?;
    ///     std::io::copy(&mut v, &mut tmp)?;
    ///
    ///     // If the copy succeeds, the message has been fully
    ///     // processed and the data has been authenticated.
    ///     assert!(v.message_processed());
    ///
    ///     // Rewind and consume.
    ///     tmp.seek(SeekFrom::Start(0))?;
    ///     consume(&mut tmp)?;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn message_processed(&self) -> bool {
        self.decryptor.message_processed()
    }
}

impl<'a, H: VerificationHelper> io::Read for Verifier<'a, H> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.decryptor.read(buf)
    }
}


/// Verifies a detached signature.
///
/// To create a `DetachedVerifier`, create a
/// [`DetachedVerifierBuilder`] using [`Parse`], and customize it to
/// your needs.
///
///   [`DetachedVerifierBuilder`]: struct.DetachedVerifierBuilder.html
///   [`Parse`]: ../trait.Parse.html
///
/// See [`GoodChecksum`] for what it means for a signature to be
/// considered valid.  When the signature(s) are processed,
/// [`VerificationHelper::check`] will be called with a
/// [`MessageStructure`] containing exactly one layer, a signature
/// group.
///
///   [`GoodChecksum`]: struct.GoodChecksum.html
///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
///   [`MessageStructure`]: struct.MessageStructure.html
///
/// # Examples
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use std::io::{self, Read};
/// use sequoia_openpgp as openpgp;
/// use openpgp::{KeyHandle, Cert, Result};
/// use openpgp::parse::{Parse, stream::*};
/// use sequoia_openpgp::policy::StandardPolicy;
///
/// let p = &StandardPolicy::new();
///
/// // This fetches keys and computes the validity of the verification.
/// struct Helper {};
/// impl VerificationHelper for Helper {
///     fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
///         Ok(Vec::new()) // Feed the Certs to the verifier here...
///     }
///     fn check(&mut self, structure: MessageStructure) -> Result<()> {
///         Ok(()) // Implement your verification policy here.
///     }
/// }
///
/// let signature =
///    b"-----BEGIN PGP SIGNATURE-----
///
///      wnUEABYKACcFglt+z/EWoQSOjDP6RiYzeXbZeXgGnAw0jdgsGQmQBpwMNI3YLBkA
///      AHmUAP9mpj2wV0/ekDuzxZrPQ0bnobFVaxZGg7YzdlksSOERrwEA6v6czXQjKcv2
///      KOwGTamb+ajTLQ3YRG9lh+ZYIXynvwE=
///      =IJ29
///      -----END PGP SIGNATURE-----";
///
/// let data = b"Hello World!";
/// let h = Helper {};
/// let mut v = DetachedVerifierBuilder::from_bytes(&signature[..])?
///     .with_policy(p, None, h)?;
/// v.verify_bytes(data)?;
/// # Ok(()) }
pub struct DetachedVerifier<'a, H: VerificationHelper> {
    decryptor: Decryptor<'a, NoDecryptionHelper<H>>,
}

/// A builder for `DetachedVerifier`.
///
/// This allows the customization of [`DetachedVerifier`], which can
/// be built using [`DetachedVerifierBuilder::with_policy`].
///
///   [`DetachedVerifier`]: struct.DetachedVerifier.html
///   [`DetachedVerifierBuilder::with_policy`]: struct.DetachedVerifierBuilder.html#method.with_policy
pub struct DetachedVerifierBuilder<'a> {
    signatures: Box<dyn BufferedReader<Cookie> + 'a>,
    mapping: bool,
}

impl<'a> Parse<'a, DetachedVerifierBuilder<'a>>
    for DetachedVerifierBuilder<'a>
{
    fn from_reader<R>(reader: R) -> Result<DetachedVerifierBuilder<'a>>
        where R: io::Read + 'a,
    {
        DetachedVerifierBuilder::new(buffered_reader::Generic::with_cookie(
            reader, None, Default::default()))
    }

    fn from_file<P>(path: P) -> Result<DetachedVerifierBuilder<'a>>
        where P: AsRef<Path>,
    {
        DetachedVerifierBuilder::new(buffered_reader::File::with_cookie(
            path, Default::default())?)
    }

    fn from_bytes<D>(data: &'a D) -> Result<DetachedVerifierBuilder<'a>>
        where D: AsRef<[u8]> + ?Sized,
    {
        DetachedVerifierBuilder::new(buffered_reader::Memory::with_cookie(
            data.as_ref(), Default::default()))
    }
}

impl<'a> DetachedVerifierBuilder<'a> {
    fn new<B>(signatures: B) -> Result<Self>
        where B: buffered_reader::BufferedReader<Cookie> + 'a
    {
        Ok(DetachedVerifierBuilder {
            signatures: Box::new(signatures),
            mapping: false,
        })
    }

    /// Enables mapping.
    ///
    /// If mapping is enabled, the packet parser will create a [`Map`]
    /// of the packets that can be inspected in
    /// [`VerificationHelper::inspect`].  Note that this buffers the
    /// packets contents, and is not recommended unless you know that
    /// the packets are small.
    ///
    ///   [`Map`]: ../map/struct.Map.html
    ///   [`VerificationHelper::inspect`]: trait.VerificationHelper.html#tymethod.inspect
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = DetachedVerifierBuilder::from_bytes(message)?
    ///     .mapping(true)
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn mapping(mut self, enabled: bool) -> Self {
        self.mapping = enabled;
        self
    }

    /// Creates the `DetachedVerifier`.
    ///
    /// Signature verifications are done under the given `policy` and
    /// relative to time `time`, or the current time, if `time` is
    /// `None`.  `helper` is the [`VerificationHelper`] to use.
    /// [`VerificationHelper::check`] will be called with a
    /// [`MessageStructure`] containing exactly one layer, a signature
    /// group.
    ///
    ///   [`VerificationHelper`]: trait.VerificationHelper.html
    ///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
    ///   [`MessageStructure`]: struct.MessageStructure.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #
    /// #   fn check(&mut self, structure: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = DetachedVerifierBuilder::from_bytes(message)?
    ///     // Customize the `DetachedVerifier` here.
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
                             -> Result<DetachedVerifier<'a, H>>
        where H: VerificationHelper,
              T: Into<Option<time::SystemTime>>,
    {
        // Do not eagerly map `t` to the current time.
        let t = time.into();
        Ok(DetachedVerifier {
            decryptor: Decryptor::from_buffered_reader(
                policy,
                self.signatures,
                NoDecryptionHelper { v: helper, },
                t, Mode::VerifyDetached, 0, self.mapping)?,
        })
    }
}

impl<'a, H: VerificationHelper> DetachedVerifier<'a, H> {
    /// Verifies the given data.
    pub fn verify_reader<R: io::Read>(&mut self, reader: R) -> Result<()> {
        self.verify(buffered_reader::Generic::with_cookie(
            reader, None, Default::default()).as_boxed())
    }

    /// Verifies the given data.
    pub fn verify_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.verify(buffered_reader::File::with_cookie(
            path, Default::default())?.as_boxed())
    }

    /// Verifies the given data.
    pub fn verify_bytes<B: AsRef<[u8]>>(&mut self, buf: B) -> Result<()> {
        self.verify(buffered_reader::Memory::with_cookie(
            buf.as_ref(), Default::default()).as_boxed())
    }

    /// Verifies the given data.
    fn verify<R>(&mut self, reader: R) -> Result<()>
        where R: BufferedReader<Cookie>,
    {
        self.decryptor.verify_detached(reader)
    }

    /// Returns a reference to the helper.
    pub fn helper_ref(&self) -> &H {
        &self.decryptor.helper_ref().v
    }

    /// Returns a mutable reference to the helper.
    pub fn helper_mut(&mut self) -> &mut H {
        &mut self.decryptor.helper_mut().v
    }

    /// Recovers the helper.
    pub fn into_helper(self) -> H {
        self.decryptor.into_helper().v
    }
}


/// Modes of operation for the Decryptor.
#[derive(Debug, PartialEq, Eq)]
enum Mode {
    Decrypt,
    Verify,
    VerifyDetached,
}

/// Decrypts and verifies an encrypted and optionally signed OpenPGP
/// message.
///
/// To create a `Decryptor`, create a [`DecryptorBuilder`] using
/// [`Parse`], and customize it to your needs.
///
///   [`DecryptorBuilder`]: struct.DecryptorBuilder.html
///   [`Parse`]: ../trait.Parse.html
///
/// Signature verification and detection of ciphertext tampering
/// requires processing the whole message first.  Therefore, OpenPGP
/// implementations supporting streaming operations necessarily must
/// output unverified data.  This has been a source of problems in the
/// past.  To alleviate this, we buffer the message first (up to 25
/// megabytes of net message data by default, see
/// [`DEFAULT_BUFFER_SIZE`]), and verify the signatures if the message
/// fits into our buffer.  Nevertheless it is important to treat the
/// data as unverified and untrustworthy until you have seen a
/// positive verification.  See [`Decryptor::message_processed`] for
/// more information.
///
///   [`DEFAULT_BUFFER_SIZE`]: constant.DEFAULT_BUFFER_SIZE.html
///   [`Decryptor::message_processed`]: #method.message_processed
///
/// See [`GoodChecksum`] for what it means for a signature to be
/// considered valid.
///
///   [`GoodChecksum`]: struct.GoodChecksum.html
///
/// # Examples
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use std::io::Read;
/// use sequoia_openpgp as openpgp;
/// use openpgp::crypto::SessionKey;
/// use openpgp::types::SymmetricAlgorithm;
/// use openpgp::{KeyID, Cert, Result, packet::{Key, PKESK, SKESK}};
/// use openpgp::parse::{Parse, stream::*};
/// use sequoia_openpgp::policy::StandardPolicy;
///
/// let p = &StandardPolicy::new();
///
/// // This fetches keys and computes the validity of the verification.
/// struct Helper {};
/// impl VerificationHelper for Helper {
///     fn get_certs(&mut self, _ids: &[openpgp::KeyHandle]) -> Result<Vec<Cert>> {
///         Ok(Vec::new()) // Feed the Certs to the verifier here...
///     }
///     fn check(&mut self, structure: MessageStructure) -> Result<()> {
///         Ok(()) // Implement your verification policy here.
///     }
/// }
/// impl DecryptionHelper for Helper {
///     fn decrypt<D>(&mut self, _: &[PKESK], skesks: &[SKESK],
///                   _sym_algo: Option<SymmetricAlgorithm>,
///                   mut decrypt: D) -> Result<Option<openpgp::Fingerprint>>
///         where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
///     {
///         skesks[0].decrypt(&"streng geheim".into())
///             .map(|(algo, session_key)| decrypt(algo, &session_key));
///         Ok(None)
///     }
/// }
///
/// let message =
///    b"-----BEGIN PGP MESSAGE-----
///
///      wy4ECQMIY5Zs8RerVcXp85UgoUKjKkevNPX3WfcS5eb7rkT9I6kw6N2eEc5PJUDh
///      0j0B9mnPKeIwhp2kBHpLX/en6RfNqYauX9eSeia7aqsd/AOLbO9WMCLZS5d2LTxN
///      rwwb8Aggyukj13Mi0FF5
///      =OB/8
///      -----END PGP MESSAGE-----";
///
/// let h = Helper {};
/// let mut v = DecryptorBuilder::from_bytes(&message[..])?
///     .with_policy(p, None, h)?;
///
/// let mut content = Vec::new();
/// v.read_to_end(&mut content)?;
/// assert_eq!(content, b"Hello World!");
/// # Ok(()) }
pub struct Decryptor<'a, H: VerificationHelper + DecryptionHelper> {
    helper: H,
    certs: Vec<Cert>,
    oppr: Option<PacketParserResult<'a>>,
    identity: Option<Fingerprint>,
    structure: IMessageStructure,

    /// We want to hold back some data until the signatures checked
    /// out.  We buffer this here, cursor is the offset of unread
    /// bytes in the buffer.
    buffer_size: usize,
    reserve: Option<Vec<u8>>,
    cursor: usize,

    /// The mode of operation.
    mode: Mode,

    /// Signature verification relative to this time.
    ///
    /// This is needed for checking the signature's liveness.
    ///
    /// We want the same semantics as `Subpacket::signature_alive`.
    /// Specifically, when using the current time, we want to tolerate
    /// some clock skew, but when using some specific time, we don't.
    /// (See `Subpacket::signature_alive` for an explanation.)
    ///
    /// These semantics can be realized by making `time` an
    /// `Option<time::SystemTime>` and passing that as is to
    /// `Subpacket::signature_alive`.  But that approach has two new
    /// problems.  First, if we are told to use the current time, then
    /// we want to use the time at which the Verifier was
    /// instantiated, not the time at which we call
    /// `Subpacket::signature_alive`.  Second, if we call
    /// `Subpacket::signature_alive` multiple times, they should all
    /// use the same time.  To work around these issues, when a
    /// Verifier is instantiated, we evaluate `time` and we record how
    /// much we want to tolerate clock skew in the same way as
    /// `Subpacket::signature_alive`.
    time: time::SystemTime,
    clock_skew_tolerance: time::Duration,

    policy: &'a dyn Policy,
}

/// A builder for `Decryptor`.
///
/// This allows the customization of [`Decryptor`], which can
/// be built using [`DecryptorBuilder::with_policy`].
///
///   [`Decryptor`]: struct.Decryptor.html
///   [`DecryptorBuilder::with_policy`]: struct.DecryptorBuilder.html#method.with_policy
pub struct DecryptorBuilder<'a> {
    message: Box<dyn BufferedReader<Cookie> + 'a>,
    buffer_size: usize,
    mapping: bool,
}

impl<'a> Parse<'a, DecryptorBuilder<'a>>
    for DecryptorBuilder<'a>
{
    fn from_reader<R>(reader: R) -> Result<DecryptorBuilder<'a>>
        where R: io::Read + 'a,
    {
        DecryptorBuilder::new(buffered_reader::Generic::with_cookie(
            reader, None, Default::default()))
    }

    fn from_file<P>(path: P) -> Result<DecryptorBuilder<'a>>
        where P: AsRef<Path>,
    {
        DecryptorBuilder::new(buffered_reader::File::with_cookie(
            path, Default::default())?)
    }

    fn from_bytes<D>(data: &'a D) -> Result<DecryptorBuilder<'a>>
        where D: AsRef<[u8]> + ?Sized,
    {
        DecryptorBuilder::new(buffered_reader::Memory::with_cookie(
            data.as_ref(), Default::default()))
    }
}

impl<'a> DecryptorBuilder<'a> {
    fn new<B>(signatures: B) -> Result<Self>
        where B: buffered_reader::BufferedReader<Cookie> + 'a
    {
        Ok(DecryptorBuilder {
            message: Box::new(signatures),
            buffer_size: DEFAULT_BUFFER_SIZE,
            mapping: false,
        })
    }

    /// Changes the amount of buffered data.
    ///
    /// By default, we buffer up to 25 megabytes of net message data
    /// (see [`DEFAULT_BUFFER_SIZE`]).  This changes the default.
    ///
    ///   [`DEFAULT_BUFFER_SIZE`]: constant.DEFAULT_BUFFER_SIZE.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       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<Fingerprint>>
    /// #       where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
    /// #   {
    /// #       Ok(None)
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = DecryptorBuilder::from_bytes(message)?
    ///     .buffer_size(1 << 12)
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }

    /// Enables mapping.
    ///
    /// If mapping is enabled, the packet parser will create a [`Map`]
    /// of the packets that can be inspected in
    /// [`VerificationHelper::inspect`].  Note that this buffers the
    /// packets contents, and is not recommended unless you know that
    /// the packets are small.
    ///
    ///   [`Map`]: ../map/struct.Map.html
    ///   [`VerificationHelper::inspect`]: trait.VerificationHelper.html#tymethod.inspect
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       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<Fingerprint>>
    /// #       where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
    /// #   {
    /// #       Ok(None)
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = DecryptorBuilder::from_bytes(message)?
    ///     .mapping(true)
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn mapping(mut self, enabled: bool) -> Self {
        self.mapping = enabled;
        self
    }

    /// Creates the `Decryptor`.
    ///
    /// Signature verifications are done under the given `policy` and
    /// relative to time `time`, or the current time, if `time` is
    /// `None`.  `helper` is the [`VerificationHelper`] and
    /// [`DecryptionHelper`] to use.
    ///
    ///   [`VerificationHelper`]: trait.VerificationHelper.html
    ///   [`DecryptionHelper`]: trait.DecryptionHelper.html
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       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<Fingerprint>>
    /// #       where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
    /// #   {
    /// #       Ok(None)
    /// #   }
    /// }
    ///
    /// let message =
    ///     // ...
    /// # &b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..];
    ///
    /// let h = Helper {};
    /// let mut v = DecryptorBuilder::from_bytes(message)?
    ///     // Customize the `Decryptor` here.
    ///     .with_policy(p, None, h)?;
    /// # let _ = v;
    /// # Ok(()) }
    /// ```
    pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
                             -> Result<Decryptor<'a, H>>
        where H: VerificationHelper + DecryptionHelper,
              T: Into<Option<time::SystemTime>>,
    {
        // Do not eagerly map `t` to the current time.
        let t = time.into();
        Decryptor::from_buffered_reader(
            policy,
            self.message,
            helper,
            t, Mode::Decrypt, self.buffer_size, self.mapping)
    }
}

/// Helper for decrypting messages.
///
/// This trait abstracts over session key decryption.  It allows us to
/// provide the [`Decryptor`] without imposing any policy on how the
/// session key is decrypted.
///
///   [`Decryptor`]: struct.Decryptor.html
pub trait DecryptionHelper {
    /// Decrypts the message.
    ///
    /// This function is called with every [`PKESK`] and [`SKESK`]
    /// packet found in the message.  The implementation must decrypt
    /// the symmetric algorithm and session key from one of the
    /// [`PKESK`] packets, the [`SKESK`] packets, or retrieve it from
    /// a cache, and then call `decrypt` with the symmetric algorithm
    /// and session key.  `decrypt` returns `true` if the decryption
    /// was successful.
    ///
    ///   [`PKESK`]: ../../packet/enum.PKESK.html
    ///   [`SKESK`]: ../../packet/enum.SKESK.html
    ///
    /// If a symmetric algorithm is given, it should be passed on to
    /// [`PKESK::decrypt`].
    ///
    ///   [`PKESK::decrypt`]: ../../packet/enum.PKESK.html#method.decrypt
    ///
    /// If the message is decrypted using a [`PKESK`] packet, then the
    /// fingerprint of the certificate containing the encryption
    /// subkey should be returned.  This is used in conjunction with
    /// the intended recipient subpacket (see [Section 5.2.3.29 of RFC
    /// 4880bis]) to prevent [*Surreptitious Forwarding*].
    ///
    ///   [Section 5.2.3.29 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.2.3.29
    ///   [*Surreptitious Forwarding*]: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
    ///
    /// This method will be called once per encryption layer.
    ///
    /// # Examples
    ///
    /// This example demonstrates how to decrypt a message using local
    /// keys (i.e. excluding remote keys like smart cards) while
    /// maximizing convenience for the user.
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::{Fingerprint, Cert, Result};
    /// # use openpgp::KeyID;
    /// use openpgp::crypto::SessionKey;
    /// use openpgp::types::SymmetricAlgorithm;
    /// use openpgp::packet::{PKESK, SKESK};
    /// # use openpgp::packet::{Key, key::*};
    /// use openpgp::parse::stream::*;
    /// # fn lookup_cache(_: &[PKESK], _: &[SKESK])
    /// #                 -> Option<(Option<Fingerprint>, SymmetricAlgorithm, SessionKey)> {
    /// #     unimplemented!()
    /// # }
    /// # fn lookup_key(_: &KeyID)
    /// #               -> Option<(Fingerprint, Key<SecretParts, UnspecifiedRole>)> {
    /// #     unimplemented!()
    /// # }
    /// # fn all_keys() -> impl Iterator<Item = (Fingerprint, Key<SecretParts, UnspecifiedRole>)> {
    /// #     Vec::new().into_iter()
    /// # }
    ///
    /// struct Helper { /* ... */ };
    /// 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
    ///     {
    ///         // Try to decrypt, from the most convenient method to the
    ///         // least convenient one.
    ///
    ///         // First, see if it is in the cache.
    ///         if let Some((fp, algo, sk)) = lookup_cache(pkesks, skesks) {
    ///             if decrypt(algo, &sk) {
    ///                 return Ok(fp);
    ///             }
    ///         }
    ///
    ///         // Second, we try those keys that we can use without
    ///         // prompting for a password.
    ///         for pkesk in pkesks {
    ///             if let Some((fp, key)) = lookup_key(pkesk.recipient()) {
    ///                 if ! key.secret().is_encrypted() {
    ///                     let mut keypair = key.clone().into_keypair()?;
    ///                     if pkesk.decrypt(&mut keypair, sym_algo)
    ///                         .map(|(algo, sk)| decrypt(algo, &sk))
    ///                         .unwrap_or(false)
    ///                     {
    ///                         return Ok(Some(fp));
    ///                     }
    ///                 }
    ///             }
    ///         }
    ///
    ///         // Third, we try to decrypt PKESK packets with
    ///         // wildcard recipients using those keys that we can
    ///         // use without prompting for a password.
    ///         for pkesk in pkesks.iter().filter(|p| p.recipient().is_wildcard()) {
    ///             for (fp, key) in all_keys() {
    ///                 if ! key.secret().is_encrypted() {
    ///                     let mut keypair = key.clone().into_keypair()?;
    ///                     if pkesk.decrypt(&mut keypair, sym_algo)
    ///                         .map(|(algo, sk)| decrypt(algo, &sk))
    ///                         .unwrap_or(false)
    ///                     {
    ///                         return Ok(Some(fp));
    ///                     }
    ///                 }
    ///             }
    ///         }
    ///
    ///         // Fourth, we try to decrypt all PKESK packets that we
    ///         // need encrypted keys for.
    ///         // [...]
    ///
    ///         // Fifth, we try to decrypt all PKESK packets with
    ///         // wildcard recipients using encrypted keys.
    ///         // [...]
    ///
    ///         // At this point, we have exhausted our options at
    ///         // decrypting the PKESK packets.
    ///         if skesks.is_empty() {
    ///             return
    ///                 Err(anyhow::anyhow!("No key to decrypt message"));
    ///         }
    ///
    ///         // Finally, try to decrypt using the SKESKs.
    ///         loop {
    ///             let password = // Prompt for a password.
    /// #               "".into();
    ///
    ///             for skesk in skesks {
    ///                 if skesk.decrypt(&password)
    ///                     .map(|(algo, sk)| decrypt(algo, &sk))
    ///                     .unwrap_or(false)
    ///                 {
    ///                     return Ok(None);
    ///                 }
    ///             }
    ///
    ///             eprintln!("Bad password.");
    ///         }
    ///     }
    /// }
    /// ```
    fn decrypt<D>(&mut self, pkesks: &[PKESK], skesks: &[SKESK],
                  sym_algo: Option<SymmetricAlgorithm>,
                  decrypt: D) -> Result<Option<Fingerprint>>
        where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool;
}

impl<'a, H: VerificationHelper + DecryptionHelper> Decryptor<'a, H> {
    /// Returns a reference to the helper.
    pub fn helper_ref(&self) -> &H {
        &self.helper
    }

    /// Returns a mutable reference to the helper.
    pub fn helper_mut(&mut self) -> &mut H {
        &mut self.helper
    }

    /// Recovers the helper.
    pub fn into_helper(self) -> H {
        self.helper
    }

    /// Returns true if the whole message has been processed and
    /// authenticated.
    ///
    /// If the function returns `true`, the whole message has been
    /// processed, the signatures are verified, and the message
    /// structure has been passed to [`VerificationHelper::check`].
    /// Data read from this `Verifier` using [`io::Read`] has been
    /// authenticated.
    ///
    ///   [`VerificationHelper::check`]: trait.VerificationHelper.html#tymethod.check
    ///   [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
    ///
    /// If the function returns `false`, the message did not fit into
    /// the internal buffer, and therefore data read from this
    /// `Verifier` using [`io::Read`] has **not yet been
    /// authenticated**.  It is important to treat this data as
    /// attacker controlled and not use it until it has been
    /// authenticated.
    ///
    /// # Examples
    ///
    /// This example demonstrates how to verify a message in a
    /// streaming fashion, writing the data to a temporary file and
    /// only commit the result once the data is authenticated.
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use std::io::{Read, Seek, SeekFrom};
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::{KeyHandle, Cert, Result};
    /// use openpgp::parse::{Parse, stream::*};
    /// use openpgp::policy::StandardPolicy;
    /// #
    /// # // Mock of `tempfile::tempfile`.
    /// # mod tempfile {
    /// #     pub fn tempfile() -> sequoia_openpgp::Result<std::fs::File> {
    /// #         unimplemented!()
    /// #     }
    /// # }
    ///
    /// let p = &StandardPolicy::new();
    ///
    /// // This fetches keys and computes the validity of the verification.
    /// struct Helper {};
    /// impl VerificationHelper for Helper {
    ///     // ...
    /// #   fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
    /// #       Ok(Vec::new())
    /// #   }
    /// #   fn check(&mut self, _: MessageStructure) -> Result<()> {
    /// #       Ok(())
    /// #   }
    /// }
    ///
    /// let mut source =
    ///    // ...
    /// #  std::io::Cursor::new(&b"-----BEGIN PGP MESSAGE-----
    /// #
    /// #    xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
    /// #    AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
    /// #    UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
    /// #    YmAFv/UfO0vYBw==
    /// #    =+l94
    /// #    -----END PGP MESSAGE-----
    /// #    "[..]);
    ///
    /// fn consume(r: &mut dyn Read) -> Result<()> {
    ///    // ...
    /// #   let _ = r; Ok(())
    /// }
    ///
    /// let h = Helper {};
    /// let mut v = VerifierBuilder::from_reader(&mut source)?
    ///     .with_policy(p, None, h)?;
    ///
    /// if v.message_processed() {
    ///     // The data has been authenticated.
    ///     consume(&mut v)?;
    /// } else {
    ///     let mut tmp = tempfile::tempfile()?;
    ///     std::io::copy(&mut v, &mut tmp)?;
    ///
    ///     // If the copy succeeds, the message has been fully
    ///     // processed and the data has been authenticated.
    ///     assert!(v.message_processed());
    ///
    ///     // Rewind and consume.
    ///     tmp.seek(SeekFrom::Start(0))?;
    ///     consume(&mut tmp)?;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn message_processed(&self) -> bool {
        // oppr is only None after we've processed the packet sequence.
        self.oppr.is_none()
    }

    /// Creates the `Decryptor`, and buffers the data up to `buffer_size`.
    fn from_buffered_reader<T>(
        policy: &'a dyn Policy,
        bio: Box<dyn BufferedReader<Cookie> + 'a>,
        helper: H, time: T,
        mode: Mode,
        buffer_size: usize,
        mapping: bool)
        -> Result<Decryptor<'a, H>>
        where T: Into<Option<time::SystemTime>>
    {
        tracer!(TRACE, "Decryptor::from_buffered_reader", 0);

        let time = time.into();
        let tolerance = time
            .map(|_| time::Duration::new(0, 0))
            .unwrap_or(
                *crate::packet::signature::subpacket::CLOCK_SKEW_TOLERANCE);
        let time = time.unwrap_or_else(time::SystemTime::now);

        let mut ppr = PacketParserBuilder::from_buffered_reader(bio)?
            .map(mapping).build()?;

        let mut v = Decryptor {
            helper,
            certs: Vec::new(),
            oppr: None,
            identity: None,
            structure: IMessageStructure::new(),
            buffer_size,
            reserve: None,
            cursor: 0,
            mode,
            time,
            clock_skew_tolerance: tolerance,
            policy,
        };

        let mut issuers = Vec::new();
        let mut pkesks: Vec<packet::PKESK> = Vec::new();
        let mut skesks: Vec<packet::SKESK> = Vec::new();
        let mut saw_content = false;

        while let PacketParserResult::Some(mut pp) = ppr {
            v.policy.packet(&pp.packet)?;
            v.helper.inspect(&pp)?;

            // When verifying detached signatures, we parse only the
            // signatures here, which on their own are not a valid
            // message.
            if v.mode != Mode::VerifyDetached {
                if let Err(err) = pp.possible_message() {
                    t!("Malformed message: {}", err);
                    return Err(err.context("Malformed OpenPGP message").into());
                }
            }

            let sym_algo_hint = if let Packet::AED(ref aed) = pp.packet {
                Some(aed.symmetric_algo())
            } else {
                None
            };

            match pp.packet {
                Packet::CompressedData(ref p) =>
                    v.structure.new_compression_layer(p.algo()),
                Packet::SEIP(_) | Packet::AED(_) if v.mode == Mode::Decrypt => {
                    saw_content = true;

                    // Get the symmetric algorithm from the decryption
                    // proxy function.  This is necessary because we
                    // cannot get the algorithm from the SEIP packet.
                    let mut sym_algo = None;
                    {
                        let decryption_proxy = |algo, secret: &SessionKey| {
                            let result = pp.decrypt(algo, secret);
                            if let Ok(_) = result {
                                sym_algo = Some(algo);
                                true
                            } else {
                                false
                            }
                        };

                        v.identity =
                            v.helper.decrypt(&pkesks[..], &skesks[..],
                                             sym_algo_hint,
                                             decryption_proxy)?;
                    }
                    if pp.encrypted() {
                        return Err(
                            Error::MissingSessionKey(
                                "No session key decrypted".into()).into());
                    }

                    let sym_algo =
                        sym_algo.expect("if we got here, sym_algo is set");
                    v.policy.symmetric_algorithm(sym_algo)?;
                    if let Packet::AED(ref p) = pp.packet {
                        v.policy.aead_algorithm(p.aead())?;
                    }

                    v.structure.new_encryption_layer(
                        sym_algo,
                        if let Packet::AED(ref p) = pp.packet {
                            Some(p.aead())
                        } else {
                            None
                        });
                },
                Packet::OnePassSig(ref ops) => {
                    v.structure.push_ops(ops);
                    issuers.push(ops.issuer().clone().into());
                },
                Packet::Literal(_) => {
                    v.structure.insert_missing_signature_group();
                    // Query keys.
                    v.certs = v.helper.get_certs(&issuers)?;
                    v.oppr = Some(PacketParserResult::Some(pp));
                    v.finish_maybe()?;

                    return Ok(v);
                },
                Packet::MDC(ref mdc) => if ! mdc.valid() {
                    return Err(Error::ManipulatedMessage.into());
                },
                _ => (),
            }

            let (p, ppr_tmp) = pp.recurse()?;
            match p {
                Packet::PKESK(pkesk) => pkesks.push(pkesk),
                Packet::SKESK(skesk) => skesks.push(skesk),
                Packet::Signature(sig) => {
                    if ! saw_content {
                        // The following structure is allowed:
                        //
                        //   SIG LITERAL
                        //
                        // In this case, we get the issuer from the
                        // signature itself.
                        let mut sig_issuers = sig.get_issuers();
                        if sig_issuers.is_empty() {
                            // No issuer information.  Push a wildcard
                            // KeyID to indicate this to the
                            // VerificationHelper::check.  This is the
                            // detached-signature equivalent of a
                            // signed message with a wildcard signer
                            // KeyID on the OPS packet and no issuer
                            // information on the signature.
                            issuers.push(KeyID::wildcard().into());
                        } else {
                            issuers.append(&mut sig_issuers);
                        }
                    }
                    v.structure.push_bare_signature(sig);
                }
                _ => (),
            }
            ppr = ppr_tmp;
        }

        if v.mode == Mode::VerifyDetached {
            v.certs = v.helper.get_certs(&issuers)?;
            return Ok(v);
        }

        // We can only get here if we didn't encounter a literal data
        // packet.
        Err(Error::MalformedMessage(
            "Malformed OpenPGP message".into()).into())
    }

    /// Verifies the given data in detached verification mode.
    fn verify_detached<D>(&mut self, data: D) -> Result<()>
        where D: BufferedReader<Cookie>
    {
        assert_eq!(self.mode, Mode::VerifyDetached);

        let sigs = if let IMessageLayer::SignatureGroup {
            sigs, .. } = &mut self.structure.layers[0] {
            sigs
        } else {
            unreachable!("There is exactly one signature group layer")
        };

        // Compute the necessary hashes.
        let algos: Vec<_> = sigs.iter().map(|s| {
            HashingMode::for_signature(s.hash_algo(), s.typ())
        }).collect();
        let hashes =
            crate::parse::hashed_reader::hash_buffered_reader(data, &algos)?;

        // Attach the digests.
        for sig in sigs.iter_mut() {
            let need_hash =
                HashingMode::for_signature(sig.hash_algo(), sig.typ());
            // Note: |hashes| < 10, most likely 1.
            for mode in hashes.iter()
                .filter(|m| m.map(|c| c.algo()) == need_hash)
            {
                // Clone the hash context, update it with the
                // signature.
                use crate::crypto::hash::Hash;
                let mut hash = mode.as_ref().clone();
                sig.hash(&mut hash);

                // Attach digest to the signature.
                let mut digest = vec![0; hash.digest_size()];
                let _ = hash.digest(&mut digest);
                sig.set_computed_digest(Some(digest.into()));
            }
        }

        self.verify_signatures()
    }

    /// Stashes the given Signature (if it is one) for later
    /// verification.
    fn push_sig(&mut self, p: Packet) -> Result<()> {
        match p {
            Packet::Signature(sig) => {
                self.structure.push_signature(sig);
            },
            _ => (),
        }
        Ok(())
    }

    // If the amount of remaining data does not exceed the reserve,
    // finish processing the OpenPGP packet sequence.
    //
    // Note: once this call succeeds, you may not call it again.
    fn finish_maybe(&mut self) -> Result<()> {
        if let Some(PacketParserResult::Some(mut pp)) = self.oppr.take() {
            // Check if we hit EOF.
            let data_len = pp.data(self.buffer_size + 1)?.len();
            if data_len <= self.buffer_size {
                // Stash the reserve.
                self.reserve = Some(pp.steal_eof()?);
                self.cursor = 0;

                // Process the rest of the packets.
                let mut ppr = PacketParserResult::Some(pp);
                let mut first = true;
                while let PacketParserResult::Some(pp) = ppr {
                    // The literal data packet was already inspected.
                    if first {
                        assert_eq!(pp.packet.tag(), packet::Tag::Literal);
                        first = false;
                    } else {
                        self.helper.inspect(&pp)?;
                    }

                    if let Err(err) = pp.possible_message() {
                        return Err(err.context(
                            "Malformed OpenPGP message").into());
                    }

                    match pp.packet {
                        Packet::MDC(ref mdc) => if ! mdc.valid() {
                            return Err(Error::ManipulatedMessage.into());
                        }
                        _ => (),
                    }

                    let (p, ppr_tmp) = pp.recurse()?;
                    self.push_sig(p)?;
                    ppr = ppr_tmp;
                }

                self.verify_signatures()
            } else {
                self.oppr = Some(PacketParserResult::Some(pp));
                Ok(())
            }
        } else {
            panic!("No ppr.");
        }
    }

    /// Verifies the signatures.
    fn verify_signatures(&mut self) -> Result<()> {
        tracer!(TRACE, "Decryptor::verify_signatures", 0);
        t!("called");

        let mut results = MessageStructure::new();
        for layer in self.structure.layers.iter_mut() {
            match layer {
                IMessageLayer::Compression { algo } =>
                    results.new_compression_layer(*algo),
                IMessageLayer::Encryption { sym_algo, aead_algo } =>
                    results.new_encryption_layer(*sym_algo, *aead_algo),
                IMessageLayer::SignatureGroup { sigs, .. } => {
                    results.new_signature_group();
                    'sigs: for sig in sigs.iter_mut() {
                        let sigid = sig.digest_prefix().clone();

                        let sig_time = if let Some(t) = sig.signature_creation_time() {
                            t
                        } else {
                            // Invalid signature.
                            results.push_verification_result(
                                Err(VerificationError::MalformedSignature {
                                    sig,
                                    error: Error::MalformedPacket(
                                        "missing a Signature Creation Time \
                                         subpacket"
                                            .into()).into(),
                                }));
                            t!("{:02X}{:02X}: Missing a signature creation time subpacket",
                               sigid[0], sigid[1]);
                            continue;
                        };

                        let mut err = VerificationErrorInternal::MissingKey {};

                        let issuers = sig.get_issuers();
                        // Note: If there are no issuers, the only way
                        // to verify the signature is to try every key
                        // that could possibly have created the
                        // signature.  While this may be feasible if
                        // the set of potential signing keys is small,
                        // the use case of hiding the signer's
                        // identity seems better solved using
                        // encryption.  Furthermore, no other OpenPGP
                        // implementation seems to support this kind
                        // of wildcard signatures.
                        //
                        // If there are no issuers, this iterator will
                        // not yield any keys, hence this verification
                        // will fail with the default error,
                        // `VerificationError::MissingKey`.
                        for ka in self.certs.iter()
                            .flat_map(|cert| {
                                cert.keys().key_handles(issuers.iter())
                            })
                        {
                            let cert = ka.cert();
                            let fingerprint = ka.fingerprint();
                            let ka = match ka.with_policy(self.policy, sig_time) {
                                Err(policy_err) => {
                                    t!("{:02X}{:02X}: key {} rejected by policy: {}",
                                       sigid[0], sigid[1], fingerprint, policy_err);
                                    err = VerificationErrorInternal::UnboundKey {
                                        cert,
                                        error: policy_err,
                                    };
                                    continue;
                                }
                                Ok(ka) => {
                                    t!("{:02X}{:02X}: key {} accepted by policy",
                                       sigid[0], sigid[1], fingerprint);
                                    ka
                                }
                            };

                            err = if let Err(error) = ka.cert().alive() {
                                t!("{:02X}{:02X}: cert {} not alive: {}",
                                   sigid[0], sigid[1], ka.cert().fingerprint(), error);
                                VerificationErrorInternal::BadKey {
                                    ka,
                                    error,
                                }
                            } else if let Err(error) = ka.alive() {
                                t!("{:02X}{:02X}: key {} not alive: {}",
                                   sigid[0], sigid[1], ka.fingerprint(), error);
                                VerificationErrorInternal::BadKey {
                                    ka,
                                    error,
                                }
                            } else if let
                                RevocationStatus::Revoked(rev) = ka.cert().revocation_status()
                            {
                                t!("{:02X}{:02X}: cert {} revoked: {:?}",
                                   sigid[0], sigid[1], ka.cert().fingerprint(), rev);
                                VerificationErrorInternal::BadKey {
                                    ka,
                                    error: Error::InvalidKey(
                                        "certificate is revoked".into())
                                        .into(),
                                }
                            } else if let
                                RevocationStatus::Revoked(rev) = ka.revocation_status()
                            {
                                t!("{:02X}{:02X}: key {} revoked: {:?}",
                                   sigid[0], sigid[1], ka.fingerprint(), rev);
                                VerificationErrorInternal::BadKey {
                                    ka,
                                    error: Error::InvalidKey(
                                        "signing key is revoked".into())
                                        .into(),
                                }
                            } else if ! ka.for_signing() {
                                t!("{:02X}{:02X}: key {} not signing capable",
                                   sigid[0], sigid[1], ka.fingerprint());
                                VerificationErrorInternal::BadKey {
                                    ka,
                                    error: Error::InvalidKey(
                                        "key is not signing capable".into())
                                        .into(),
                                }
                            } else if let Err(error) = sig.signature_alive(
                                self.time, self.clock_skew_tolerance)
                            {
                                t!("{:02X}{:02X}: Signature not alive: {}",
                                   sigid[0], sigid[1], error);
                                VerificationErrorInternal::BadSignature {
                                    ka,
                                    error,
                                }
                            } else if self.identity.as_ref().map(|identity| {
                                let (have_one, contains_identity) =
                                    sig.intended_recipients()
                                        .fold((false, false),
                                              |(_, contains_one), ir| {
                                                  (
                                                      true,
                                                      contains_one || identity == ir
                                                  )
                                              });
                                have_one && ! contains_identity
                            }).unwrap_or(false) {
                                // The signature contains intended
                                // recipients, but we are not one.
                                // Treat the signature as bad.
                                t!("{:02X}{:02X}: not an intended recipient",
                                   sigid[0], sigid[1]);
                                VerificationErrorInternal::BadSignature {
                                    ka,
                                    error: Error::BadSignature(
                                        "Not an intended recipient".into())
                                        .into(),
                                }
                            } else {
                                match sig.verify(ka.key()) {
                                    Ok(()) => {
                                        if let Err(error) = self.policy.signature(&sig) {
                                            t!("{:02X}{:02X}: signature rejected by policy: {}",
                                               sigid[0], sigid[1], error);
                                            VerificationErrorInternal::BadSignature {
                                                ka,
                                                error,
                                            }
                                        } else {
                                            t!("{:02X}{:02X}: good checksum using {}",
                                               sigid[0], sigid[1], ka.fingerprint());
                                            results.push_verification_result(
                                                Ok(GoodChecksum {
                                                    sig: sig,
                                                    ka,
                                                }));
                                            // Continue to the next sig.
                                            continue 'sigs;
                                        }
                                    }
                                    Err(error) => {
                                        t!("{:02X}{:02X} using {}: error: {}",
                                           sigid[0], sigid[1], ka.fingerprint(), error);
                                        VerificationErrorInternal::BadSignature {
                                            ka,
                                            error,
                                        }
                                    }
                                }
                            }
                        }

                        let err = err.attach_sig(sig);
                        t!("{:02X}{:02X}: returning: {:?}", sigid[0], sigid[1], err);
                        results.push_verification_result(Err(err));
                    }
                }
            }
        }

        let r = self.helper.check(results);
        t!("-> {:?}", r);
        r
    }

    /// Like `io::Read::read()`, but returns our `Result`.
    fn read_helper(&mut self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() == 0 {
            return Ok(0);
        }

        if let Some(ref mut reserve) = self.reserve {
            // The message has been verified.  We can now drain the
            // reserve.
            assert!(self.oppr.is_none());
            assert!(self.cursor <= reserve.len());
            let n = cmp::min(buf.len(), reserve.len() - self.cursor);
            &mut buf[..n]
                .copy_from_slice(&reserve[self.cursor..n + self.cursor]);
            self.cursor += n;
            return Ok(n);
        }

        // Read the data from the Literal data packet.
        if let Some(PacketParserResult::Some(mut pp)) = self.oppr.take() {
            // Be careful to not read from the reserve.
            let data_len = pp.data(self.buffer_size + buf.len())?.len();
            if data_len <= self.buffer_size {
                self.oppr = Some(PacketParserResult::Some(pp));
                self.finish_maybe()?;
                self.read_helper(buf)
            } else {
                let n = cmp::min(buf.len(), data_len - self.buffer_size);
                let buf = &mut buf[..n];
                let result = pp.read(buf);
                self.oppr = Some(PacketParserResult::Some(pp));
                Ok(result?)
            }
        } else {
            panic!("No ppr.");
        }
    }
}

impl<'a, H: VerificationHelper + DecryptionHelper> io::Read for Decryptor<'a, H>
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.read_helper(buf) {
            Ok(n) => Ok(n),
            Err(e) => match e.downcast::<io::Error>() {
                // An io::Error.  Pass as-is.
                Ok(e) => Err(e),
                // A failure.  Wrap it.
                Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
            },
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::convert::TryFrom;
    use crate::parse::Parse;
    use crate::policy::StandardPolicy as P;
    use crate::serialize::Serialize;

    #[derive(PartialEq)]
    struct VHelper {
        good: usize,
        unknown: usize,
        bad: usize,
        error: usize,
        keys: Vec<Cert>,
        error_out: bool,
    }

    impl std::fmt::Debug for VHelper {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.debug_struct("VHelper")
                .field("good", &self.good)
                .field("unknown", &self.unknown)
                .field("bad", &self.bad)
                .field("error", &self.error)
                .field("error_out", &self.error_out)
                .finish()
        }
    }

    impl Default for VHelper {
        fn default() -> Self {
            VHelper {
                good: 0,
                unknown: 0,
                bad: 0,
                error: 0,
                keys: Vec::default(),
                error_out: true,
            }
        }
    }

    impl VHelper {
        fn new(good: usize, unknown: usize, bad: usize, error: usize, keys: Vec<Cert>) -> Self {
            VHelper {
                good,
                unknown,
                bad,
                error,
                keys,
                error_out: true,
            }
        }
    }

    impl VerificationHelper for VHelper {
        fn get_certs(&mut self, _ids: &[crate::KeyHandle]) -> Result<Vec<Cert>> {
            Ok(self.keys.clone())
        }

        fn check(&mut self, structure: MessageStructure) -> Result<()> {
            use self::VerificationError::*;
            for layer in structure.iter() {
                match layer {
                    MessageLayer::SignatureGroup { ref results } =>
                        for result in results {
                            match result {
                                Ok(_) => self.good += 1,
                                Err(MissingKey { .. }) => self.unknown += 1,
                                Err(UnboundKey { .. }) => self.unknown += 1,
                                Err(MalformedSignature { .. }) => self.bad += 1,
                                Err(BadKey { .. }) => self.bad += 1,
                                Err(BadSignature { error, .. }) => {
                                    eprintln!("error: {}", error);
                                    self.bad += 1;
                                },
                            }
                        }
                    MessageLayer::Compression { .. } => (),
                    _ => unreachable!(),
                }
            }

            if ! self.error_out || (self.good > 0 && self.bad == 0) {
                Ok(())
            } else {
                Err(anyhow::anyhow!("Verification failed: {:?}", self))
            }
        }
    }

    impl DecryptionHelper for VHelper {
        fn decrypt<D>(&mut self, _: &[PKESK], _: &[SKESK],
                      _: Option<SymmetricAlgorithm>, _: D)
                      -> Result<Option<Fingerprint>>
            where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
        {
            unreachable!();
        }
    }

    #[test]
    fn verifier() -> Result<()> {
        let p = P::new();

        let keys = [
            "neal.pgp",
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"
        ].iter()
         .map(|f| Cert::from_bytes(crate::tests::key(f)).unwrap())
         .collect::<Vec<_>>();
        let tests = &[
            ("messages/signed-1.gpg",                      VHelper::new(1, 0, 0, 0, keys.clone())),
            ("messages/signed-1-sha256-testy.gpg",         VHelper::new(0, 1, 0, 0, keys.clone())),
            ("messages/signed-1-notarized-by-ed25519.pgp", VHelper::new(2, 0, 0, 0, keys.clone())),
            ("keys/neal.pgp",                              VHelper::new(0, 0, 0, 1, keys.clone())),
        ];

        let reference = crate::tests::manifesto();

        for (f, r) in tests {
            eprintln!("{}...", f);

            // Test Verifier.
            let h = VHelper::new(0, 0, 0, 0, keys.clone());
            let mut v =
                match VerifierBuilder::from_bytes(crate::tests::file(f))?
                    .with_policy(&p, crate::frozen_time(), h) {
                    Ok(v) => v,
                    Err(e) => if r.error > 0 || r.unknown > 0 {
                        // Expected error.  No point in trying to read
                        // something.
                        continue;
                    } else {
                        panic!("{}: {}", f, e);
                    },
                };
            assert!(v.message_processed());
            assert_eq!(v.helper_ref(), r);

            if v.helper_ref().error > 0 {
                // Expected error.  No point in trying to read
                // something.
                continue;
            }

            let mut content = Vec::new();
            v.read_to_end(&mut content).unwrap();
            assert_eq!(reference.len(), content.len());
            assert_eq!(reference, &content[..]);

            // Test Decryptor.
            let h = VHelper::new(0, 0, 0, 0, keys.clone());
            let mut v = match DecryptorBuilder::from_bytes(crate::tests::file(f))?
                .with_policy(&p, crate::frozen_time(), h) {
                    Ok(v) => v,
                    Err(e) => if r.error > 0 || r.unknown > 0 {
                        // Expected error.  No point in trying to read
                        // something.
                        continue;
                    } else {
                        panic!("{}: {}", f, e);
                    },
                };
            assert!(v.message_processed());
            assert_eq!(v.helper_ref(), r);

            if v.helper_ref().error > 0 {
                // Expected error.  No point in trying to read
                // something.
                continue;
            }

            let mut content = Vec::new();
            v.read_to_end(&mut content).unwrap();
            assert_eq!(reference.len(), content.len());
            assert_eq!(reference, &content[..]);
        }
        Ok(())
    }

    /// Tests legacy two-pass signature scheme, corner cases.
    ///
    /// XXX: This test needs to be adapted once
    /// https://gitlab.com/sequoia-pgp/sequoia/-/issues/128 is
    /// implemented.
    #[test]
    fn verifier_legacy() -> Result<()> {
        let packets = crate::PacketPile::from_bytes(
            crate::tests::message("signed-1.gpg")
        )?
            .into_children()
            .collect::<Vec<_>>();

        fn check(msg: &str, buf: &[u8], expect_good: usize) -> Result<()> {
            eprintln!("{}...", msg);
            let p = P::new();

            let keys = [
                "neal.pgp",
            ]
                .iter()
                .map(|f| Cert::from_bytes(crate::tests::key(f)).unwrap())
                .collect::<Vec<_>>();

            let mut h = VHelper::new(0, 0, 0, 0, keys.clone());
            h.error_out = false;
            let mut v = VerifierBuilder::from_bytes(buf)?
                .with_policy(&p, crate::frozen_time(), h)?;
            assert!(v.message_processed());
            assert_eq!(v.helper_ref().good, expect_good);

            let mut content = Vec::new();
            v.read_to_end(&mut content).unwrap();
            let reference = crate::tests::manifesto();
            assert_eq!(reference.len(), content.len());
            assert_eq!(reference, &content[..]);
            Ok(())
        }

        // Bare legacy signed message: SIG Literal
        let mut o = Vec::new();
        packets[2].serialize(&mut o)?;
        packets[1].serialize(&mut o)?;
        check("bare", &o, 0 /* XXX: should be 1 once #128 is implemented.  */)?;

        // Legacy signed message, two signatures: SIG SIG Literal
        let mut o = Vec::new();
        packets[2].serialize(&mut o)?;
        packets[2].serialize(&mut o)?;
        packets[1].serialize(&mut o)?;
        check("double", &o, 0 /* XXX: should be 2 once #128 is implemented.  */)?;

        // Weird legacy signed message: OPS SIG Literal SIG
        let mut o = Vec::new();
        packets[0].serialize(&mut o)?;
        packets[2].serialize(&mut o)?;
        packets[1].serialize(&mut o)?;
        packets[2].serialize(&mut o)?;
        check("weird", &o, 0 /* XXX: should be 2 once #128 is implemented.  */)?;

        // Fubar legacy signed message: SIG OPS Literal SIG
        let mut o = Vec::new();
        packets[2].serialize(&mut o)?;
        packets[0].serialize(&mut o)?;
        packets[1].serialize(&mut o)?;
        packets[2].serialize(&mut o)?;
        check("fubar", &o, 1 /* XXX: should be 2 once #128 is implemented.  */)?;

        Ok(())
    }

    /// Tests the order of signatures given to
    /// VerificationHelper::check().
    #[test]
    fn verifier_levels() -> Result<()> {
        let p = P::new();

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

            fn check(&mut self, structure: MessageStructure) -> Result<()> {
                assert_eq!(structure.len(), 2);
                for (i, layer) in structure.into_iter().enumerate() {
                    match layer {
                        MessageLayer::SignatureGroup { results } => {
                            assert_eq!(results.len(), 1);
                            if let Err(VerificationError::MissingKey {
                                sig, ..
                            }) = &results[0] {
                                assert_eq!(
                                    &sig.issuer_fingerprints().nth(0).unwrap()
                                        .to_string(),
                                    match i {
                                        0 => "8E8C 33FA 4626 3379 76D9  7978 069C 0C34 8DD8 2C19",
                                        1 => "C03F A641 1B03 AE12 5764  6118 7223 B566 78E0 2528",
                                        _ => unreachable!(),
                                    }
                                );
                            } else {
                                unreachable!()
                            }
                        },
                        _ => unreachable!(),
                    }
                }
                Ok(())
            }
        }
        impl DecryptionHelper for VHelper {
            fn decrypt<D>(&mut self, _: &[PKESK], _: &[SKESK],
                          _: Option<SymmetricAlgorithm>, _: D)
                          -> Result<Option<Fingerprint>>
                where D: FnMut(SymmetricAlgorithm, &SessionKey) -> bool
            {
                unreachable!();
            }
        }

        // Test verifier.
        let v = VerifierBuilder::from_bytes(
            crate::tests::message("signed-1-notarized-by-ed25519.pgp"))?
            .with_policy(&p, crate::frozen_time(), VHelper(()))?;
        assert!(v.message_processed());

        // Test decryptor.
        let v = DecryptorBuilder::from_bytes(
            crate::tests::message("signed-1-notarized-by-ed25519.pgp"))?
            .with_policy(&p, crate::frozen_time(), VHelper(()))?;
        assert!(v.message_processed());
        Ok(())
    }

    #[test]
    fn detached_verifier() {
        lazy_static::lazy_static! {
            static ref ZEROS: Vec<u8> = vec![0; 100 * 1024 * 1024];
        }

        let p = P::new();

        struct Test<'a> {
            sig: &'a [u8],
            content: &'a [u8],
            reference: time::SystemTime,
        };
        let tests = [
            Test {
                sig: crate::tests::message(
                    "a-cypherpunks-manifesto.txt.ed25519.sig"),
                content: crate::tests::manifesto(),
                reference: crate::frozen_time(),
            },
            Test {
                sig: crate::tests::message(
                    "emmelie-dorothea-dina-samantha-awina-detached-signature-of-100MB-of-zeros.sig"),
                content: &ZEROS[..],
                reference:
                crate::types::Timestamp::try_from(1572602018).unwrap().into(),
            },
        ];

        let keys = [
            "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"
        ].iter()
            .map(|f| Cert::from_bytes(crate::tests::key(f)).unwrap())
            .collect::<Vec<_>>();

        for test in tests.iter() {
            let sig = test.sig;
            let content = test.content;
            let reference = test.reference;

            let h = VHelper::new(0, 0, 0, 0, keys.clone());
            let mut v = DetachedVerifierBuilder::from_bytes(sig).unwrap()
                .with_policy(&p, reference, h).unwrap();
            v.verify_bytes(content).unwrap();

            let h = v.into_helper();
            assert_eq!(h.good, 1);
            assert_eq!(h.bad, 0);
        }
    }

    #[test]
    fn verify_long_message() -> Result<()> {
        use std::io::Write;
        use crate::serialize::stream::{LiteralWriter, Signer, Message};

        let p = &P::new();

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

        // sign 3MiB message
        let mut buf = vec![];
        {
            let key = cert.keys().with_policy(p, None).for_signing().nth(0).unwrap().key();
            let keypair =
                key.clone().parts_into_secret().unwrap()
                .into_keypair().unwrap();

            let m = Message::new(&mut buf);
            let signer = Signer::new(m, keypair).build().unwrap();
            let mut ls = LiteralWriter::new(signer).build().unwrap();

            ls.write_all(&mut vec![42u8; 3 * 1024 * 1024]).unwrap();
            ls.finalize().unwrap();
        }

        // Test Verifier.
        let h = VHelper::new(0, 0, 0, 0, vec![cert.clone()]);
        let mut v = VerifierBuilder::from_bytes(&buf)?
            .buffer_size(2 * 2usize.pow(20))
            .with_policy(p, None, h)?;

        assert!(!v.message_processed());
        assert!(v.helper_ref().good == 0);
        assert!(v.helper_ref().bad == 0);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        let mut message = Vec::new();

        v.read_to_end(&mut message).unwrap();

        assert!(v.message_processed());
        assert_eq!(3 * 1024 * 1024, message.len());
        assert!(message.iter().all(|&b| b == 42));
        assert!(v.helper_ref().good == 1);
        assert!(v.helper_ref().bad == 0);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        // Try the same, but this time we let .check() fail.
        let h = VHelper::new(0, 0, /* makes check() fail: */ 1, 0,
                             vec![cert.clone()]);
        let mut v = VerifierBuilder::from_bytes(&buf)?
            .buffer_size(2 * 2usize.pow(20))
            .with_policy(p, None, h)?;

        assert!(!v.message_processed());
        assert!(v.helper_ref().good == 0);
        assert!(v.helper_ref().bad == 1);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        let mut message = Vec::new();
        let r = v.read_to_end(&mut message);
        assert!(r.is_err());

        // Check that we only got a truncated message.
        assert!(v.message_processed());
        assert!(message.len() > 0);
        assert!(message.len() <= 1 * 1024 * 1024);
        assert!(message.iter().all(|&b| b == 42));
        assert!(v.helper_ref().good == 1);
        assert!(v.helper_ref().bad == 1);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        // Test Decryptor.
        let h = VHelper::new(0, 0, 0, 0, vec![cert.clone()]);
        let mut v = DecryptorBuilder::from_bytes(&buf)?
            .buffer_size(2 * 2usize.pow(20))
            .with_policy(p, None, h)?;

        assert!(!v.message_processed());
        assert!(v.helper_ref().good == 0);
        assert!(v.helper_ref().bad == 0);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        let mut message = Vec::new();

        v.read_to_end(&mut message).unwrap();

        assert!(v.message_processed());
        assert_eq!(3 * 1024 * 1024, message.len());
        assert!(message.iter().all(|&b| b == 42));
        assert!(v.helper_ref().good == 1);
        assert!(v.helper_ref().bad == 0);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        // Try the same, but this time we let .check() fail.
        let h = VHelper::new(0, 0, /* makes check() fail: */ 1, 0,
                             vec![cert.clone()]);
        let mut v = DecryptorBuilder::from_bytes(&buf)?
            .buffer_size(2 * 2usize.pow(20))
            .with_policy(p, None, h)?;

        assert!(!v.message_processed());
        assert!(v.helper_ref().good == 0);
        assert!(v.helper_ref().bad == 1);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);

        let mut message = Vec::new();
        let r = v.read_to_end(&mut message);
        assert!(r.is_err());

        // Check that we only got a truncated message.
        assert!(v.message_processed());
        assert!(message.len() > 0);
        assert!(message.len() <= 1 * 1024 * 1024);
        assert!(message.iter().all(|&b| b == 42));
        assert!(v.helper_ref().good == 1);
        assert!(v.helper_ref().bad == 1);
        assert!(v.helper_ref().unknown == 0);
        assert!(v.helper_ref().error == 0);
        Ok(())
    }
}