summaryrefslogtreecommitdiffstats
path: root/comm/mail/extensions/openpgp/content/modules/RNP.jsm
blob: c6969842c80e66e74ab3b346652298a5dae7a39a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const EXPORTED_SYMBOLS = ["RNP", "RnpPrivateKeyUnlockTracker"];

const { AppConstants } = ChromeUtils.importESModule(
  "resource://gre/modules/AppConstants.sys.mjs"
);
const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ctypes: "resource://gre/modules/ctypes.sys.mjs",
});

XPCOMUtils.defineLazyModuleGetters(lazy, {
  EnigmailConstants: "chrome://openpgp/content/modules/constants.jsm",
  EnigmailFuncs: "chrome://openpgp/content/modules/funcs.jsm",
  GPGME: "chrome://openpgp/content/modules/GPGME.jsm",
  OpenPGPMasterpass: "chrome://openpgp/content/modules/masterpass.jsm",
  PgpSqliteDb2: "chrome://openpgp/content/modules/sqliteDb.jsm",
  RNPLibLoader: "chrome://openpgp/content/modules/RNPLib.jsm",
});

var l10n = new Localization(["messenger/openpgp/openpgp.ftl"]);

const str_encrypt = "encrypt";
const str_sign = "sign";
const str_certify = "certify";
const str_authenticate = "authenticate";
const RNP_PHOTO_USERID_ID = "(photo)"; // string is hardcoded inside RNP

var RNPLib;

/**
 * Opens a prompt, asking the user to enter passphrase for given key id.

 * @param {?nsIWindow} win - Parent window, may be null
 * @param {string} promptString - This message will be shown to the user
 * @param {object} resultFlags - Attribute .canceled is set to true
 *   if the user clicked cancel, other it's set to false.
 * @returns {string} - The passphrase the user entered
 */
function passphrasePromptCallback(win, promptString, resultFlags) {
  let password = { value: "" };
  if (!Services.prompt.promptPassword(win, "", promptString, password)) {
    resultFlags.canceled = true;
    return "";
  }

  resultFlags.canceled = false;
  return password.value;
}

/**
 * Helper class to track resources related to a private/secret key,
 * holding the key handle obtained from RNP, and offering services
 * related to that key and its handle, including releasing the handle
 * when done. Tracking a null handle is allowed.
 */
class RnpPrivateKeyUnlockTracker {
  #rnpKeyHandle = null;
  #wasUnlocked = false;
  #allowPromptingUserForPassword = false;
  #allowAutoUnlockWithCachedPasswords = false;
  #passwordCache = null;
  #fingerprint = "";
  #passphraseCallback = null;
  #rememberUnlockPasswordForUnprotect = false;
  #unlockPassword = null;
  #isLocked = true;

  /**
   * Initialize this object as a tracker for the private key identified
   * by the given fingerprint. The fingerprint will be looked up in an
   * RNP space (FFI) and the resulting handle will be tracked. The
   * default FFI is used for performing the lookup, unless a specific
   * FFI is given. If no key can be found, the object is initialized
   * with a null handle. If a handle was found, the handle and any
   * additional resources can be freed by calling the object's release()
   * method.
   *
   * @param {string} fingerprint - the fingerprint of a key to look up.
   * @param {rnp_ffi_t} ffi - An optional specific FFI.
   * @returns {RnpPrivateKeyUnlockTracker} - a new instance, which was
   *   either initialized with a found key handle, or with null-
   */
  static constructFromFingerprint(fingerprint, ffi = RNPLib.ffi) {
    if (fingerprint.startsWith("0x")) {
      throw new Error("fingerprint must not start with 0x");
    }

    let handle = RNP.getKeyHandleByKeyIdOrFingerprint(ffi, `0x${fingerprint}`);

    return new RnpPrivateKeyUnlockTracker(handle);
  }

  /**
   * Construct this object as a tracker for the private key referenced
   * by the given handle. The object may also be initialized
   * with null, if no key was found. A valid handle and any additional
   * resources can be freed by calling the object's release() method.
   *
   * @param {?rnp_key_handle_t} handle - the handle of a RNP key, or null
   */
  constructor(handle) {
    if (this.#rnpKeyHandle) {
      throw new Error("Instance already initialized");
    }
    if (!handle) {
      return;
    }
    this.#rnpKeyHandle = handle;

    if (!this.available()) {
      // Not a private key. We tolerate this use to enable automatic
      // handle releasing, for code that sometimes needs to track a
      // secret key, and sometimes only a public key.
      // The only functionality that is allowed on such a key is to
      // call the .available() and the .release() methods.
      this.#isLocked = false;
    } else {
      let is_locked = new lazy.ctypes.bool();
      if (RNPLib.rnp_key_is_locked(this.#rnpKeyHandle, is_locked.address())) {
        throw new Error("rnp_key_is_locked failed");
      }
      this.#isLocked = is_locked.value;
    }

    if (!this.#fingerprint) {
      let fingerprint = new lazy.ctypes.char.ptr();
      if (
        RNPLib.rnp_key_get_fprint(this.#rnpKeyHandle, fingerprint.address())
      ) {
        throw new Error("rnp_key_get_fprint failed");
      }
      this.#fingerprint = fingerprint.readString();
      RNPLib.rnp_buffer_destroy(fingerprint);
    }
  }

  /**
   * @param {Function} cb - Override the callback function that this
   *   object will call to obtain the passphrase to unlock the private
   *   key for tracked key handle, if the object needs to unlock
   *   the key and prompting the user is allowed.
   *   If no alternative callback is set, the global
   *   passphrasePromptCallback function will be used.
   */
  setPassphraseCallback(cb) {
    this.#passphraseCallback = cb;
  }

  /**
   * Allow or forbid prompting the user for a passphrase.
   *
   * @param {boolean} isAllowed - True if allowed, false if forbidden
   */
  setAllowPromptingUserForPassword(isAllowed) {
    this.#allowPromptingUserForPassword = isAllowed;
  }

  /**
   * Allow or forbid automatically using passphrases from a configured
   * cache of passphrase, if it's necessary to obtain a passphrase
   * for unlocking.
   *
   * @param {boolean} isAllowed - True if allowed, false if forbidden
   */
  setAllowAutoUnlockWithCachedPasswords(isAllowed) {
    this.#allowAutoUnlockWithCachedPasswords = isAllowed;
  }

  /**
   * Allow or forbid this object to remember the passphrase that was
   * successfully used to to unlock it. This is necessary when intending
   * to subsequently call the unprotect() function to remove the key's
   * passphrase protection. Care should be taken that a tracker object
   * with a remembered passphrase is held in memory only for a short
   * amount of time, and should be released as soon as a task has
   * completed.
   *
   * @param {boolean} isAllowed - True if allowed, false if forbidden
   */
  setRememberUnlockPassword(isAllowed) {
    this.#rememberUnlockPasswordForUnprotect = isAllowed;
  }

  /**
   * Registers a reference to shared object that implements an optional
   * password cache. Will be used to look up passwords if
   * #allowAutoUnlockWithCachedPasswords is set to true. Will be used
   * to store additional passwords that are found to unlock a key.
   */
  setPasswordCache(cacheObj) {
    this.#passwordCache = cacheObj;
  }

  /**
   * Completely remove the encryption layer that protects the private
   * key. Requires that setRememberUnlockPassword(true) was already
   * called on this object, prior to unlocking the key, because this
   * code requires that the unlock/unprotect passphrase has been cached
   * in this object already, and that the tracked key has already been
   * unlocked.
   */
  unprotect() {
    if (!this.#rnpKeyHandle) {
      return;
    }

    const is_protected = new lazy.ctypes.bool();
    if (
      RNPLib.rnp_key_is_protected(this.#rnpKeyHandle, is_protected.address())
    ) {
      throw new Error("rnp_key_is_protected failed");
    }
    if (!is_protected.value) {
      return;
    }

    if (!this.#wasUnlocked || !this.#rememberUnlockPasswordForUnprotect) {
      // This precondition ensures we have the correct password cached.
      throw new Error("Key should have been unlocked already.");
    }

    if (RNPLib.rnp_key_unprotect(this.#rnpKeyHandle, this.#unlockPassword)) {
      throw new Error(`Failed to unprotect private key ${this.#fingerprint}`);
    }
  }

  /**
   * Attempt to unlock the tracked key with the given passphrase,
   * can also be used with the empty string, which will unlock the key
   * if no passphrase is set.
   *
   * @param {string} pass - try to unlock the key using this passphrase
   */
  unlockWithPassword(pass) {
    if (!this.#rnpKeyHandle || !this.#isLocked) {
      return;
    }
    this.#wasUnlocked = false;

    if (!RNPLib.rnp_key_unlock(this.#rnpKeyHandle, pass)) {
      this.#isLocked = false;
      this.#wasUnlocked = true;
      if (this.#rememberUnlockPasswordForUnprotect) {
        this.#unlockPassword = pass;
      }
    }
  }

  /**
   * Attempt to unlock the tracked key, using the allowed unlock
   * mechanisms that have been configured/allowed for this tracker,
   * which must been configured as desired prior to calling this function.
   * Attempts will potentially be made to unlock using the automatic
   * passphrase, or using password available in the password cache,
   * or by prompting the user for a password, repeatedly prompting
   * until the user enters the correct password or cancels.
   * When prompting the user for a passphrase, and the key is a subkey,
   * it might be necessary to lookup the primary key. A RNP FFI handle
   * is necessary for that potential lookup.
   * Unless a ffi parameter is provided, the default ffi is used.
   *
   * @param {rnp_ffi_t} ffi - An optional specific FFI.
   */
  async unlock(ffi = RNPLib.ffi) {
    if (!this.#rnpKeyHandle || !this.#isLocked) {
      return;
    }
    this.#wasUnlocked = false;
    let autoPassword = await lazy.OpenPGPMasterpass.retrieveOpenPGPPassword();

    if (!RNPLib.rnp_key_unlock(this.#rnpKeyHandle, autoPassword)) {
      this.#isLocked = false;
      this.#wasUnlocked = true;
      if (this.#rememberUnlockPasswordForUnprotect) {
        this.#unlockPassword = autoPassword;
      }
      return;
    }

    if (this.#allowAutoUnlockWithCachedPasswords && this.#passwordCache) {
      for (let pw of this.#passwordCache.passwords) {
        if (!RNPLib.rnp_key_unlock(this.#rnpKeyHandle, pw)) {
          this.#isLocked = false;
          this.#wasUnlocked = true;
          if (this.#rememberUnlockPasswordForUnprotect) {
            this.#unlockPassword = pw;
          }
          return;
        }
      }
    }

    if (!this.#allowPromptingUserForPassword) {
      return;
    }

    let promptString = await RNP.getPassphrasePrompt(this.#rnpKeyHandle, ffi);

    while (true) {
      let userFlags = { canceled: false };
      let pass;
      if (this.#passphraseCallback) {
        pass = this.#passphraseCallback(null, promptString, userFlags);
      } else {
        pass = passphrasePromptCallback(null, promptString, userFlags);
      }
      if (userFlags.canceled) {
        return;
      }

      if (!RNPLib.rnp_key_unlock(this.#rnpKeyHandle, pass)) {
        this.#isLocked = false;
        this.#wasUnlocked = true;
        if (this.#rememberUnlockPasswordForUnprotect) {
          this.#unlockPassword = pass;
        }

        if (this.#passwordCache) {
          this.#passwordCache.passwords.push(pass);
        }
        return;
      }
    }
  }

  /**
   * Check that this tracker has a reference to a private key.
   *
   * @returns {boolean} - true if the tracked key is a secret/private
   */
  isSecret() {
    return (
      this.#rnpKeyHandle &&
      RNPLib.getSecretAvailableFromHandle(this.#rnpKeyHandle)
    );
  }

  /**
   * Check that this tracker has a reference to a valid private key.
   * The check will fail e.g. for offline secret keys, where a
   * primary key is marked as being a secret key, but not having
   * the raw key data available. (In that scenario, the raw key data
   * for subkeys is usually available.)
   *
   * @returns {boolean} - true if the tracked key is a secret/private
   *   key with its key material available.
   */
  available() {
    return (
      this.#rnpKeyHandle &&
      RNPLib.getSecretAvailableFromHandle(this.#rnpKeyHandle) &&
      RNPLib.isSecretKeyMaterialAvailable(this.#rnpKeyHandle)
    );
  }

  /**
   * Obtain the raw RNP key handle managed by this tracker.
   * The returned handle may be temporarily used by the caller,
   * but the caller must not destroy the handle. The returned handle
   * will become invalid as soon as the release() function is called
   * on this tracker object.
   *
   * @returns {rnp_key_handle_t} - the handle of the tracked private key
   *   or null, if no key is tracked by this tracker.
   */
  getHandle() {
    return this.#rnpKeyHandle;
  }

  /**
   * @returns {string} - key fingerprint of the tracked key, or the
   *   empty string.
   */
  getFingerprint() {
    return this.#fingerprint;
  }

  /**
   * @returns {boolean} - true if the tracked key is currently unlocked.
   */
  isUnlocked() {
    return !this.#isLocked;
  }

  /**
   * Protect the key with the automatic passphrase mechanism, that is,
   * using the classic mechanism that uses an automatically generated
   * passphrase, which is either unprotected, or protected by the
   * primary password.
   * Requires that the key is unlocked already.
   */
  async setAutoPassphrase() {
    if (!this.#rnpKeyHandle) {
      return;
    }

    let autoPassword = await lazy.OpenPGPMasterpass.retrieveOpenPGPPassword();
    if (
      RNPLib.rnp_key_protect(
        this.#rnpKeyHandle,
        autoPassword,
        null,
        null,
        null,
        0
      )
    ) {
      throw new Error(`rnp_key_protect failed for ${this.#fingerprint}`);
    }
  }

  /**
   * Protect the key with the given passphrase.
   * Requires that the key is unlocked already.
   *
   * @param {string} pass - protect the key with this passphrase
   */
  setPassphrase(pass) {
    if (!this.#rnpKeyHandle) {
      return;
    }

    if (RNPLib.rnp_key_protect(this.#rnpKeyHandle, pass, null, null, null, 0)) {
      throw new Error(`rnp_key_protect failed for ${this.#fingerprint}`);
    }
  }

  /**
   * Release all data managed by this tracker, if necessary locking the
   * tracked private key, forgetting the remembered unlock password,
   * and destroying the handle.
   * Note that data passed on to a password cache isn't released.
   */
  release() {
    if (!this.#rnpKeyHandle) {
      return;
    }

    this.#unlockPassword = null;
    if (!this.#isLocked && this.#wasUnlocked) {
      RNPLib.rnp_key_lock(this.#rnpKeyHandle);
      this.#isLocked = true;
    }

    RNPLib.rnp_key_handle_destroy(this.#rnpKeyHandle);
    this.#rnpKeyHandle = null;
  }
}

var RNP = {
  hasRan: false,
  libLoaded: false,
  async once() {
    this.hasRan = true;
    try {
      RNPLib = lazy.RNPLibLoader.init();
      if (!RNPLib || !RNPLib.loaded) {
        return;
      }
      if (await RNPLib.init()) {
        //this.initUiOps();
        RNP.libLoaded = true;
      }
      await lazy.OpenPGPMasterpass.ensurePasswordIsCached();
    } catch (e) {
      console.log(e);
    }
  },

  getRNPLibStatus() {
    return RNPLib.getRNPLibStatus();
  },

  async init(opts) {
    opts = opts || {};

    if (!this.hasRan) {
      await this.once();
    }

    return RNP.libLoaded;
  },

  isAllowedPublicKeyAlgo(algo) {
    // see rnp/src/lib/rnp.cpp pubkey_alg_map
    switch (algo) {
      case "SM2":
        return false;

      default:
        return true;
    }
  },

  /**
   * returns {integer} - the raw value of the key's creation date
   */
  getKeyCreatedValueFromHandle(handle) {
    let key_creation = new lazy.ctypes.uint32_t();
    if (RNPLib.rnp_key_get_creation(handle, key_creation.address())) {
      throw new Error("rnp_key_get_creation failed");
    }
    return key_creation.value;
  },

  addKeyAttributes(handle, meta, keyObj, is_subkey, forListing) {
    let algo = new lazy.ctypes.char.ptr();
    let bits = new lazy.ctypes.uint32_t();
    let key_expiration = new lazy.ctypes.uint32_t();
    let allowed = new lazy.ctypes.bool();

    keyObj.secretAvailable = this.getSecretAvailableFromHandle(handle);

    if (keyObj.secretAvailable) {
      keyObj.secretMaterial = RNPLib.isSecretKeyMaterialAvailable(handle);
    } else {
      keyObj.secretMaterial = false;
    }

    if (is_subkey) {
      keyObj.type = "sub";
    } else {
      keyObj.type = "pub";
    }

    keyObj.keyId = this.getKeyIDFromHandle(handle);
    if (forListing) {
      keyObj.id = keyObj.keyId;
    }

    keyObj.fpr = this.getFingerprintFromHandle(handle);

    if (RNPLib.rnp_key_get_alg(handle, algo.address())) {
      throw new Error("rnp_key_get_alg failed");
    }
    keyObj.algoSym = algo.readString();
    RNPLib.rnp_buffer_destroy(algo);

    if (RNPLib.rnp_key_get_bits(handle, bits.address())) {
      throw new Error("rnp_key_get_bits failed");
    }
    keyObj.keySize = bits.value;

    keyObj.keyCreated = this.getKeyCreatedValueFromHandle(handle);
    keyObj.created = new Services.intl.DateTimeFormat().format(
      new Date(keyObj.keyCreated * 1000)
    );

    if (RNPLib.rnp_key_get_expiration(handle, key_expiration.address())) {
      throw new Error("rnp_key_get_expiration failed");
    }
    if (key_expiration.value > 0) {
      keyObj.expiryTime = keyObj.keyCreated + key_expiration.value;
    } else {
      keyObj.expiryTime = 0;
    }
    keyObj.expiry = keyObj.expiryTime
      ? new Services.intl.DateTimeFormat().format(
          new Date(keyObj.expiryTime * 1000)
        )
      : "";
    keyObj.keyUseFor = "";

    if (!this.isAllowedPublicKeyAlgo(keyObj.algoSym)) {
      return;
    }

    let key_revoked = new lazy.ctypes.bool();
    if (RNPLib.rnp_key_is_revoked(handle, key_revoked.address())) {
      throw new Error("rnp_key_is_revoked failed");
    }

    if (key_revoked.value) {
      keyObj.keyTrust = "r";
      if (forListing) {
        keyObj.revoke = true;
      }
    } else if (this.isExpiredTime(keyObj.expiryTime)) {
      keyObj.keyTrust = "e";
    } else if (keyObj.secretAvailable) {
      keyObj.keyTrust = "u";
    } else {
      keyObj.keyTrust = "o";
    }

    if (RNPLib.rnp_key_allows_usage(handle, str_encrypt, allowed.address())) {
      throw new Error("rnp_key_allows_usage failed");
    }
    if (allowed.value) {
      keyObj.keyUseFor += "e";
      meta.e = true;
    }
    if (RNPLib.rnp_key_allows_usage(handle, str_sign, allowed.address())) {
      throw new Error("rnp_key_allows_usage failed");
    }
    if (allowed.value) {
      keyObj.keyUseFor += "s";
      meta.s = true;
    }
    if (RNPLib.rnp_key_allows_usage(handle, str_certify, allowed.address())) {
      throw new Error("rnp_key_allows_usage failed");
    }
    if (allowed.value) {
      keyObj.keyUseFor += "c";
      meta.c = true;
    }
    if (
      RNPLib.rnp_key_allows_usage(handle, str_authenticate, allowed.address())
    ) {
      throw new Error("rnp_key_allows_usage failed");
    }
    if (allowed.value) {
      keyObj.keyUseFor += "a";
      meta.a = true;
    }
  },

  async getKeys(onlyKeys = null) {
    return this.getKeysFromFFI(RNPLib.ffi, false, onlyKeys, false);
  },

  async getSecretKeys(onlyKeys = null) {
    return this.getKeysFromFFI(RNPLib.ffi, false, onlyKeys, true);
  },

  getProtectedKeysCount() {
    return RNPLib.getProtectedKeysCount();
  },

  async protectUnprotectedKeys() {
    return RNPLib.protectUnprotectedKeys();
  },

  /**
   * This function inspects the keys contained in the RNP space "ffi",
   * and returns objects of type KeyObj that describe the keys.
   *
   * Some consumers want a different listing of keys, and expect
   * slightly different attribute names.
   * If forListing is true, we'll set those additional attributes.
   * If onlyKeys is given: only returns keys in that array.
   *
   * @param {rnp_ffi_t} ffi - RNP library handle to key storage area
   * @param {boolean} forListing - Request additional attributes
   *   in the returned objects, for backwards compatibility.
   * @param {string[]} onlyKeys - An array of key IDs or fingerprints.
   *   If non-null, only the given elements will be returned.
   *   If null, all elements are returned.
   * @param {boolean} onlySecret - If true, only information for
   *   available secret keys is returned.
   * @param {boolean} withPubKey - If true, an additional attribute
   *   "pubKey" will be added to each returned KeyObj, which will
   *   contain an ascii armor copy of the public key.
   * @returns {KeyObj[]} - An array of KeyObj objects that describe the
   *                       available keys.
   */
  async getKeysFromFFI(
    ffi,
    forListing,
    onlyKeys = null,
    onlySecret = false,
    withPubKey = false
  ) {
    if (!!onlyKeys && onlySecret) {
      throw new Error(
        "filtering by both white list and only secret keys isn't supported"
      );
    }

    let keys = [];

    if (onlyKeys) {
      for (let ki = 0; ki < onlyKeys.length; ki++) {
        let handle = await this.getKeyHandleByIdentifier(ffi, onlyKeys[ki]);
        if (!handle || handle.isNull()) {
          continue;
        }

        let keyObj = {};
        try {
          // Skip if it is a sub key, it will be processed together with primary key later.
          let ok = this.getKeyInfoFromHandle(
            ffi,
            handle,
            keyObj,
            false,
            forListing,
            false
          );
          if (!ok) {
            continue;
          }
        } catch (ex) {
          console.log(ex);
        } finally {
          RNPLib.rnp_key_handle_destroy(handle);
        }

        if (keyObj) {
          if (withPubKey) {
            let pubKey = await this.getPublicKey("0x" + keyObj.id, ffi);
            if (pubKey) {
              keyObj.pubKey = pubKey;
            }
          }
          keys.push(keyObj);
        }
      }
    } else {
      let rv;

      let iter = new RNPLib.rnp_identifier_iterator_t();
      let grip = new lazy.ctypes.char.ptr();

      rv = RNPLib.rnp_identifier_iterator_create(ffi, iter.address(), "grip");
      if (rv) {
        return null;
      }

      while (!RNPLib.rnp_identifier_iterator_next(iter, grip.address())) {
        if (grip.isNull()) {
          break;
        }

        let handle = new RNPLib.rnp_key_handle_t();

        if (RNPLib.rnp_locate_key(ffi, "grip", grip, handle.address())) {
          throw new Error("rnp_locate_key failed");
        }

        let keyObj = {};
        try {
          if (RNP.isBadKey(handle, null, ffi)) {
            continue;
          }

          // Skip if it is a sub key, it will be processed together with primary key later.
          if (
            !this.getKeyInfoFromHandle(
              ffi,
              handle,
              keyObj,
              false,
              forListing,
              onlySecret
            )
          ) {
            continue;
          }
        } catch (ex) {
          console.log(ex);
        } finally {
          RNPLib.rnp_key_handle_destroy(handle);
        }

        if (keyObj) {
          if (withPubKey) {
            let pubKey = await this.getPublicKey("0x" + keyObj.id, ffi);
            if (pubKey) {
              keyObj.pubKey = pubKey;
            }
          }
          keys.push(keyObj);
        }
      }
      RNPLib.rnp_identifier_iterator_destroy(iter);
    }
    return keys;
  },

  getFingerprintFromHandle(handle) {
    let fingerprint = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_key_get_fprint(handle, fingerprint.address())) {
      throw new Error("rnp_key_get_fprint failed");
    }
    let result = fingerprint.readString();
    RNPLib.rnp_buffer_destroy(fingerprint);
    return result;
  },

  getKeyIDFromHandle(handle) {
    let ctypes_key_id = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_key_get_keyid(handle, ctypes_key_id.address())) {
      throw new Error("rnp_key_get_keyid failed");
    }
    let result = ctypes_key_id.readString();
    RNPLib.rnp_buffer_destroy(ctypes_key_id);
    return result;
  },

  getSecretAvailableFromHandle(handle) {
    return RNPLib.getSecretAvailableFromHandle(handle);
  },

  // We already know sub_handle is a subkey
  getPrimaryKeyHandleFromSub(ffi, sub_handle) {
    let newHandle = new RNPLib.rnp_key_handle_t();
    // test my expectation is correct
    if (!newHandle.isNull()) {
      throw new Error("unexpected, new handle isn't null");
    }
    let primary_grip = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_key_get_primary_grip(sub_handle, primary_grip.address())) {
      throw new Error("rnp_key_get_primary_grip failed");
    }
    if (primary_grip.isNull()) {
      return newHandle;
    }
    if (RNPLib.rnp_locate_key(ffi, "grip", primary_grip, newHandle.address())) {
      throw new Error("rnp_locate_key failed");
    }
    return newHandle;
  },

  // We don't know if handle is a subkey. If it's not, return null handle
  getPrimaryKeyHandleIfSub(ffi, handle) {
    let is_subkey = new lazy.ctypes.bool();
    if (RNPLib.rnp_key_is_sub(handle, is_subkey.address())) {
      throw new Error("rnp_key_is_sub failed");
    }
    if (!is_subkey.value) {
      let nullHandle = new RNPLib.rnp_key_handle_t();
      // test my expectation is correct
      if (!nullHandle.isNull()) {
        throw new Error("unexpected, new handle isn't null");
      }
      return nullHandle;
    }
    return this.getPrimaryKeyHandleFromSub(ffi, handle);
  },

  hasKeyWeakSelfSignature(selfId, handle) {
    let sig_count = new lazy.ctypes.size_t();
    if (RNPLib.rnp_key_get_signature_count(handle, sig_count.address())) {
      throw new Error("rnp_key_get_signature_count failed");
    }

    let hasWeak = false;
    for (let i = 0; !hasWeak && i < sig_count.value; i++) {
      let sig_handle = new RNPLib.rnp_signature_handle_t();

      if (RNPLib.rnp_key_get_signature_at(handle, i, sig_handle.address())) {
        throw new Error("rnp_key_get_signature_at failed");
      }

      hasWeak = RNP.isWeakSelfSignature(selfId, sig_handle);
      RNPLib.rnp_signature_handle_destroy(sig_handle);
    }
    return hasWeak;
  },

  isWeakSelfSignature(selfId, sig_handle) {
    let sig_id_str = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_signature_get_keyid(sig_handle, sig_id_str.address())) {
      throw new Error("rnp_signature_get_keyid failed");
    }

    let sigId = sig_id_str.readString();
    RNPLib.rnp_buffer_destroy(sig_id_str);

    // Is it a self-signature?
    if (sigId != selfId) {
      return false;
    }

    let creation = new lazy.ctypes.uint32_t();
    if (RNPLib.rnp_signature_get_creation(sig_handle, creation.address())) {
      throw new Error("rnp_signature_get_creation failed");
    }

    let hash_str = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_signature_get_hash_alg(sig_handle, hash_str.address())) {
      throw new Error("rnp_signature_get_hash_alg failed");
    }

    let creation64 = new lazy.ctypes.uint64_t();
    creation64.value = creation.value;

    let level = new lazy.ctypes.uint32_t();

    if (
      RNPLib.rnp_get_security_rule(
        RNPLib.ffi,
        RNPLib.RNP_FEATURE_HASH_ALG,
        hash_str,
        creation64,
        null,
        null,
        level.address()
      )
    ) {
      throw new Error("rnp_get_security_rule failed");
    }

    RNPLib.rnp_buffer_destroy(hash_str);
    return level.value < RNPLib.RNP_SECURITY_DEFAULT;
  },

  // return false if handle refers to subkey and should be ignored
  getKeyInfoFromHandle(
    ffi,
    handle,
    keyObj,
    usePrimaryIfSubkey,
    forListing,
    onlyIfSecret
  ) {
    keyObj.ownerTrust = null;
    keyObj.userId = null;
    keyObj.userIds = [];
    keyObj.subKeys = [];
    keyObj.photoAvailable = false;
    keyObj.hasIgnoredAttributes = false;

    let is_subkey = new lazy.ctypes.bool();
    let sub_count = new lazy.ctypes.size_t();
    let uid_count = new lazy.ctypes.size_t();

    if (RNPLib.rnp_key_is_sub(handle, is_subkey.address())) {
      throw new Error("rnp_key_is_sub failed");
    }
    if (is_subkey.value) {
      if (!usePrimaryIfSubkey) {
        return false;
      }
      let rv = false;
      let newHandle = this.getPrimaryKeyHandleFromSub(ffi, handle);
      if (!newHandle.isNull()) {
        // recursively call ourselves to get primary key info
        rv = this.getKeyInfoFromHandle(
          ffi,
          newHandle,
          keyObj,
          false,
          forListing,
          onlyIfSecret
        );
        RNPLib.rnp_key_handle_destroy(newHandle);
      }
      return rv;
    }

    if (onlyIfSecret) {
      let have_secret = new lazy.ctypes.bool();
      if (RNPLib.rnp_key_have_secret(handle, have_secret.address())) {
        throw new Error("rnp_key_have_secret failed");
      }
      if (!have_secret.value) {
        return false;
      }
    }

    let meta = {
      a: false,
      s: false,
      c: false,
      e: false,
    };
    this.addKeyAttributes(handle, meta, keyObj, false, forListing);

    let hasAnySecretKey = keyObj.secretAvailable;

    /* The remaining actions are done for primary keys, only. */
    if (!is_subkey.value) {
      if (RNPLib.rnp_key_get_uid_count(handle, uid_count.address())) {
        throw new Error("rnp_key_get_uid_count failed");
      }
      let firstValidUid = null;
      for (let i = 0; i < uid_count.value; i++) {
        let uid_handle = new RNPLib.rnp_uid_handle_t();

        if (RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())) {
          throw new Error("rnp_key_get_uid_handle_at failed");
        }

        // Never allow revoked user IDs
        let uidOkToUse = !this.isRevokedUid(uid_handle);
        if (uidOkToUse) {
          // Usually, we don't allow user IDs reported as not valid
          uidOkToUse = !this.isBadUid(uid_handle);

          let { hasGoodSignature, hasWeakSignature } =
            this.getUidSignatureQuality(keyObj.keyId, uid_handle);

          if (hasWeakSignature) {
            keyObj.hasIgnoredAttributes = true;
          }

          if (!uidOkToUse && keyObj.keyTrust == "e") {
            // However, a user might be not valid, because it has
            // expired. If the primary key has expired, we should show
            // some user ID, even if all user IDs have expired,
            // otherwise the user cannot see any text description.
            // We allow showing user IDs with a good self-signature.
            uidOkToUse = hasGoodSignature;
          }
        }

        if (uidOkToUse) {
          let uid_str = new lazy.ctypes.char.ptr();
          if (RNPLib.rnp_key_get_uid_at(handle, i, uid_str.address())) {
            throw new Error("rnp_key_get_uid_at failed");
          }
          let userIdStr = uid_str.readStringReplaceMalformed();
          RNPLib.rnp_buffer_destroy(uid_str);

          if (userIdStr !== RNP_PHOTO_USERID_ID) {
            if (!firstValidUid) {
              firstValidUid = userIdStr;
            }

            if (!keyObj.userId && this.isPrimaryUid(uid_handle)) {
              keyObj.userId = userIdStr;
            }

            let uidObj = {};
            uidObj.userId = userIdStr;
            uidObj.type = "uid";
            uidObj.keyTrust = keyObj.keyTrust;
            uidObj.uidFpr = "??fpr??";

            keyObj.userIds.push(uidObj);
          }
        }

        RNPLib.rnp_uid_handle_destroy(uid_handle);
      }

      if (!keyObj.userId && firstValidUid) {
        // No user ID marked as primary, so let's use the first valid.
        keyObj.userId = firstValidUid;
      }

      if (!keyObj.userId) {
        keyObj.userId = "?";
      }

      if (forListing) {
        keyObj.name = keyObj.userId;
      }

      if (RNPLib.rnp_key_get_subkey_count(handle, sub_count.address())) {
        throw new Error("rnp_key_get_subkey_count failed");
      }
      for (let i = 0; i < sub_count.value; i++) {
        let sub_handle = new RNPLib.rnp_key_handle_t();
        if (RNPLib.rnp_key_get_subkey_at(handle, i, sub_handle.address())) {
          throw new Error("rnp_key_get_subkey_at failed");
        }

        if (RNP.hasKeyWeakSelfSignature(keyObj.keyId, sub_handle)) {
          keyObj.hasIgnoredAttributes = true;
        }

        if (!RNP.isBadKey(sub_handle, handle, null)) {
          let subKeyObj = {};
          this.addKeyAttributes(sub_handle, meta, subKeyObj, true, forListing);
          keyObj.subKeys.push(subKeyObj);
          hasAnySecretKey = hasAnySecretKey || subKeyObj.secretAvailable;
        }

        RNPLib.rnp_key_handle_destroy(sub_handle);
      }

      let haveNonExpiringEncryptionKey = false;
      let haveNonExpiringSigningKey = false;

      let effectiveEncryptionExpiry = keyObj.expiry;
      let effectiveSigningExpiry = keyObj.expiry;
      let effectiveEncryptionExpiryTime = keyObj.expiryTime;
      let effectiveSigningExpiryTime = keyObj.expiryTime;

      if (keyObj.keyUseFor.match(/e/) && !keyObj.expiryTime) {
        haveNonExpiringEncryptionKey = true;
      }

      if (keyObj.keyUseFor.match(/s/) && !keyObj.expiryTime) {
        haveNonExpiringSigningKey = true;
      }

      let mostFutureEncExpiryTime = 0;
      let mostFutureSigExpiryTime = 0;
      let mostFutureEncExpiry = "";
      let mostFutureSigExpiry = "";

      for (let aSub of keyObj.subKeys) {
        if (aSub.keyTrust == "r") {
          continue;
        }

        // Expiring subkeys may shorten the effective expiry,
        // unless the primary key is non-expiring and can be used
        // for a purpose.
        // Subkeys cannot extend the expiry beyond the primary key's.

        // Strategy: If we don't have a non-expiring usable primary key,
        // then find the usable subkey that has the most future
        // expiration date. Stop searching is a non-expiring subkey
        // is found. Then compare with primary key expiry.

        if (!haveNonExpiringEncryptionKey && aSub.keyUseFor.match(/e/)) {
          if (!aSub.expiryTime) {
            haveNonExpiringEncryptionKey = true;
          } else if (!mostFutureEncExpiryTime) {
            mostFutureEncExpiryTime = aSub.expiryTime;
            mostFutureEncExpiry = aSub.expiry;
          } else if (aSub.expiryTime > mostFutureEncExpiryTime) {
            mostFutureEncExpiryTime = aSub.expiryTime;
            mostFutureEncExpiry = aSub.expiry;
          }
        }

        // We only need to calculate the effective signing expiration
        // if it's about a personal key (we require both signing and
        // encryption capability).
        if (
          hasAnySecretKey &&
          !haveNonExpiringSigningKey &&
          aSub.keyUseFor.match(/s/)
        ) {
          if (!aSub.expiryTime) {
            haveNonExpiringSigningKey = true;
          } else if (!mostFutureSigExpiryTime) {
            mostFutureSigExpiryTime = aSub.expiryTime;
            mostFutureSigExpiry = aSub.expiry;
          } else if (aSub.expiryTime > mostFutureEncExpiryTime) {
            mostFutureSigExpiryTime = aSub.expiryTime;
            mostFutureSigExpiry = aSub.expiry;
          }
        }
      }

      if (
        !haveNonExpiringEncryptionKey &&
        mostFutureEncExpiryTime &&
        (!keyObj.expiryTime || mostFutureEncExpiryTime < keyObj.expiryTime)
      ) {
        effectiveEncryptionExpiryTime = mostFutureEncExpiryTime;
        effectiveEncryptionExpiry = mostFutureEncExpiry;
      }

      if (
        !haveNonExpiringSigningKey &&
        mostFutureSigExpiryTime &&
        (!keyObj.expiryTime || mostFutureSigExpiryTime < keyObj.expiryTime)
      ) {
        effectiveSigningExpiryTime = mostFutureSigExpiryTime;
        effectiveSigningExpiry = mostFutureSigExpiry;
      }

      if (!hasAnySecretKey) {
        keyObj.effectiveExpiryTime = effectiveEncryptionExpiryTime;
        keyObj.effectiveExpiry = effectiveEncryptionExpiry;
      } else {
        let effectiveSignOrEncExpiry = "";
        let effectiveSignOrEncExpiryTime = 0;

        if (!effectiveEncryptionExpiryTime) {
          if (effectiveSigningExpiryTime) {
            effectiveSignOrEncExpiryTime = effectiveSigningExpiryTime;
            effectiveSignOrEncExpiry = effectiveSigningExpiry;
          }
        } else if (!effectiveSigningExpiryTime) {
          effectiveSignOrEncExpiryTime = effectiveEncryptionExpiryTime;
          effectiveSignOrEncExpiry = effectiveEncryptionExpiry;
        } else if (effectiveSigningExpiryTime < effectiveEncryptionExpiryTime) {
          effectiveSignOrEncExpiryTime = effectiveSigningExpiryTime;
          effectiveSignOrEncExpiry = effectiveSigningExpiry;
        } else {
          effectiveSignOrEncExpiryTime = effectiveEncryptionExpiryTime;
          effectiveSignOrEncExpiry = effectiveEncryptionExpiry;
        }

        keyObj.effectiveExpiryTime = effectiveSignOrEncExpiryTime;
        keyObj.effectiveExpiry = effectiveSignOrEncExpiry;
      }

      if (meta.s) {
        keyObj.keyUseFor += "S";
      }
      if (meta.a) {
        keyObj.keyUseFor += "A";
      }
      if (meta.c) {
        keyObj.keyUseFor += "C";
      }
      if (meta.e) {
        keyObj.keyUseFor += "E";
      }

      if (RNP.hasKeyWeakSelfSignature(keyObj.keyId, handle)) {
        keyObj.hasIgnoredAttributes = true;
      }
    }

    return true;
  },

  /*
  // We don't need these functions currently, but it's helpful
  // information that I'd like to keep around as documentation.

  isUInt64WithinBounds(val) {
    // JS integers are limited to 53 bits precision.
    // Numbers smaller than 2^53 -1 are safe to use.
    // (For comparison, that's 8192 TB or 8388608 GB).
    const num53BitsMinus1 = ctypes.UInt64("0x1fffffffffffff");
    return ctypes.UInt64.compare(val, num53BitsMinus1) < 0;
  },

  isUInt64Max(val) {
    // 2^64-1, 18446744073709551615
    const max = ctypes.UInt64("0xffffffffffffffff");
    return ctypes.UInt64.compare(val, max) == 0;
  },
  */

  isBadKey(handle, knownPrimaryKey, knownContextFFI) {
    let validTill64 = new lazy.ctypes.uint64_t();
    if (RNPLib.rnp_key_valid_till64(handle, validTill64.address())) {
      throw new Error("rnp_key_valid_till64 failed");
    }

    // For the purpose of this function, we define bad as: there isn't
    // any valid self-signature on the key, and thus the key should
    // be completely avoided.
    // In this scenario, zero is returned. In other words,
    // if a non-zero value is returned, we know the key isn't completely
    // bad according to our definition.

    // ctypes.uint64_t().value is of type ctypes.UInt64

    if (
      lazy.ctypes.UInt64.compare(validTill64.value, lazy.ctypes.UInt64("0")) > 0
    ) {
      return false;
    }

    // If zero was returned, it could potentially have been revoked.
    // If it was revoked, we don't treat is as generally bad,
    // to allow importing it and to consume the revocation information.
    // If the key was not revoked, then treat it as a bad key.
    let key_revoked = new lazy.ctypes.bool();
    if (RNPLib.rnp_key_is_revoked(handle, key_revoked.address())) {
      throw new Error("rnp_key_is_revoked failed");
    }

    if (!key_revoked.value) {
      // Also check if the primary key was revoked. If the primary key
      // is revoked, the subkey is considered revoked, too.
      if (knownPrimaryKey) {
        if (RNPLib.rnp_key_is_revoked(knownPrimaryKey, key_revoked.address())) {
          throw new Error("rnp_key_is_revoked failed");
        }
      } else if (knownContextFFI) {
        let primaryHandle = this.getPrimaryKeyHandleIfSub(
          knownContextFFI,
          handle
        );
        if (!primaryHandle.isNull()) {
          if (RNPLib.rnp_key_is_revoked(primaryHandle, key_revoked.address())) {
            throw new Error("rnp_key_is_revoked failed");
          }
          RNPLib.rnp_key_handle_destroy(primaryHandle);
        }
      }
    }

    return !key_revoked.value;
  },

  isPrimaryUid(uid_handle) {
    let is_primary = new lazy.ctypes.bool();

    if (RNPLib.rnp_uid_is_primary(uid_handle, is_primary.address())) {
      throw new Error("rnp_uid_is_primary failed");
    }

    return is_primary.value;
  },

  getUidSignatureQuality(self_key_id, uid_handle) {
    let result = {
      hasGoodSignature: false,
      hasWeakSignature: false,
    };

    let sig_count = new lazy.ctypes.size_t();
    if (RNPLib.rnp_uid_get_signature_count(uid_handle, sig_count.address())) {
      throw new Error("rnp_uid_get_signature_count failed");
    }

    for (let i = 0; i < sig_count.value; i++) {
      let sig_handle = new RNPLib.rnp_signature_handle_t();

      if (
        RNPLib.rnp_uid_get_signature_at(uid_handle, i, sig_handle.address())
      ) {
        throw new Error("rnp_uid_get_signature_at failed");
      }

      let sig_id_str = new lazy.ctypes.char.ptr();
      if (RNPLib.rnp_signature_get_keyid(sig_handle, sig_id_str.address())) {
        throw new Error("rnp_signature_get_keyid failed");
      }

      if (sig_id_str.readString() == self_key_id) {
        if (!result.hasGoodSignature) {
          let sig_validity = RNPLib.rnp_signature_is_valid(sig_handle, 0);
          result.hasGoodSignature =
            sig_validity == RNPLib.RNP_SUCCESS ||
            sig_validity == RNPLib.RNP_ERROR_SIGNATURE_EXPIRED;
        }

        if (!result.hasWeakSignature) {
          result.hasWeakSignature = RNP.isWeakSelfSignature(
            self_key_id,
            sig_handle
          );
        }
      }

      RNPLib.rnp_buffer_destroy(sig_id_str);
      RNPLib.rnp_signature_handle_destroy(sig_handle);
    }

    return result;
  },

  isBadUid(uid_handle) {
    let is_valid = new lazy.ctypes.bool();

    if (RNPLib.rnp_uid_is_valid(uid_handle, is_valid.address())) {
      throw new Error("rnp_uid_is_valid failed");
    }

    return !is_valid.value;
  },

  isRevokedUid(uid_handle) {
    let is_revoked = new lazy.ctypes.bool();

    if (RNPLib.rnp_uid_is_revoked(uid_handle, is_revoked.address())) {
      throw new Error("rnp_uid_is_revoked failed");
    }

    return is_revoked.value;
  },

  getKeySignatures(keyId, ignoreUnknownUid) {
    let handle = this.getKeyHandleByKeyIdOrFingerprint(
      RNPLib.ffi,
      "0x" + keyId
    );
    if (handle.isNull()) {
      return null;
    }

    let mainKeyObj = {};
    this.getKeyInfoFromHandle(
      RNPLib.ffi,
      handle,
      mainKeyObj,
      false,
      true,
      false
    );

    let result = RNP._getSignatures(mainKeyObj, handle, ignoreUnknownUid);
    RNPLib.rnp_key_handle_destroy(handle);
    return result;
  },

  getKeyObjSignatures(keyObj, ignoreUnknownUid) {
    let handle = this.getKeyHandleByKeyIdOrFingerprint(
      RNPLib.ffi,
      "0x" + keyObj.keyId
    );
    if (handle.isNull()) {
      return null;
    }

    let result = RNP._getSignatures(keyObj, handle, ignoreUnknownUid);
    RNPLib.rnp_key_handle_destroy(handle);
    return result;
  },

  _getSignatures(keyObj, handle, ignoreUnknownUid) {
    let rList = [];

    try {
      let uid_count = new lazy.ctypes.size_t();
      if (RNPLib.rnp_key_get_uid_count(handle, uid_count.address())) {
        throw new Error("rnp_key_get_uid_count failed");
      }
      let outputIndex = 0;
      for (let i = 0; i < uid_count.value; i++) {
        let uid_handle = new RNPLib.rnp_uid_handle_t();

        if (RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())) {
          throw new Error("rnp_key_get_uid_handle_at failed");
        }

        if (!this.isBadUid(uid_handle) && !this.isRevokedUid(uid_handle)) {
          let uid_str = new lazy.ctypes.char.ptr();
          if (RNPLib.rnp_key_get_uid_at(handle, i, uid_str.address())) {
            throw new Error("rnp_key_get_uid_at failed");
          }
          let userIdStr = uid_str.readStringReplaceMalformed();
          RNPLib.rnp_buffer_destroy(uid_str);

          if (userIdStr !== RNP_PHOTO_USERID_ID) {
            let id = outputIndex;
            ++outputIndex;

            let subList = {};

            subList = {};
            subList.keyCreated = keyObj.keyCreated;
            subList.created = keyObj.created;
            subList.fpr = keyObj.fpr;
            subList.keyId = keyObj.keyId;

            subList.userId = userIdStr;
            subList.sigList = [];

            let sig_count = new lazy.ctypes.size_t();
            if (
              RNPLib.rnp_uid_get_signature_count(
                uid_handle,
                sig_count.address()
              )
            ) {
              throw new Error("rnp_uid_get_signature_count failed");
            }
            for (let j = 0; j < sig_count.value; j++) {
              let sigObj = {};

              let sig_handle = new RNPLib.rnp_signature_handle_t();
              if (
                RNPLib.rnp_uid_get_signature_at(
                  uid_handle,
                  j,
                  sig_handle.address()
                )
              ) {
                throw new Error("rnp_uid_get_signature_at failed");
              }

              let creation = new lazy.ctypes.uint32_t();
              if (
                RNPLib.rnp_signature_get_creation(
                  sig_handle,
                  creation.address()
                )
              ) {
                throw new Error("rnp_signature_get_creation failed");
              }
              sigObj.keyCreated = creation.value;
              sigObj.created = new Services.intl.DateTimeFormat().format(
                new Date(sigObj.keyCreated * 1000)
              );
              sigObj.sigType = "?";

              let sig_id_str = new lazy.ctypes.char.ptr();
              if (
                RNPLib.rnp_signature_get_keyid(sig_handle, sig_id_str.address())
              ) {
                throw new Error("rnp_signature_get_keyid failed");
              }

              let sigIdStr = sig_id_str.readString();
              sigObj.signerKeyId = sigIdStr;
              RNPLib.rnp_buffer_destroy(sig_id_str);

              let signerHandle = new RNPLib.rnp_key_handle_t();

              if (
                RNPLib.rnp_signature_get_signer(
                  sig_handle,
                  signerHandle.address()
                )
              ) {
                throw new Error("rnp_signature_get_signer failed");
              }

              if (
                signerHandle.isNull() ||
                this.isBadKey(signerHandle, null, RNPLib.ffi)
              ) {
                if (!ignoreUnknownUid) {
                  sigObj.userId = "?";
                  sigObj.sigKnown = false;
                  subList.sigList.push(sigObj);
                }
              } else {
                let signer_uid_str = new lazy.ctypes.char.ptr();
                if (
                  RNPLib.rnp_key_get_primary_uid(
                    signerHandle,
                    signer_uid_str.address()
                  )
                ) {
                  throw new Error("rnp_key_get_primary_uid failed");
                }
                sigObj.userId = signer_uid_str.readStringReplaceMalformed();
                RNPLib.rnp_buffer_destroy(signer_uid_str);
                sigObj.sigKnown = true;
                subList.sigList.push(sigObj);
                RNPLib.rnp_key_handle_destroy(signerHandle);
              }
              RNPLib.rnp_signature_handle_destroy(sig_handle);
            }
            rList[id] = subList;
          }
        }

        RNPLib.rnp_uid_handle_destroy(uid_handle);
      }
    } catch (ex) {
      console.log(ex);
    }
    return rList;
  },

  policyForbidsAlg(alg) {
    // TODO: implement policy
    // Currently, all algorithms are allowed
    return false;
  },

  getKeyIdsFromRecipHandle(recip_handle, resultRecipAndPrimary) {
    resultRecipAndPrimary.keyId = "";
    resultRecipAndPrimary.primaryKeyId = "";

    let c_key_id = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_recipient_get_keyid(recip_handle, c_key_id.address())) {
      throw new Error("rnp_recipient_get_keyid failed");
    }
    let recip_key_id = c_key_id.readString();
    resultRecipAndPrimary.keyId = recip_key_id;
    RNPLib.rnp_buffer_destroy(c_key_id);

    let recip_key_handle = this.getKeyHandleByKeyIdOrFingerprint(
      RNPLib.ffi,
      "0x" + recip_key_id
    );
    if (!recip_key_handle.isNull()) {
      let primary_signer_handle = this.getPrimaryKeyHandleIfSub(
        RNPLib.ffi,
        recip_key_handle
      );
      if (!primary_signer_handle.isNull()) {
        resultRecipAndPrimary.primaryKeyId = this.getKeyIDFromHandle(
          primary_signer_handle
        );
        RNPLib.rnp_key_handle_destroy(primary_signer_handle);
      }
      RNPLib.rnp_key_handle_destroy(recip_key_handle);
    }
  },

  getCharCodeArray(pgpData) {
    return pgpData.split("").map(e => e.charCodeAt());
  },

  is8Bit(charCodeArray) {
    for (let i = 0; i < charCodeArray.length; i++) {
      if (charCodeArray[i] > 255) {
        return false;
      }
    }
    return true;
  },

  removeCommentLines(str) {
    const commentLine = /^Comment:.*(\r?\n|\r)/gm;
    return str.replace(commentLine, "");
  },

  /**
   * This function analyzes an encrypted message. It will check if one
   * of the available secret keys can be used to decrypt a message,
   * without actually performing the decryption.
   * This is done by performing a decryption attempt in an empty
   * environment, which doesn't have any keys available. The decryption
   * attempt allows us to use the RNP APIs that list the key IDs of
   * keys that would be able to decrypt the object.
   * If a matching available secret ID is found, then the handle to that
   * available secret key is returned.
   *
   * @param {rnp_input_t} - A prepared RNP input object that contains
   *   the encrypted message that should be analyzed.
   * @returns {rnp_key_handle_t} - the handle of a private key that can
   *   be used to decrypt the message, or null, if no usable key was
   *   found.
   */
  getFirstAvailableDecryptionKeyHandle(encrypted_rnp_input_from_memory) {
    let resultKey = null;

    let dummyFfi = RNPLib.prepare_ffi();
    if (!dummyFfi) {
      return null;
    }

    const dummy_max_output_size = 1;
    let dummy_output_to_memory = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(
      dummy_output_to_memory.address(),
      dummy_max_output_size
    );

    let dummy_verify_op = new RNPLib.rnp_op_verify_t();
    RNPLib.rnp_op_verify_create(
      dummy_verify_op.address(),
      dummyFfi,
      encrypted_rnp_input_from_memory,
      dummy_output_to_memory
    );

    // It's expected and ok that this function returns an error,
    // e.r. RNP_ERROR_NO_SUITABLE_KEY, we'll query detailed results.
    RNPLib.rnp_op_verify_execute(dummy_verify_op);

    let all_recip_count = new lazy.ctypes.size_t();
    if (
      RNPLib.rnp_op_verify_get_recipient_count(
        dummy_verify_op,
        all_recip_count.address()
      )
    ) {
      throw new Error("rnp_op_verify_get_recipient_count failed");
    }

    // Loop is skipped if all_recip_count is zero.
    for (
      let recip_i = 0;
      recip_i < all_recip_count.value && !resultKey;
      recip_i++
    ) {
      let recip_handle = new RNPLib.rnp_recipient_handle_t();
      if (
        RNPLib.rnp_op_verify_get_recipient_at(
          dummy_verify_op,
          recip_i,
          recip_handle.address()
        )
      ) {
        throw new Error("rnp_op_verify_get_recipient_at failed");
      }

      let c_key_id = new lazy.ctypes.char.ptr();
      if (RNPLib.rnp_recipient_get_keyid(recip_handle, c_key_id.address())) {
        throw new Error("rnp_recipient_get_keyid failed");
      }
      let recip_key_id = c_key_id.readString();
      RNPLib.rnp_buffer_destroy(c_key_id);

      let recip_key_handle = this.getKeyHandleByKeyIdOrFingerprint(
        RNPLib.ffi,
        "0x" + recip_key_id
      );
      if (!recip_key_handle.isNull()) {
        if (
          RNPLib.getSecretAvailableFromHandle(recip_key_handle) &&
          RNPLib.isSecretKeyMaterialAvailable(recip_key_handle)
        ) {
          resultKey = recip_key_handle;
        } else {
          RNPLib.rnp_key_handle_destroy(recip_key_handle);
        }
      }
    }

    RNPLib.rnp_output_destroy(dummy_output_to_memory);
    RNPLib.rnp_op_verify_destroy(dummy_verify_op);
    RNPLib.rnp_ffi_destroy(dummyFfi);

    return resultKey;
  },

  async decrypt(encrypted, options, alreadyDecrypted = false) {
    let arr = encrypted.split("").map(e => e.charCodeAt());
    var encrypted_array = lazy.ctypes.uint8_t.array()(arr);

    let result = {};
    result.decryptedData = "";
    result.statusFlags = 0;
    result.extStatusFlags = 0;

    result.userId = "";
    result.keyId = "";
    result.encToDetails = {};
    result.encToDetails.myRecipKey = {};
    result.encToDetails.allRecipKeys = [];
    result.sigDetails = {};
    result.sigDetails.sigDate = null;

    if (alreadyDecrypted) {
      result.encToDetails = options.encToDetails;
    }

    // We cannot reuse the same rnp_input_t for both the dummy operation
    // and the real decryption operation, as the rnp_input_t object
    // apparently becomes unusable after operating on it.
    // That's why we produce a separate rnp_input_t based on the same
    // data for the dummy operation.
    let dummy_input_from_memory = new RNPLib.rnp_input_t();
    RNPLib.rnp_input_from_memory(
      dummy_input_from_memory.address(),
      encrypted_array,
      encrypted_array.length,
      false
    );

    let rnpCannotDecrypt = true;

    let decryptKey = new RnpPrivateKeyUnlockTracker(
      this.getFirstAvailableDecryptionKeyHandle(dummy_input_from_memory)
    );

    decryptKey.setAllowPromptingUserForPassword(true);
    decryptKey.setAllowAutoUnlockWithCachedPasswords(true);

    if (decryptKey.available()) {
      // If the key cannot be automatically unlocked, we'll rely on
      // the password prompt callback from RNP, and on the user to unlock.
      await decryptKey.unlock();
    }

    // Even if we don't have a matching decryption key, run
    // through full processing, to obtain all the various status flags,
    // and because decryption might not be necessary.
    try {
      let input_from_memory = new RNPLib.rnp_input_t();
      RNPLib.rnp_input_from_memory(
        input_from_memory.address(),
        encrypted_array,
        encrypted_array.length,
        false
      );

      // Allow compressed encrypted messages, max factor 1200, up to 100 MiB.
      const max_decrypted_message_size = 100 * 1024 * 1024;
      let max_out = Math.min(
        encrypted.length * 1200,
        max_decrypted_message_size
      );

      let output_to_memory = new RNPLib.rnp_output_t();
      RNPLib.rnp_output_to_memory(output_to_memory.address(), max_out);

      let verify_op = new RNPLib.rnp_op_verify_t();
      // Apparently the exit code here is ignored (replaced below)
      result.exitCode = RNPLib.rnp_op_verify_create(
        verify_op.address(),
        RNPLib.ffi,
        input_from_memory,
        output_to_memory
      );

      result.exitCode = RNPLib.rnp_op_verify_execute(verify_op);

      rnpCannotDecrypt = false;
      let queryAllEncryptionRecipients = false;
      let stillUndecidedIfSignatureIsBad = false;

      let useDecodedData;
      let processSignature;
      switch (result.exitCode) {
        case RNPLib.RNP_SUCCESS:
          useDecodedData = true;
          processSignature = true;
          break;
        case RNPLib.RNP_ERROR_SIGNATURE_INVALID:
          // Either the signing key is unavailable, or the signature is
          // indeed bad. Must check signature status below.
          stillUndecidedIfSignatureIsBad = true;
          useDecodedData = true;
          processSignature = true;
          break;
        case RNPLib.RNP_ERROR_SIGNATURE_EXPIRED:
          useDecodedData = true;
          processSignature = false;
          result.statusFlags |= lazy.EnigmailConstants.EXPIRED_SIGNATURE;
          break;
        case RNPLib.RNP_ERROR_DECRYPT_FAILED:
          rnpCannotDecrypt = true;
          useDecodedData = false;
          processSignature = false;
          queryAllEncryptionRecipients = true;
          result.statusFlags |= lazy.EnigmailConstants.DECRYPTION_FAILED;
          break;
        case RNPLib.RNP_ERROR_NO_SUITABLE_KEY:
          rnpCannotDecrypt = true;
          useDecodedData = false;
          processSignature = false;
          queryAllEncryptionRecipients = true;
          result.statusFlags |=
            lazy.EnigmailConstants.DECRYPTION_FAILED |
            lazy.EnigmailConstants.NO_SECKEY;
          break;
        default:
          useDecodedData = false;
          processSignature = false;
          console.debug(
            "rnp_op_verify_execute returned unexpected: " + result.exitCode
          );
          break;
      }

      if (useDecodedData && alreadyDecrypted) {
        result.statusFlags |= lazy.EnigmailConstants.DECRYPTION_OKAY;
      } else if (useDecodedData && !alreadyDecrypted) {
        let prot_mode_str = new lazy.ctypes.char.ptr();
        let prot_cipher_str = new lazy.ctypes.char.ptr();
        let prot_is_valid = new lazy.ctypes.bool();

        if (
          RNPLib.rnp_op_verify_get_protection_info(
            verify_op,
            prot_mode_str.address(),
            prot_cipher_str.address(),
            prot_is_valid.address()
          )
        ) {
          throw new Error("rnp_op_verify_get_protection_info failed");
        }
        let mode = prot_mode_str.readString();
        let cipher = prot_cipher_str.readString();
        let validIntegrityProtection = prot_is_valid.value;

        if (mode != "none") {
          if (!validIntegrityProtection) {
            useDecodedData = false;
            result.statusFlags |=
              lazy.EnigmailConstants.MISSING_MDC |
              lazy.EnigmailConstants.DECRYPTION_FAILED;
          } else if (mode == "null" || this.policyForbidsAlg(cipher)) {
            // don't indicate decryption, because a non-protecting or insecure cipher was used
            result.statusFlags |= lazy.EnigmailConstants.UNKNOWN_ALGO;
          } else {
            queryAllEncryptionRecipients = true;

            let recip_handle = new RNPLib.rnp_recipient_handle_t();
            let rv = RNPLib.rnp_op_verify_get_used_recipient(
              verify_op,
              recip_handle.address()
            );
            if (rv) {
              throw new Error("rnp_op_verify_get_used_recipient failed");
            }

            let c_alg = new lazy.ctypes.char.ptr();
            rv = RNPLib.rnp_recipient_get_alg(recip_handle, c_alg.address());
            if (rv) {
              throw new Error("rnp_recipient_get_alg failed");
            }

            if (this.policyForbidsAlg(c_alg.readString())) {
              result.statusFlags |= lazy.EnigmailConstants.UNKNOWN_ALGO;
            } else {
              this.getKeyIdsFromRecipHandle(
                recip_handle,
                result.encToDetails.myRecipKey
              );
              result.statusFlags |= lazy.EnigmailConstants.DECRYPTION_OKAY;
            }
          }
        }
      }

      if (queryAllEncryptionRecipients) {
        let all_recip_count = new lazy.ctypes.size_t();
        if (
          RNPLib.rnp_op_verify_get_recipient_count(
            verify_op,
            all_recip_count.address()
          )
        ) {
          throw new Error("rnp_op_verify_get_recipient_count failed");
        }
        if (all_recip_count.value > 1) {
          for (let recip_i = 0; recip_i < all_recip_count.value; recip_i++) {
            let other_recip_handle = new RNPLib.rnp_recipient_handle_t();
            if (
              RNPLib.rnp_op_verify_get_recipient_at(
                verify_op,
                recip_i,
                other_recip_handle.address()
              )
            ) {
              throw new Error("rnp_op_verify_get_recipient_at failed");
            }
            let encTo = {};
            this.getKeyIdsFromRecipHandle(other_recip_handle, encTo);
            result.encToDetails.allRecipKeys.push(encTo);
          }
        }
      }

      if (useDecodedData) {
        let result_buf = new lazy.ctypes.uint8_t.ptr();
        let result_len = new lazy.ctypes.size_t();
        let rv = RNPLib.rnp_output_memory_get_buf(
          output_to_memory,
          result_buf.address(),
          result_len.address(),
          false
        );

        // result_len is of type UInt64, I don't know of a better way
        // to convert it to an integer.
        let b_len = parseInt(result_len.value.toString());

        if (!rv) {
          // type casting the pointer type to an array type allows us to
          // access the elements by index.
          let uint8_array = lazy.ctypes.cast(
            result_buf,
            lazy.ctypes.uint8_t.array(result_len.value).ptr
          ).contents;

          let str = "";
          for (let i = 0; i < b_len; i++) {
            str += String.fromCharCode(uint8_array[i]);
          }

          result.decryptedData = str;
        }

        if (processSignature) {
          // ignore "no signature" result, that's ok
          await this.getVerifyDetails(
            RNPLib.ffi,
            options.fromAddr,
            options.msgDate,
            verify_op,
            result
          );

          if (
            (result.statusFlags &
              (lazy.EnigmailConstants.GOOD_SIGNATURE |
                lazy.EnigmailConstants.UNCERTAIN_SIGNATURE |
                lazy.EnigmailConstants.EXPIRED_SIGNATURE |
                lazy.EnigmailConstants.BAD_SIGNATURE)) !=
            0
          ) {
            // A decision was already made.
            stillUndecidedIfSignatureIsBad = false;
          }
        }
      }

      if (stillUndecidedIfSignatureIsBad) {
        // We didn't find more details above, so conclude it's bad.
        result.statusFlags |= lazy.EnigmailConstants.BAD_SIGNATURE;
      }

      RNPLib.rnp_input_destroy(input_from_memory);
      RNPLib.rnp_output_destroy(output_to_memory);
      RNPLib.rnp_op_verify_destroy(verify_op);
    } finally {
      decryptKey.release();
      RNPLib.rnp_input_destroy(dummy_input_from_memory);
    }

    if (
      rnpCannotDecrypt &&
      !alreadyDecrypted &&
      Services.prefs.getBoolPref("mail.openpgp.allow_external_gnupg") &&
      lazy.GPGME.allDependenciesLoaded()
    ) {
      // failure processing with RNP, attempt decryption with GPGME
      let r2 = await lazy.GPGME.decrypt(
        encrypted,
        this.enArmorCDataMessage.bind(this)
      );
      if (!r2.exitCode && r2.decryptedData) {
        // TODO: obtain info which key ID was used for decryption
        //       and set result.decryptKey*
        //       It isn't obvious how to do that with GPGME, because
        //       gpgme_op_decrypt_result provides the list of all the
        //       encryption keys, only.

        // The result may still contain wrapping like compression,
        // and optional signature data. Recursively call ourselves
        // to perform the remaining processing.
        options.encToDetails = result.encToDetails;
        return RNP.decrypt(r2.decryptedData, options, true);
      }
    }

    return result;
  },

  async getVerifyDetails(ffi, fromAddr, msgDate, verify_op, result) {
    if (!fromAddr) {
      // We cannot correctly verify without knowing the fromAddr.
      // This scenario is reached when quoting an encrypted MIME part.
      return false;
    }

    let sig_count = new lazy.ctypes.size_t();
    if (
      RNPLib.rnp_op_verify_get_signature_count(verify_op, sig_count.address())
    ) {
      throw new Error("rnp_op_verify_get_signature_count failed");
    }

    // TODO: How should handle (sig_count.value > 1) ?
    if (sig_count.value == 0) {
      // !sig_count.value didn't work, === also doesn't work
      return false;
    }

    let sig = new RNPLib.rnp_op_verify_signature_t();
    if (RNPLib.rnp_op_verify_get_signature_at(verify_op, 0, sig.address())) {
      throw new Error("rnp_op_verify_get_signature_at failed");
    }

    let sig_handle = new RNPLib.rnp_signature_handle_t();
    if (RNPLib.rnp_op_verify_signature_get_handle(sig, sig_handle.address())) {
      throw new Error("rnp_op_verify_signature_get_handle failed");
    }

    let sig_id_str = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_signature_get_keyid(sig_handle, sig_id_str.address())) {
      throw new Error("rnp_signature_get_keyid failed");
    }
    result.keyId = sig_id_str.readString();
    RNPLib.rnp_buffer_destroy(sig_id_str);
    RNPLib.rnp_signature_handle_destroy(sig_handle);

    let sig_status = RNPLib.rnp_op_verify_signature_get_status(sig);
    if (sig_status != RNPLib.RNP_SUCCESS && !result.exitCode) {
      /* Don't allow a good exit code. Keep existing bad code. */
      result.exitCode = -1;
    }

    let query_signer = true;

    switch (sig_status) {
      case RNPLib.RNP_SUCCESS:
        result.statusFlags |= lazy.EnigmailConstants.GOOD_SIGNATURE;
        break;
      case RNPLib.RNP_ERROR_KEY_NOT_FOUND:
        result.statusFlags |=
          lazy.EnigmailConstants.UNCERTAIN_SIGNATURE |
          lazy.EnigmailConstants.NO_PUBKEY;
        query_signer = false;
        break;
      case RNPLib.RNP_ERROR_SIGNATURE_EXPIRED:
        result.statusFlags |= lazy.EnigmailConstants.EXPIRED_SIGNATURE;
        break;
      case RNPLib.RNP_ERROR_SIGNATURE_INVALID:
        result.statusFlags |= lazy.EnigmailConstants.BAD_SIGNATURE;
        break;
      default:
        result.statusFlags |= lazy.EnigmailConstants.BAD_SIGNATURE;
        query_signer = false;
        break;
    }

    if (msgDate && result.statusFlags & lazy.EnigmailConstants.GOOD_SIGNATURE) {
      let created = new lazy.ctypes.uint32_t();
      let expires = new lazy.ctypes.uint32_t(); //relative

      if (
        RNPLib.rnp_op_verify_signature_get_times(
          sig,
          created.address(),
          expires.address()
        )
      ) {
        throw new Error("rnp_op_verify_signature_get_times failed");
      }

      result.sigDetails.sigDate = new Date(created.value * 1000);

      let timeDelta;
      if (result.sigDetails.sigDate > msgDate) {
        timeDelta = result.sigDetails.sigDate - msgDate;
      } else {
        timeDelta = msgDate - result.sigDetails.sigDate;
      }

      if (timeDelta > 1000 * 60 * 60 * 1) {
        result.statusFlags &= ~lazy.EnigmailConstants.GOOD_SIGNATURE;
        result.statusFlags |= lazy.EnigmailConstants.MSG_SIG_INVALID;
      }
    }

    let signer_key = new RNPLib.rnp_key_handle_t();
    let have_signer_key = false;
    let use_signer_key = false;

    if (query_signer) {
      if (RNPLib.rnp_op_verify_signature_get_key(sig, signer_key.address())) {
        // If sig_status isn't RNP_ERROR_KEY_NOT_FOUND then we must
        // be able to obtain the signer key.
        throw new Error("rnp_op_verify_signature_get_key");
      }

      have_signer_key = true;
      use_signer_key = !this.isBadKey(signer_key, null, RNPLib.ffi);
    }

    if (use_signer_key) {
      let keyInfo = {};
      let ok = this.getKeyInfoFromHandle(
        ffi,
        signer_key,
        keyInfo,
        true,
        false,
        false
      );
      if (!ok) {
        throw new Error("getKeyInfoFromHandle failed");
      }

      let fromMatchesAnyUid = false;
      let fromLower = fromAddr ? fromAddr.toLowerCase() : "";

      for (let uid of keyInfo.userIds) {
        if (uid.type !== "uid") {
          continue;
        }

        if (
          lazy.EnigmailFuncs.getEmailFromUserID(uid.userId).toLowerCase() ===
          fromLower
        ) {
          fromMatchesAnyUid = true;
          break;
        }
      }

      let useUndecided = true;

      if (keyInfo.secretAvailable) {
        let isPersonal = await lazy.PgpSqliteDb2.isAcceptedAsPersonalKey(
          keyInfo.fpr
        );
        if (isPersonal && fromMatchesAnyUid) {
          result.extStatusFlags |= lazy.EnigmailConstants.EXT_SELF_IDENTITY;
          useUndecided = false;
        } else {
          result.statusFlags |= lazy.EnigmailConstants.INVALID_RECIPIENT;
          useUndecided = true;
        }
      } else if (result.statusFlags & lazy.EnigmailConstants.GOOD_SIGNATURE) {
        if (!fromMatchesAnyUid) {
          /* At the time the user had accepted the key,
           * a different set of email addresses might have been
           * contained inside the key. In the meantime, we might
           * have refreshed the key, a email addresses
           * might have been removed or revoked.
           * If the current from was removed/revoked, we'd still
           * get an acceptance match, but the from is no longer found
           * in the key's UID list. That should get "undecided".
           */
          result.statusFlags |= lazy.EnigmailConstants.INVALID_RECIPIENT;
          useUndecided = true;
        } else {
          let acceptanceResult = {};
          try {
            await lazy.PgpSqliteDb2.getAcceptance(
              keyInfo.fpr,
              fromLower,
              acceptanceResult
            );
          } catch (ex) {
            console.debug("getAcceptance failed: " + ex);
          }

          // unverified key acceptance means, we consider the signature OK,
          //   but it's not a trusted identity.
          // unverified signature means, we cannot decide if the signature
          //   is ok.

          if (
            "emailDecided" in acceptanceResult &&
            acceptanceResult.emailDecided &&
            "fingerprintAcceptance" in acceptanceResult &&
            acceptanceResult.fingerprintAcceptance.length &&
            acceptanceResult.fingerprintAcceptance != "undecided"
          ) {
            if (acceptanceResult.fingerprintAcceptance == "rejected") {
              result.statusFlags &= ~lazy.EnigmailConstants.GOOD_SIGNATURE;
              result.statusFlags |=
                lazy.EnigmailConstants.BAD_SIGNATURE |
                lazy.EnigmailConstants.INVALID_RECIPIENT;
              useUndecided = false;
            } else if (acceptanceResult.fingerprintAcceptance == "verified") {
              result.statusFlags |= lazy.EnigmailConstants.TRUSTED_IDENTITY;
              useUndecided = false;
            } else if (acceptanceResult.fingerprintAcceptance == "unverified") {
              useUndecided = false;
            }
          }
        }
      }

      if (useUndecided) {
        result.statusFlags &= ~lazy.EnigmailConstants.GOOD_SIGNATURE;
        result.statusFlags |= lazy.EnigmailConstants.UNCERTAIN_SIGNATURE;
      }
    }

    if (have_signer_key) {
      RNPLib.rnp_key_handle_destroy(signer_key);
    }

    return true;
  },

  async verifyDetached(data, options) {
    let result = {};
    result.decryptedData = "";
    result.statusFlags = 0;
    result.exitCode = -1;
    result.extStatusFlags = 0;
    result.userId = "";
    result.keyId = "";
    result.sigDetails = {};
    result.sigDetails.sigDate = null;

    let sig_arr = options.mimeSignatureData.split("").map(e => e.charCodeAt());
    var sig_array = lazy.ctypes.uint8_t.array()(sig_arr);

    let input_sig = new RNPLib.rnp_input_t();
    RNPLib.rnp_input_from_memory(
      input_sig.address(),
      sig_array,
      sig_array.length,
      false
    );

    let input_from_memory = new RNPLib.rnp_input_t();

    let arr = data.split("").map(e => e.charCodeAt());
    var data_array = lazy.ctypes.uint8_t.array()(arr);

    RNPLib.rnp_input_from_memory(
      input_from_memory.address(),
      data_array,
      data_array.length,
      false
    );

    let verify_op = new RNPLib.rnp_op_verify_t();
    if (
      RNPLib.rnp_op_verify_detached_create(
        verify_op.address(),
        RNPLib.ffi,
        input_from_memory,
        input_sig
      )
    ) {
      throw new Error("rnp_op_verify_detached_create failed");
    }

    result.exitCode = RNPLib.rnp_op_verify_execute(verify_op);

    let haveSignature = await this.getVerifyDetails(
      RNPLib.ffi,
      options.fromAddr,
      options.msgDate,
      verify_op,
      result
    );
    if (!haveSignature) {
      if (!result.exitCode) {
        /* Don't allow a good exit code. Keep existing bad code. */
        result.exitCode = -1;
      }
      result.statusFlags |= lazy.EnigmailConstants.BAD_SIGNATURE;
    }

    RNPLib.rnp_input_destroy(input_from_memory);
    RNPLib.rnp_input_destroy(input_sig);
    RNPLib.rnp_op_verify_destroy(verify_op);

    return result;
  },

  async genKey(userId, keyType, keyBits, expiryDays, passphrase) {
    let newKeyId = "";
    let newKeyFingerprint = "";

    let primaryKeyType;
    let primaryKeyBits = 0;
    let subKeyType;
    let subKeyBits = 0;
    let primaryKeyCurve = null;
    let subKeyCurve = null;
    let expireSeconds = 0;

    if (keyType == "RSA") {
      primaryKeyType = subKeyType = "rsa";
      primaryKeyBits = subKeyBits = keyBits;
    } else if (keyType == "ECC") {
      primaryKeyType = "eddsa";
      subKeyType = "ecdh";
      subKeyCurve = "Curve25519";
    } else {
      return null;
    }

    if (expiryDays != 0) {
      expireSeconds = expiryDays * 24 * 60 * 60;
    }

    let genOp = new RNPLib.rnp_op_generate_t();
    if (
      RNPLib.rnp_op_generate_create(genOp.address(), RNPLib.ffi, primaryKeyType)
    ) {
      throw new Error("rnp_op_generate_create primary failed");
    }

    if (RNPLib.rnp_op_generate_set_userid(genOp, userId)) {
      throw new Error("rnp_op_generate_set_userid failed");
    }

    if (passphrase != null && passphrase.length != 0) {
      if (RNPLib.rnp_op_generate_set_protection_password(genOp, passphrase)) {
        throw new Error("rnp_op_generate_set_protection_password failed");
      }
    }

    if (primaryKeyBits != 0) {
      if (RNPLib.rnp_op_generate_set_bits(genOp, primaryKeyBits)) {
        throw new Error("rnp_op_generate_set_bits primary failed");
      }
    }

    if (primaryKeyCurve != null) {
      if (RNPLib.rnp_op_generate_set_curve(genOp, primaryKeyCurve)) {
        throw new Error("rnp_op_generate_set_curve primary failed");
      }
    }

    if (RNPLib.rnp_op_generate_set_expiration(genOp, expireSeconds)) {
      throw new Error("rnp_op_generate_set_expiration primary failed");
    }

    if (RNPLib.rnp_op_generate_execute(genOp)) {
      throw new Error("rnp_op_generate_execute primary failed");
    }

    let primaryKey = new RNPLib.rnp_key_handle_t();
    if (RNPLib.rnp_op_generate_get_key(genOp, primaryKey.address())) {
      throw new Error("rnp_op_generate_get_key primary failed");
    }

    RNPLib.rnp_op_generate_destroy(genOp);

    newKeyFingerprint = this.getFingerprintFromHandle(primaryKey);
    newKeyId = this.getKeyIDFromHandle(primaryKey);

    if (
      RNPLib.rnp_op_generate_subkey_create(
        genOp.address(),
        RNPLib.ffi,
        primaryKey,
        subKeyType
      )
    ) {
      throw new Error("rnp_op_generate_subkey_create primary failed");
    }

    if (passphrase != null && passphrase.length != 0) {
      if (RNPLib.rnp_op_generate_set_protection_password(genOp, passphrase)) {
        throw new Error("rnp_op_generate_set_protection_password failed");
      }
    }

    if (subKeyBits != 0) {
      if (RNPLib.rnp_op_generate_set_bits(genOp, subKeyBits)) {
        throw new Error("rnp_op_generate_set_bits sub failed");
      }
    }

    if (subKeyCurve != null) {
      if (RNPLib.rnp_op_generate_set_curve(genOp, subKeyCurve)) {
        throw new Error("rnp_op_generate_set_curve sub failed");
      }
    }

    if (RNPLib.rnp_op_generate_set_expiration(genOp, expireSeconds)) {
      throw new Error("rnp_op_generate_set_expiration sub failed");
    }

    let unlocked = false;
    try {
      if (passphrase != null && passphrase.length != 0) {
        if (RNPLib.rnp_key_unlock(primaryKey, passphrase)) {
          throw new Error("rnp_key_unlock failed");
        }
        unlocked = true;
      }

      if (RNPLib.rnp_op_generate_execute(genOp)) {
        throw new Error("rnp_op_generate_execute sub failed");
      }
    } finally {
      if (unlocked) {
        RNPLib.rnp_key_lock(primaryKey);
      }
    }

    RNPLib.rnp_op_generate_destroy(genOp);
    RNPLib.rnp_key_handle_destroy(primaryKey);

    await lazy.PgpSqliteDb2.acceptAsPersonalKey(newKeyFingerprint);

    return newKeyId;
  },

  async saveKeyRings() {
    RNPLib.saveKeys();
    Services.obs.notifyObservers(null, "openpgp-key-change");
  },

  importToFFI(ffi, keyBlockStr, usePublic, useSecret, permissive) {
    let input_from_memory = new RNPLib.rnp_input_t();

    if (!keyBlockStr) {
      throw new Error("no keyBlockStr parameter in importToFFI");
    }

    if (typeof keyBlockStr != "string") {
      throw new Error(
        "keyBlockStr of unepected type importToFFI: %o",
        keyBlockStr
      );
    }

    // Input might be either plain text or binary data.
    // If the input is binary, do not modify it.
    // If the input contains characters with a multi-byte char code value,
    // we know the input doesn't consist of binary 8-bit values. Rather,
    // it contains text with multi-byte characters. The only scenario
    // in which we can tolerate those are comment lines, which we can
    // filter out.

    let arr = this.getCharCodeArray(keyBlockStr);
    if (!this.is8Bit(arr)) {
      let trimmed = this.removeCommentLines(keyBlockStr);
      arr = this.getCharCodeArray(trimmed);
      if (!this.is8Bit(arr)) {
        throw new Error(`Non-ascii key block: ${keyBlockStr}`);
      }
    }
    var key_array = lazy.ctypes.uint8_t.array()(arr);

    if (
      RNPLib.rnp_input_from_memory(
        input_from_memory.address(),
        key_array,
        key_array.length,
        false
      )
    ) {
      throw new Error("rnp_input_from_memory failed");
    }

    let jsonInfo = new lazy.ctypes.char.ptr();

    let flags = 0;
    if (usePublic) {
      flags |= RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS;
    }
    if (useSecret) {
      flags |= RNPLib.RNP_LOAD_SAVE_SECRET_KEYS;
    }

    if (permissive) {
      flags |= RNPLib.RNP_LOAD_SAVE_PERMISSIVE;
    }

    let rv = RNPLib.rnp_import_keys(
      ffi,
      input_from_memory,
      flags,
      jsonInfo.address()
    );

    // TODO: parse jsonInfo and return a list of keys,
    // as seen in keyRing.importKeyAsync.
    // (should prevent the incorrect popup "no keys imported".)

    if (rv) {
      console.debug("rnp_import_keys failed with  rv: " + rv);
    }

    RNPLib.rnp_buffer_destroy(jsonInfo);
    RNPLib.rnp_input_destroy(input_from_memory);

    return rv;
  },

  maxImportKeyBlockSize: 5000000,

  async getOnePubKeyFromKeyBlock(keyBlockStr, fpr, permissive = true) {
    if (!keyBlockStr) {
      throw new Error(`Invalid parameter; keyblock: ${keyBlockStr}`);
    }

    if (keyBlockStr.length > RNP.maxImportKeyBlockSize) {
      throw new Error("rejecting big keyblock");
    }

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    let pubKey;
    if (!this.importToFFI(tempFFI, keyBlockStr, true, false, permissive)) {
      pubKey = await this.getPublicKey("0x" + fpr, tempFFI);
    }

    RNPLib.rnp_ffi_destroy(tempFFI);
    return pubKey;
  },

  async getKeyListFromKeyBlockImpl(
    keyBlockStr,
    pubkey = true,
    seckey = false,
    permissive = true,
    withPubKey = false
  ) {
    if (!keyBlockStr) {
      throw new Error(`Invalid parameter; keyblock: ${keyBlockStr}`);
    }

    if (keyBlockStr.length > RNP.maxImportKeyBlockSize) {
      throw new Error("rejecting big keyblock");
    }

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    let keyList = null;
    if (!this.importToFFI(tempFFI, keyBlockStr, pubkey, seckey, permissive)) {
      keyList = await this.getKeysFromFFI(
        tempFFI,
        true,
        null,
        false,
        withPubKey
      );
    }

    RNPLib.rnp_ffi_destroy(tempFFI);
    return keyList;
  },

  /**
   * Take two or more ASCII armored key blocks and import them into memory,
   * and return the merged public key for the given fingerprint.
   * (Other keys included in the key blocks are ignored.)
   * The intention is to use it to combine keys obtained from different places,
   * possibly with updated/different expiration date and userIds etc. to
   * a canonical representation of them.
   *
   * @param {string} fingerprint - Key fingerprint.
   * @param {...string} - Key blocks.
   * @returns {string} the resulting public key of the blocks
   */
  async mergePublicKeyBlocks(fingerprint, ...keyBlocks) {
    if (keyBlocks.some(b => b.length > RNP.maxImportKeyBlockSize)) {
      throw new Error("keyBlock too big");
    }

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    const pubkey = true;
    const seckey = false;
    const permissive = false;
    for (let block of new Set(keyBlocks)) {
      if (this.importToFFI(tempFFI, block, pubkey, seckey, permissive)) {
        throw new Error("Merging public keys failed");
      }
    }
    let pubKey = await this.getPublicKey(`0x${fingerprint}`, tempFFI);

    RNPLib.rnp_ffi_destroy(tempFFI);
    return pubKey;
  },

  async importRevImpl(data) {
    if (!data || typeof data != "string") {
      throw new Error("invalid data parameter");
    }

    let arr = data.split("").map(e => e.charCodeAt());
    var key_array = lazy.ctypes.uint8_t.array()(arr);

    let input_from_memory = new RNPLib.rnp_input_t();
    if (
      RNPLib.rnp_input_from_memory(
        input_from_memory.address(),
        key_array,
        key_array.length,
        false
      )
    ) {
      throw new Error("rnp_input_from_memory failed");
    }

    let jsonInfo = new lazy.ctypes.char.ptr();

    let flags = 0;
    let rv = RNPLib.rnp_import_signatures(
      RNPLib.ffi,
      input_from_memory,
      flags,
      jsonInfo.address()
    );

    // TODO: parse jsonInfo

    if (rv) {
      console.debug("rnp_import_signatures failed with rv: " + rv);
    }

    RNPLib.rnp_buffer_destroy(jsonInfo);
    RNPLib.rnp_input_destroy(input_from_memory);
    await this.saveKeyRings();

    return rv;
  },

  async importSecKeyBlockImpl(
    win,
    passCB,
    keepPassphrases,
    keyBlockStr,
    permissive = false,
    limitedFPRs = []
  ) {
    return this._importKeyBlockWithAutoAccept(
      win,
      passCB,
      keepPassphrases,
      keyBlockStr,
      false,
      true,
      null,
      permissive,
      limitedFPRs
    );
  },

  async importPubkeyBlockAutoAcceptImpl(
    win,
    keyBlockStr,
    acceptance,
    permissive = false,
    limitedFPRs = []
  ) {
    return this._importKeyBlockWithAutoAccept(
      win,
      null,
      false,
      keyBlockStr,
      true,
      false,
      acceptance,
      permissive,
      limitedFPRs
    );
  },

  /**
   * Import either a public key or a secret key.
   * Importing both at the same time isn't supported by this API.
   *
   * @param {?nsIWindow} win - Parent window, may be null
   * @param {Function} passCB - a callback function that will be called if the user needs
   *   to enter a passphrase to unlock a secret key. See passphrasePromptCallback
   *   for the function signature.
   * @param {boolean} keepPassphrases - controls which passphrase will
   *   be used to protect imported secret keys. If true, the existing
   *   passphrase will be kept. If false, (of if currently there's no
   *   passphrase set), passphrase protection will be changed to use
   *   our automatic passphrase (to allow automatic protection by
   *   primary password, whether's it's currently enabled or not).
   * @param {string} keyBlockStr - An block of OpenPGP key data. See
   *   implementation of function importToFFI for allowed contents.
   *   TODO: Write better documentation for this parameter.
   * @param {boolean} pubkey - If true, import the public keys found in
   *   keyBlockStr.
   * @param {boolean} seckey - If true, import the secret keys found in
   *   keyBlockStr.
   * @param {string} acceptance - The key acceptance level that should
   *   be assigned to imported public keys.
   *   TODO: Write better documentation for the allowed values.
   * @param {boolean} permissive - Whether it's allowed to fall back
   *   to a permissive import, if strict import fails.
   *   (See RNP documentation for RNP_LOAD_SAVE_PERMISSIVE.)
   * @param {string[]} limitedFPRs - This is a filtering parameter.
   *   If the array is empty, all keys will be imported.
   *   If the array contains at least one entry, a key will be imported
   *   only if its fingerprint (of the primary key) is listed in this
   *   array.
   */
  async _importKeyBlockWithAutoAccept(
    win,
    passCB,
    keepPassphrases,
    keyBlockStr,
    pubkey,
    seckey,
    acceptance,
    permissive = false,
    limitedFPRs = []
  ) {
    if (keyBlockStr.length > RNP.maxImportKeyBlockSize) {
      throw new Error("rejecting big keyblock");
    }
    if (pubkey && seckey) {
      // Currently no caller needs to import both at the save time,
      // and the implementation hasn't been reviewed, whether it
      // supports it or not, so we refuse this request.
      throw new Error("Cannot import public and secret keys at the same time");
    }

    /*
     * Import strategy:
     * - import file into a temporary space, in-memory only (ffi)
     * - if we failed to decrypt the secret keys, return null
     * - set the password of secret keys that don't have one yet
     * - get the key listing of all keys from the temporary space,
     *   which is want we want to return as the import report
     * - export all keys from the temporary space, and import them
     *   into our permanent space.
     */
    let userFlags = { canceled: false };

    let result = {};
    result.exitCode = -1;
    result.importedKeys = [];
    result.errorMsg = "";

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    // TODO: check result
    if (this.importToFFI(tempFFI, keyBlockStr, pubkey, seckey, permissive)) {
      result.errorMsg = "RNP.importToFFI failed";
      return result;
    }

    let keys = await this.getKeysFromFFI(tempFFI, true);
    let pwCache = {
      passwords: [],
    };

    // Prior to importing, ensure the user is able to unlock all keys

    // If anything goes wrong during our attempt to unlock keys,
    // we don't want to keep key material remain unprotected in memory,
    // that's why we remember the trackers, including the respective
    // unlock passphrase, temporarily in memory, and we'll minimize
    // the period of time during which the key remains unprotected.
    let secretKeyTrackers = new Map();

    let unableToUnlockId = null;

    for (let k of keys) {
      let fprStr = "0x" + k.fpr;
      if (limitedFPRs.length && !limitedFPRs.includes(fprStr)) {
        continue;
      }

      let impKey = await this.getKeyHandleByIdentifier(tempFFI, fprStr);
      if (impKey.isNull()) {
        throw new Error("cannot get key handle for imported key: " + k.fpr);
      }

      if (!k.secretAvailable) {
        RNPLib.rnp_key_handle_destroy(impKey);
        impKey = null;
      } else {
        let primaryKey = new RnpPrivateKeyUnlockTracker(impKey);
        impKey = null;

        // Don't attempt to unlock secret keys that are unavailable.
        if (primaryKey.available()) {
          // Is it unprotected?
          primaryKey.unlockWithPassword("");
          if (primaryKey.isUnlocked()) {
            // yes, it's unprotected (empty passphrase)
            await primaryKey.setAutoPassphrase();
          } else {
            // try to unlock with the recently entered passwords,
            // or ask the user, if allowed
            primaryKey.setPasswordCache(pwCache);
            primaryKey.setAllowAutoUnlockWithCachedPasswords(true);
            primaryKey.setAllowPromptingUserForPassword(!!passCB);
            primaryKey.setPassphraseCallback(passCB);
            primaryKey.setRememberUnlockPassword(true);
            await primaryKey.unlock(tempFFI);
            if (!primaryKey.isUnlocked()) {
              userFlags.canceled = true;
              unableToUnlockId = RNP.getKeyIDFromHandle(primaryKey.getHandle());
            } else {
              secretKeyTrackers.set(fprStr, primaryKey);
            }
          }
        }

        if (!userFlags.canceled) {
          let sub_count = new lazy.ctypes.size_t();
          if (
            RNPLib.rnp_key_get_subkey_count(
              primaryKey.getHandle(),
              sub_count.address()
            )
          ) {
            throw new Error("rnp_key_get_subkey_count failed");
          }

          for (let i = 0; i < sub_count.value && !userFlags.canceled; i++) {
            let sub_handle = new RNPLib.rnp_key_handle_t();
            if (
              RNPLib.rnp_key_get_subkey_at(
                primaryKey.getHandle(),
                i,
                sub_handle.address()
              )
            ) {
              throw new Error("rnp_key_get_subkey_at failed");
            }

            let subTracker = new RnpPrivateKeyUnlockTracker(sub_handle);
            sub_handle = null;

            if (subTracker.available()) {
              // Is it unprotected?
              subTracker.unlockWithPassword("");
              if (subTracker.isUnlocked()) {
                // yes, it's unprotected (empty passphrase)
                await subTracker.setAutoPassphrase();
              } else {
                // try to unlock with the recently entered passwords,
                // or ask the user, if allowed
                subTracker.setPasswordCache(pwCache);
                subTracker.setAllowAutoUnlockWithCachedPasswords(true);
                subTracker.setAllowPromptingUserForPassword(!!passCB);
                subTracker.setPassphraseCallback(passCB);
                subTracker.setRememberUnlockPassword(true);
                await subTracker.unlock(tempFFI);
                if (!subTracker.isUnlocked()) {
                  userFlags.canceled = true;
                  unableToUnlockId = RNP.getKeyIDFromHandle(
                    subTracker.getHandle()
                  );
                  break;
                } else {
                  secretKeyTrackers.set(
                    this.getFingerprintFromHandle(subTracker.getHandle()),
                    subTracker
                  );
                }
              }
            }
          }
        }
      }

      if (userFlags.canceled) {
        break;
      }
    }

    if (unableToUnlockId) {
      result.errorMsg = "Cannot unlock key " + unableToUnlockId;
    }

    if (!userFlags.canceled) {
      for (let k of keys) {
        let fprStr = "0x" + k.fpr;
        if (limitedFPRs.length && !limitedFPRs.includes(fprStr)) {
          continue;
        }

        // We allow importing, if any of the following is true
        // - it contains a secret key
        // - it contains at least one user ID
        // - it is an update for an existing key (possibly new validity/revocation)

        if (k.userIds.length == 0 && !k.secretAvailable) {
          let existingKey = await this.getKeyHandleByIdentifier(
            RNPLib.ffi,
            "0x" + k.fpr
          );
          if (existingKey.isNull()) {
            continue;
          }
          RNPLib.rnp_key_handle_destroy(existingKey);
        }

        let impKeyPub;
        let impKeySecTracker = secretKeyTrackers.get(fprStr);
        if (!impKeySecTracker) {
          impKeyPub = await this.getKeyHandleByIdentifier(tempFFI, fprStr);
        }

        if (!keepPassphrases) {
          // It's possible that the primary key doesn't come with a
          // secret key (only public key of primary key was imported).
          // In that scenario, we must still process subkeys that come
          // with a secret key.

          if (impKeySecTracker) {
            impKeySecTracker.unprotect();
            await impKeySecTracker.setAutoPassphrase();
          }

          let sub_count = new lazy.ctypes.size_t();
          if (
            RNPLib.rnp_key_get_subkey_count(
              impKeySecTracker ? impKeySecTracker.getHandle() : impKeyPub,
              sub_count.address()
            )
          ) {
            throw new Error("rnp_key_get_subkey_count failed");
          }

          for (let i = 0; i < sub_count.value; i++) {
            let sub_handle = new RNPLib.rnp_key_handle_t();
            if (
              RNPLib.rnp_key_get_subkey_at(
                impKeySecTracker ? impKeySecTracker.getHandle() : impKeyPub,
                i,
                sub_handle.address()
              )
            ) {
              throw new Error("rnp_key_get_subkey_at failed");
            }

            let subTracker = secretKeyTrackers.get(
              this.getFingerprintFromHandle(sub_handle)
            );
            if (!subTracker) {
              // There is no secret key material for this subkey available,
              // that's why no tracker was created, we can skip it.
              continue;
            }
            subTracker.unprotect();
            await subTracker.setAutoPassphrase();
          }
        }

        let exportFlags =
          RNPLib.RNP_KEY_EXPORT_ARMORED | RNPLib.RNP_KEY_EXPORT_SUBKEYS;

        if (pubkey) {
          exportFlags |= RNPLib.RNP_KEY_EXPORT_PUBLIC;
        }
        if (seckey) {
          exportFlags |= RNPLib.RNP_KEY_EXPORT_SECRET;
        }

        let output_to_memory = new RNPLib.rnp_output_t();
        if (RNPLib.rnp_output_to_memory(output_to_memory.address(), 0)) {
          throw new Error("rnp_output_to_memory failed");
        }

        if (
          RNPLib.rnp_key_export(
            impKeySecTracker ? impKeySecTracker.getHandle() : impKeyPub,
            output_to_memory,
            exportFlags
          )
        ) {
          throw new Error("rnp_key_export failed");
        }

        if (impKeyPub) {
          RNPLib.rnp_key_handle_destroy(impKeyPub);
          impKeyPub = null;
        }

        let result_buf = new lazy.ctypes.uint8_t.ptr();
        let result_len = new lazy.ctypes.size_t();
        if (
          RNPLib.rnp_output_memory_get_buf(
            output_to_memory,
            result_buf.address(),
            result_len.address(),
            false
          )
        ) {
          throw new Error("rnp_output_memory_get_buf failed");
        }

        let input_from_memory = new RNPLib.rnp_input_t();

        if (
          RNPLib.rnp_input_from_memory(
            input_from_memory.address(),
            result_buf,
            result_len,
            false
          )
        ) {
          throw new Error("rnp_input_from_memory failed");
        }

        let importFlags = 0;
        if (pubkey) {
          importFlags |= RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS;
        }
        if (seckey) {
          importFlags |= RNPLib.RNP_LOAD_SAVE_SECRET_KEYS;
        }
        if (permissive) {
          importFlags |= RNPLib.RNP_LOAD_SAVE_PERMISSIVE;
        }

        if (
          RNPLib.rnp_import_keys(
            RNPLib.ffi,
            input_from_memory,
            importFlags,
            null
          )
        ) {
          throw new Error("rnp_import_keys failed");
        }

        result.importedKeys.push("0x" + k.id);

        RNPLib.rnp_input_destroy(input_from_memory);
        RNPLib.rnp_output_destroy(output_to_memory);

        // For acceptance "undecided", we don't store it, because that's
        // the default if no value is stored.
        let actionableAcceptances = ["rejected", "unverified", "verified"];

        if (
          pubkey &&
          !k.secretAvailable &&
          actionableAcceptances.includes(acceptance)
        ) {
          // For each imported public key and associated email address,
          // update the acceptance to unverified, but only if it's only
          // currently undecided. In other words, we keep the acceptance
          // if it's rejected or verified.

          let currentAcceptance =
            await lazy.PgpSqliteDb2.getFingerprintAcceptance(null, k.fpr);

          if (!currentAcceptance || currentAcceptance == "undecided") {
            // Currently undecided, allowed to change.
            let allEmails = [];

            for (let uid of k.userIds) {
              if (uid.type != "uid") {
                continue;
              }

              let uidEmail = lazy.EnigmailFuncs.getEmailFromUserID(uid.userId);
              if (uidEmail) {
                allEmails.push(uidEmail);
              }
            }
            await lazy.PgpSqliteDb2.updateAcceptance(
              k.fpr,
              allEmails,
              acceptance
            );
          }
        }
      }

      result.exitCode = 0;
      await this.saveKeyRings();
    }

    for (let valTracker of secretKeyTrackers.values()) {
      valTracker.release();
    }

    RNPLib.rnp_ffi_destroy(tempFFI);
    return result;
  },

  async deleteKey(keyFingerprint, deleteSecret) {
    let handle = new RNPLib.rnp_key_handle_t();
    if (
      RNPLib.rnp_locate_key(
        RNPLib.ffi,
        "fingerprint",
        keyFingerprint,
        handle.address()
      )
    ) {
      throw new Error("rnp_locate_key failed");
    }

    let flags = RNPLib.RNP_KEY_REMOVE_PUBLIC | RNPLib.RNP_KEY_REMOVE_SUBKEYS;
    if (deleteSecret) {
      flags |= RNPLib.RNP_KEY_REMOVE_SECRET;
    }

    if (RNPLib.rnp_key_remove(handle, flags)) {
      throw new Error("rnp_key_remove failed");
    }

    RNPLib.rnp_key_handle_destroy(handle);
    await this.saveKeyRings();
  },

  async revokeKey(keyFingerprint) {
    let tracker =
      RnpPrivateKeyUnlockTracker.constructFromFingerprint(keyFingerprint);
    if (!tracker.available()) {
      return;
    }
    tracker.setAllowPromptingUserForPassword(true);
    tracker.setAllowAutoUnlockWithCachedPasswords(true);
    await tracker.unlock();
    if (!tracker.isUnlocked()) {
      return;
    }

    let flags = 0;
    let revokeResult = RNPLib.rnp_key_revoke(
      tracker.getHandle(),
      flags,
      null,
      null,
      null
    );
    tracker.release();
    if (revokeResult) {
      throw new Error(
        `rnp_key_revoke failed for fingerprint=${keyFingerprint}`
      );
    }
    await this.saveKeyRings();
  },

  _getKeyHandleByKeyIdOrFingerprint(ffi, id, findPrimary) {
    if (!id.startsWith("0x")) {
      throw new Error("unexpected identifier " + id);
    } else {
      // remove 0x
      id = id.substring(2);
    }

    let type = null;
    if (id.length == 16) {
      type = "keyid";
    } else if (id.length == 40 || id.length == 32) {
      type = "fingerprint";
    } else {
      throw new Error("key/fingerprint identifier of unexpected length: " + id);
    }

    let key = new RNPLib.rnp_key_handle_t();
    if (RNPLib.rnp_locate_key(ffi, type, id, key.address())) {
      throw new Error("rnp_locate_key failed, " + type + ", " + id);
    }

    if (!key.isNull() && findPrimary) {
      let is_subkey = new lazy.ctypes.bool();
      if (RNPLib.rnp_key_is_sub(key, is_subkey.address())) {
        throw new Error("rnp_key_is_sub failed");
      }
      if (is_subkey.value) {
        let primaryKey = this.getPrimaryKeyHandleFromSub(ffi, key);
        RNPLib.rnp_key_handle_destroy(key);
        key = primaryKey;
      }
    }

    if (!key.isNull() && this.isBadKey(key, null, ffi)) {
      RNPLib.rnp_key_handle_destroy(key);
      key = new RNPLib.rnp_key_handle_t();
    }

    return key;
  },

  getPrimaryKeyHandleByKeyIdOrFingerprint(ffi, id) {
    return this._getKeyHandleByKeyIdOrFingerprint(ffi, id, true);
  },

  getKeyHandleByKeyIdOrFingerprint(ffi, id) {
    return this._getKeyHandleByKeyIdOrFingerprint(ffi, id, false);
  },

  async getKeyHandleByIdentifier(ffi, id) {
    let key = null;

    if (id.startsWith("<")) {
      //throw new Error("search by email address not yet implemented: " + id);
      if (!id.endsWith(">")) {
        throw new Error(
          "if search identifier starts with < then it must end with > : " + id
        );
      }
      key = await this.findKeyByEmail(id);
    } else {
      key = this.getKeyHandleByKeyIdOrFingerprint(ffi, id);
    }
    return key;
  },

  isKeyUsableFor(key, usage) {
    let allowed = new lazy.ctypes.bool();
    if (RNPLib.rnp_key_allows_usage(key, usage, allowed.address())) {
      throw new Error("rnp_key_allows_usage failed");
    }
    if (!allowed.value) {
      return false;
    }

    if (usage != str_sign) {
      return true;
    }

    return (
      RNPLib.getSecretAvailableFromHandle(key) &&
      RNPLib.isSecretKeyMaterialAvailable(key)
    );
  },

  getSuitableSubkey(primary, usage) {
    let sub_count = new lazy.ctypes.size_t();
    if (RNPLib.rnp_key_get_subkey_count(primary, sub_count.address())) {
      throw new Error("rnp_key_get_subkey_count failed");
    }

    // For compatibility with GnuPG, when encrypting to a single subkey,
    // encrypt to the most recently created subkey. (Bug 1665281)
    let newest_created = null;
    let newest_handle = null;

    for (let i = 0; i < sub_count.value; i++) {
      let sub_handle = new RNPLib.rnp_key_handle_t();
      if (RNPLib.rnp_key_get_subkey_at(primary, i, sub_handle.address())) {
        throw new Error("rnp_key_get_subkey_at failed");
      }
      let skip =
        this.isBadKey(sub_handle, primary, null) ||
        this.isKeyExpired(sub_handle);
      if (!skip) {
        let key_revoked = new lazy.ctypes.bool();
        if (RNPLib.rnp_key_is_revoked(sub_handle, key_revoked.address())) {
          throw new Error("rnp_key_is_revoked failed");
        }
        if (key_revoked.value) {
          skip = true;
        }
      }
      if (!skip) {
        if (!this.isKeyUsableFor(sub_handle, usage)) {
          skip = true;
        }
      }

      if (!skip) {
        let created = this.getKeyCreatedValueFromHandle(sub_handle);
        if (!newest_handle || created > newest_created) {
          if (newest_handle) {
            RNPLib.rnp_key_handle_destroy(newest_handle);
          }
          newest_handle = sub_handle;
          sub_handle = null;
          newest_created = created;
        }
      }

      if (sub_handle) {
        RNPLib.rnp_key_handle_destroy(sub_handle);
      }
    }

    return newest_handle;
  },

  /**
   * Get a minimal Autocrypt-compatible public key, for the given key
   * that exactly matches the given userId.
   *
   * @param {rnp_key_handle_t} key - RNP key handle.
   * @param {string} uidString - The userID to include.
   * @returns {string} The encoded key, or the empty string on failure.
   */
  getSuitableEncryptKeyAsAutocrypt(key, userId) {
    // Prefer usable subkeys, because they are always newer
    // (or same age) as primary key.

    let use_sub = this.getSuitableSubkey(key, str_encrypt);
    if (!use_sub && !this.isKeyUsableFor(key, str_encrypt)) {
      return "";
    }

    let result = this.getAutocryptKeyB64ByHandle(key, use_sub, userId);

    if (use_sub) {
      RNPLib.rnp_key_handle_destroy(use_sub);
    }
    return result;
  },

  addSuitableEncryptKey(key, op) {
    // Prefer usable subkeys, because they are always newer
    // (or same age) as primary key.

    let use_sub = this.getSuitableSubkey(key, str_encrypt);
    if (!use_sub && !this.isKeyUsableFor(key, str_encrypt)) {
      throw new Error("no suitable subkey found for " + str_encrypt);
    }

    if (
      RNPLib.rnp_op_encrypt_add_recipient(op, use_sub != null ? use_sub : key)
    ) {
      throw new Error("rnp_op_encrypt_add_recipient sender failed");
    }
    if (use_sub) {
      RNPLib.rnp_key_handle_destroy(use_sub);
    }
  },

  addAliasKeys(aliasKeys, op) {
    for (let ak of aliasKeys) {
      let key = this.getKeyHandleByKeyIdOrFingerprint(RNPLib.ffi, "0x" + ak);
      if (!key || key.isNull()) {
        console.debug(
          "addAliasKeys: cannot find key used by alias rule: " + ak
        );
        return false;
      }
      this.addSuitableEncryptKey(key, op);
      RNPLib.rnp_key_handle_destroy(key);
    }
    return true;
  },

  /**
   * Get a minimal Autocrypt-compatible public key, for the given email
   * address.
   *
   * @param {string} email - Use a userID with this email address.
   * @returns {string} The encoded key, or the empty string on failure.
   */
  async getRecipientAutocryptKeyForEmail(email) {
    email = email.toLowerCase();

    let key = await this.findKeyByEmail("<" + email + ">", true);
    if (!key || key.isNull()) {
      return "";
    }

    let keyInfo = {};
    let ok = this.getKeyInfoFromHandle(
      RNPLib.ffi,
      key,
      keyInfo,
      false,
      false,
      false
    );
    if (!ok) {
      throw new Error("getKeyInfoFromHandle failed");
    }

    let result = "";
    let userId = keyInfo.userIds.find(
      uid =>
        uid.type == "uid" &&
        lazy.EnigmailFuncs.getEmailFromUserID(uid.userId).toLowerCase() == email
    );
    if (userId) {
      result = this.getSuitableEncryptKeyAsAutocrypt(key, userId.userId);
    }
    RNPLib.rnp_key_handle_destroy(key);
    return result;
  },

  async addEncryptionKeyForEmail(email, op) {
    let key = await this.findKeyByEmail(email, true);
    if (!key || key.isNull()) {
      return false;
    }
    this.addSuitableEncryptKey(key, op);
    RNPLib.rnp_key_handle_destroy(key);
    return true;
  },

  getEmailWithoutBrackets(email) {
    if (email.startsWith("<") && email.endsWith(">")) {
      return email.substring(1, email.length - 1);
    }
    return email;
  },

  async encryptAndOrSign(plaintext, args, resultStatus) {
    let signedInner;

    if (args.sign && args.senderKeyIsExternal) {
      if (!lazy.GPGME.allDependenciesLoaded()) {
        throw new Error(
          "invalid configuration, request to use external GnuPG key, but GPGME isn't working"
        );
      }
      if (args.sigTypeClear) {
        throw new Error(
          "unexpected signing request with external GnuPG key configuration"
        );
      }

      if (args.encrypt) {
        // If we are asked to encrypt and sign at the same time, it
        // means we're asked to produce the combined OpenPGP encoding.
        // We ask GPG to produce a regular signature, and will then
        // combine it with the encryption produced by RNP.
        let orgEncrypt = args.encrypt;
        args.encrypt = false;
        signedInner = await lazy.GPGME.sign(plaintext, args, resultStatus);
        args.encrypt = orgEncrypt;
      } else {
        // We aren't asked to encrypt, but sign only. That means the
        // caller needs the detatched signature, either for MIME
        // mime encoding with separate signature part, or for the nested
        // approach with separate signing and encryption layers.
        return lazy.GPGME.signDetached(plaintext, args, resultStatus);
      }
    }

    resultStatus.exitCode = -1;
    resultStatus.statusFlags = 0;
    resultStatus.statusMsg = "";
    resultStatus.errorMsg = "";

    let data_array;
    if (args.sign && args.senderKeyIsExternal) {
      data_array = lazy.ctypes.uint8_t.array()(signedInner);
    } else {
      let arr = plaintext.split("").map(e => e.charCodeAt());
      data_array = lazy.ctypes.uint8_t.array()(arr);
    }

    let input = new RNPLib.rnp_input_t();
    if (
      RNPLib.rnp_input_from_memory(
        input.address(),
        data_array,
        data_array.length,
        false
      )
    ) {
      throw new Error("rnp_input_from_memory failed");
    }

    let output = new RNPLib.rnp_output_t();
    if (RNPLib.rnp_output_to_memory(output.address(), 0)) {
      throw new Error("rnp_output_to_memory failed");
    }

    let op;
    if (args.encrypt) {
      op = new RNPLib.rnp_op_encrypt_t();
      if (
        RNPLib.rnp_op_encrypt_create(op.address(), RNPLib.ffi, input, output)
      ) {
        throw new Error("rnp_op_encrypt_create failed");
      }
    } else if (args.sign && !args.senderKeyIsExternal) {
      op = new RNPLib.rnp_op_sign_t();
      if (args.sigTypeClear) {
        if (
          RNPLib.rnp_op_sign_cleartext_create(
            op.address(),
            RNPLib.ffi,
            input,
            output
          )
        ) {
          throw new Error("rnp_op_sign_cleartext_create failed");
        }
      } else if (args.sigTypeDetached) {
        if (
          RNPLib.rnp_op_sign_detached_create(
            op.address(),
            RNPLib.ffi,
            input,
            output
          )
        ) {
          throw new Error("rnp_op_sign_detached_create failed");
        }
      } else {
        throw new Error(
          "not yet implemented scenario: signing, neither clear nor encrypt, without encryption"
        );
      }
    } else {
      throw new Error("invalid parameters, neither encrypt nor sign");
    }

    let senderKeyTracker = null;
    let subKeyTracker = null;

    try {
      if ((args.sign && !args.senderKeyIsExternal) || args.encryptToSender) {
        {
          // Use a temporary scope to ensure the senderKey variable
          // cannot be accessed later on.
          let senderKey = await this.getKeyHandleByIdentifier(
            RNPLib.ffi,
            args.sender
          );
          if (!senderKey || senderKey.isNull()) {
            return null;
          }

          senderKeyTracker = new RnpPrivateKeyUnlockTracker(senderKey);
          senderKeyTracker.setAllowPromptingUserForPassword(true);
          senderKeyTracker.setAllowAutoUnlockWithCachedPasswords(true);
        }

        // Manually configured external key overrides the check for
        // a valid personal key.
        if (!args.senderKeyIsExternal) {
          if (!senderKeyTracker.isSecret()) {
            throw new Error(
              `configured sender key ${args.sender} isn't available`
            );
          }
          if (
            !(await lazy.PgpSqliteDb2.isAcceptedAsPersonalKey(
              senderKeyTracker.getFingerprint()
            ))
          ) {
            throw new Error(
              `configured sender key ${args.sender} isn't accepted as a personal key`
            );
          }
        }

        if (args.encryptToSender) {
          this.addSuitableEncryptKey(senderKeyTracker.getHandle(), op);
        }

        if (args.sign && !args.senderKeyIsExternal) {
          let signingKeyTrackerReference = senderKeyTracker;

          // Prefer usable subkeys, because they are always newer
          // (or same age) as primary key.
          let usableSubKeyHandle = this.getSuitableSubkey(
            senderKeyTracker.getHandle(),
            str_sign
          );
          if (
            !usableSubKeyHandle &&
            !this.isKeyUsableFor(senderKeyTracker.getHandle(), str_sign)
          ) {
            throw new Error("no suitable (sub)key found for " + str_sign);
          }
          if (usableSubKeyHandle) {
            subKeyTracker = new RnpPrivateKeyUnlockTracker(usableSubKeyHandle);
            subKeyTracker.setAllowPromptingUserForPassword(true);
            subKeyTracker.setAllowAutoUnlockWithCachedPasswords(true);
            if (subKeyTracker.available()) {
              signingKeyTrackerReference = subKeyTracker;
            }
          }

          await signingKeyTrackerReference.unlock();

          if (args.encrypt) {
            if (
              RNPLib.rnp_op_encrypt_add_signature(
                op,
                signingKeyTrackerReference.getHandle(),
                null
              )
            ) {
              throw new Error("rnp_op_encrypt_add_signature failed");
            }
          } else if (
            RNPLib.rnp_op_sign_add_signature(
              op,
              signingKeyTrackerReference.getHandle(),
              null
            )
          ) {
            throw new Error("rnp_op_sign_add_signature failed");
          }
          // This was just a reference, no ownership.
          signingKeyTrackerReference = null;
        }
      }

      if (args.encrypt) {
        // If we have an alias definition, it will be used, and the usual
        // lookup by email address will be skipped. Earlier code should
        // have already checked that alias keys are available and usable
        // for encryption, so we fail if a problem is found.

        for (let rcpList of [args.to, args.bcc]) {
          for (let rcpEmail of rcpList) {
            rcpEmail = rcpEmail.toLowerCase();
            let aliasKeys = args.aliasKeys.get(
              this.getEmailWithoutBrackets(rcpEmail)
            );
            if (aliasKeys) {
              if (!this.addAliasKeys(aliasKeys, op)) {
                resultStatus.statusFlags |=
                  lazy.EnigmailConstants.INVALID_RECIPIENT;
                return null;
              }
            } else if (!(await this.addEncryptionKeyForEmail(rcpEmail, op))) {
              resultStatus.statusFlags |=
                lazy.EnigmailConstants.INVALID_RECIPIENT;
              return null;
            }
          }
        }

        if (AppConstants.MOZ_UPDATE_CHANNEL != "release") {
          let debugKey = Services.prefs.getStringPref(
            "mail.openpgp.debug.extra_encryption_key"
          );
          if (debugKey) {
            let handle = this.getKeyHandleByKeyIdOrFingerprint(
              RNPLib.ffi,
              debugKey
            );
            if (!handle.isNull()) {
              console.debug("encrypting to debug key " + debugKey);
              this.addSuitableEncryptKey(handle, op);
              RNPLib.rnp_key_handle_destroy(handle);
            }
          }
        }

        // Don't use AEAD as long as RNP uses v5 packets which aren't
        // widely compatible with other clients.
        if (RNPLib.rnp_op_encrypt_set_aead(op, "NONE")) {
          throw new Error("rnp_op_encrypt_set_aead failed");
        }

        if (RNPLib.rnp_op_encrypt_set_cipher(op, "AES256")) {
          throw new Error("rnp_op_encrypt_set_cipher failed");
        }

        // TODO, map args.signatureHash string to RNP and call
        //       rnp_op_encrypt_set_hash
        if (RNPLib.rnp_op_encrypt_set_hash(op, "SHA256")) {
          throw new Error("rnp_op_encrypt_set_hash failed");
        }

        if (RNPLib.rnp_op_encrypt_set_armor(op, args.armor)) {
          throw new Error("rnp_op_encrypt_set_armor failed");
        }

        if (args.sign && args.senderKeyIsExternal) {
          if (RNPLib.rnp_op_encrypt_set_flags(op, RNPLib.RNP_ENCRYPT_NOWRAP)) {
            throw new Error("rnp_op_encrypt_set_flags failed");
          }
        }

        let rv = RNPLib.rnp_op_encrypt_execute(op);
        if (rv) {
          throw new Error("rnp_op_encrypt_execute failed: " + rv);
        }
        RNPLib.rnp_op_encrypt_destroy(op);
      } else if (args.sign && !args.senderKeyIsExternal) {
        if (RNPLib.rnp_op_sign_set_hash(op, "SHA256")) {
          throw new Error("rnp_op_sign_set_hash failed");
        }
        // TODO, map args.signatureHash string to RNP and call
        //       rnp_op_encrypt_set_hash

        if (RNPLib.rnp_op_sign_set_armor(op, args.armor)) {
          throw new Error("rnp_op_sign_set_armor failed");
        }

        if (RNPLib.rnp_op_sign_execute(op)) {
          throw new Error("rnp_op_sign_execute failed");
        }
        RNPLib.rnp_op_sign_destroy(op);
      }
    } finally {
      if (subKeyTracker) {
        subKeyTracker.release();
      }
      if (senderKeyTracker) {
        senderKeyTracker.release();
      }
    }

    RNPLib.rnp_input_destroy(input);

    let result = null;

    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    if (
      !RNPLib.rnp_output_memory_get_buf(
        output,
        result_buf.address(),
        result_len.address(),
        false
      )
    ) {
      let char_array = lazy.ctypes.cast(
        result_buf,
        lazy.ctypes.char.array(result_len.value).ptr
      ).contents;

      result = char_array.readString();
    }

    RNPLib.rnp_output_destroy(output);

    resultStatus.exitCode = 0;

    if (args.encrypt) {
      resultStatus.statusFlags |= lazy.EnigmailConstants.END_ENCRYPTION;
    }

    if (args.sign) {
      resultStatus.statusFlags |= lazy.EnigmailConstants.SIG_CREATED;
    }

    return result;
  },

  /**
   * @param {number} expiryTime - Time to check, in seconds from the epoch.
   * @returns {boolean} - true if the given time is after now.
   */
  isExpiredTime(expiryTime) {
    if (!expiryTime) {
      return false;
    }
    let nowSeconds = Math.floor(Date.now() / 1000);
    return nowSeconds > expiryTime;
  },

  isKeyExpired(handle) {
    let expiration = new lazy.ctypes.uint32_t();
    if (RNPLib.rnp_key_get_expiration(handle, expiration.address())) {
      throw new Error("rnp_key_get_expiration failed");
    }
    if (!expiration.value) {
      return false;
    }

    let created = this.getKeyCreatedValueFromHandle(handle);
    let expirationSeconds = created + expiration.value;
    return this.isExpiredTime(expirationSeconds);
  },

  async findKeyByEmail(id, onlyIfAcceptableAsRecipientKey = false) {
    if (!id.startsWith("<") || !id.endsWith(">") || id.includes(" ")) {
      throw new Error(`Invalid argument; id=${id}`);
    }

    let emailWithoutBrackets = id.substring(1, id.length - 1);

    let iter = new RNPLib.rnp_identifier_iterator_t();
    let grip = new lazy.ctypes.char.ptr();

    if (
      RNPLib.rnp_identifier_iterator_create(RNPLib.ffi, iter.address(), "grip")
    ) {
      throw new Error("rnp_identifier_iterator_create failed");
    }

    let foundHandle = null;
    let tentativeUnverifiedHandle = null;

    while (
      !foundHandle &&
      !RNPLib.rnp_identifier_iterator_next(iter, grip.address())
    ) {
      if (grip.isNull()) {
        break;
      }

      let have_handle = false;
      let handle = new RNPLib.rnp_key_handle_t();

      try {
        let is_subkey = new lazy.ctypes.bool();
        let uid_count = new lazy.ctypes.size_t();

        if (RNPLib.rnp_locate_key(RNPLib.ffi, "grip", grip, handle.address())) {
          throw new Error("rnp_locate_key failed");
        }
        have_handle = true;
        if (RNPLib.rnp_key_is_sub(handle, is_subkey.address())) {
          throw new Error("rnp_key_is_sub failed");
        }
        if (is_subkey.value) {
          continue;
        }
        if (this.isBadKey(handle, null, RNPLib.ffi)) {
          continue;
        }
        let key_revoked = new lazy.ctypes.bool();
        if (RNPLib.rnp_key_is_revoked(handle, key_revoked.address())) {
          throw new Error("rnp_key_is_revoked failed");
        }

        if (key_revoked.value) {
          continue;
        }

        if (this.isKeyExpired(handle)) {
          continue;
        }

        if (RNPLib.rnp_key_get_uid_count(handle, uid_count.address())) {
          throw new Error("rnp_key_get_uid_count failed");
        }

        let foundUid = false;
        for (let i = 0; i < uid_count.value && !foundUid; i++) {
          let uid_handle = new RNPLib.rnp_uid_handle_t();

          if (
            RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())
          ) {
            throw new Error("rnp_key_get_uid_handle_at failed");
          }

          if (!this.isBadUid(uid_handle) && !this.isRevokedUid(uid_handle)) {
            let uid_str = new lazy.ctypes.char.ptr();
            if (RNPLib.rnp_key_get_uid_at(handle, i, uid_str.address())) {
              throw new Error("rnp_key_get_uid_at failed");
            }

            let userId = uid_str.readStringReplaceMalformed();
            RNPLib.rnp_buffer_destroy(uid_str);

            if (
              lazy.EnigmailFuncs.getEmailFromUserID(userId).toLowerCase() ==
              emailWithoutBrackets
            ) {
              foundUid = true;

              if (onlyIfAcceptableAsRecipientKey) {
                // a key is acceptable, either:
                // - without secret key, it's accepted verified or unverified
                // - with secret key, must be marked as personal

                let have_secret = new lazy.ctypes.bool();
                if (RNPLib.rnp_key_have_secret(handle, have_secret.address())) {
                  throw new Error("rnp_key_have_secret failed");
                }

                let fingerprint = new lazy.ctypes.char.ptr();
                if (RNPLib.rnp_key_get_fprint(handle, fingerprint.address())) {
                  throw new Error("rnp_key_get_fprint failed");
                }
                let fpr = fingerprint.readString();
                RNPLib.rnp_buffer_destroy(fingerprint);

                if (have_secret.value) {
                  let isAccepted =
                    await lazy.PgpSqliteDb2.isAcceptedAsPersonalKey(fpr);
                  if (isAccepted) {
                    foundHandle = handle;
                    have_handle = false;
                    if (tentativeUnverifiedHandle) {
                      RNPLib.rnp_key_handle_destroy(tentativeUnverifiedHandle);
                      tentativeUnverifiedHandle = null;
                    }
                  }
                } else {
                  let acceptanceResult = {};
                  try {
                    await lazy.PgpSqliteDb2.getAcceptance(
                      fpr,
                      emailWithoutBrackets,
                      acceptanceResult
                    );
                  } catch (ex) {
                    console.debug("getAcceptance failed: " + ex);
                  }

                  if (!acceptanceResult.emailDecided) {
                    continue;
                  }
                  if (acceptanceResult.fingerprintAcceptance == "unverified") {
                    /* keep searching for a better, verified key */
                    if (!tentativeUnverifiedHandle) {
                      tentativeUnverifiedHandle = handle;
                      have_handle = false;
                    }
                  } else if (
                    acceptanceResult.fingerprintAcceptance == "verified"
                  ) {
                    foundHandle = handle;
                    have_handle = false;
                    if (tentativeUnverifiedHandle) {
                      RNPLib.rnp_key_handle_destroy(tentativeUnverifiedHandle);
                      tentativeUnverifiedHandle = null;
                    }
                  }
                }
              } else {
                foundHandle = handle;
                have_handle = false;
              }
            }
          }
          RNPLib.rnp_uid_handle_destroy(uid_handle);
        }
      } catch (ex) {
        console.log(ex);
      } finally {
        if (have_handle) {
          RNPLib.rnp_key_handle_destroy(handle);
        }
      }
    }

    if (!foundHandle && tentativeUnverifiedHandle) {
      foundHandle = tentativeUnverifiedHandle;
      tentativeUnverifiedHandle = null;
    }

    RNPLib.rnp_identifier_iterator_destroy(iter);
    return foundHandle;
  },

  async getPublicKey(id, store = RNPLib.ffi) {
    let result = "";
    let key = await this.getKeyHandleByIdentifier(store, id);

    if (key.isNull()) {
      return result;
    }

    let flags =
      RNPLib.RNP_KEY_EXPORT_ARMORED |
      RNPLib.RNP_KEY_EXPORT_PUBLIC |
      RNPLib.RNP_KEY_EXPORT_SUBKEYS;

    let output_to_memory = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(output_to_memory.address(), 0);

    if (RNPLib.rnp_key_export(key, output_to_memory, flags)) {
      throw new Error("rnp_key_export failed");
    }

    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    let exitCode = RNPLib.rnp_output_memory_get_buf(
      output_to_memory,
      result_buf.address(),
      result_len.address(),
      false
    );

    if (!exitCode) {
      let char_array = lazy.ctypes.cast(
        result_buf,
        lazy.ctypes.char.array(result_len.value).ptr
      ).contents;

      result = char_array.readString();
    }

    RNPLib.rnp_output_destroy(output_to_memory);
    RNPLib.rnp_key_handle_destroy(key);
    return result;
  },

  /**
   * Exports a public key, strips all signatures added by others,
   * and optionally also strips user IDs. Self-signatures are kept.
   * The given key handle will not be modified. The input key will be
   * copied to a temporary area, only the temporary copy will be
   * modified. The result key will be streamed to the given output.
   *
   * @param {rnp_key_handle_t} expKey - RNP key handle
   * @param {boolean} keepUserIDs - if true keep users IDs
   * @param {rnp_output_t} out_binary - output stream handle
   *
   */
  export_pubkey_strip_sigs_uids(expKey, keepUserIDs, out_binary) {
    let expKeyId = this.getKeyIDFromHandle(expKey);

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    let exportFlags =
      RNPLib.RNP_KEY_EXPORT_SUBKEYS | RNPLib.RNP_KEY_EXPORT_PUBLIC;
    let importFlags = RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS;

    let output_to_memory = new RNPLib.rnp_output_t();
    if (RNPLib.rnp_output_to_memory(output_to_memory.address(), 0)) {
      throw new Error("rnp_output_to_memory failed");
    }

    if (RNPLib.rnp_key_export(expKey, output_to_memory, exportFlags)) {
      throw new Error("rnp_key_export failed");
    }

    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    if (
      RNPLib.rnp_output_memory_get_buf(
        output_to_memory,
        result_buf.address(),
        result_len.address(),
        false
      )
    ) {
      throw new Error("rnp_output_memory_get_buf failed");
    }

    let input_from_memory = new RNPLib.rnp_input_t();

    if (
      RNPLib.rnp_input_from_memory(
        input_from_memory.address(),
        result_buf,
        result_len,
        false
      )
    ) {
      throw new Error("rnp_input_from_memory failed");
    }

    if (RNPLib.rnp_import_keys(tempFFI, input_from_memory, importFlags, null)) {
      throw new Error("rnp_import_keys failed");
    }

    let tempKey = this.getKeyHandleByKeyIdOrFingerprint(
      tempFFI,
      "0x" + expKeyId
    );

    // Strip

    if (!keepUserIDs) {
      let uid_count = new lazy.ctypes.size_t();
      if (RNPLib.rnp_key_get_uid_count(tempKey, uid_count.address())) {
        throw new Error("rnp_key_get_uid_count failed");
      }
      for (let i = uid_count.value; i > 0; i--) {
        let uid_handle = new RNPLib.rnp_uid_handle_t();
        if (
          RNPLib.rnp_key_get_uid_handle_at(tempKey, i - 1, uid_handle.address())
        ) {
          throw new Error("rnp_key_get_uid_handle_at failed");
        }
        if (RNPLib.rnp_uid_remove(tempKey, uid_handle)) {
          throw new Error("rnp_uid_remove failed");
        }
        RNPLib.rnp_uid_handle_destroy(uid_handle);
      }
    }

    if (
      RNPLib.rnp_key_remove_signatures(
        tempKey,
        RNPLib.RNP_KEY_SIGNATURE_NON_SELF_SIG,
        null,
        null
      )
    ) {
      throw new Error("rnp_key_remove_signatures failed");
    }

    if (RNPLib.rnp_key_export(tempKey, out_binary, exportFlags)) {
      throw new Error("rnp_key_export failed");
    }
    RNPLib.rnp_key_handle_destroy(tempKey);

    RNPLib.rnp_input_destroy(input_from_memory);
    RNPLib.rnp_output_destroy(output_to_memory);
    RNPLib.rnp_ffi_destroy(tempFFI);
  },

  /**
   * Export one or multiple public keys.
   *
   * @param {string[]} idArrayFull - an array of key IDs or fingerprints
   *   that should be exported as full keys including all attributes.
   * @param {string[]} idArrayReduced - an array of key IDs or
   *   fingerprints that should be exported with all self-signatures,
   *   but without signatures from others.
   * @param {string[]} idArrayMinimal - an array of key IDs or
   *   fingerprints that should be exported as minimized keys.
   * @returns {string} - An ascii armored key block containing all
   *   requested (available) keys.
   */
  getMultiplePublicKeys(idArrayFull, idArrayReduced, idArrayMinimal) {
    let out_final = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(out_final.address(), 0);

    let out_binary = new RNPLib.rnp_output_t();
    let rv;
    if (
      (rv = RNPLib.rnp_output_to_armor(
        out_final,
        out_binary.address(),
        "public key"
      ))
    ) {
      throw new Error("rnp_output_to_armor failed:" + rv);
    }

    if ((rv = RNPLib.rnp_output_armor_set_line_length(out_binary, 64))) {
      throw new Error("rnp_output_armor_set_line_length failed:" + rv);
    }

    let flags = RNPLib.RNP_KEY_EXPORT_PUBLIC | RNPLib.RNP_KEY_EXPORT_SUBKEYS;

    if (idArrayFull) {
      for (let id of idArrayFull) {
        let key = this.getKeyHandleByKeyIdOrFingerprint(RNPLib.ffi, id);
        if (key.isNull()) {
          continue;
        }

        if (RNPLib.rnp_key_export(key, out_binary, flags)) {
          throw new Error("rnp_key_export failed");
        }

        RNPLib.rnp_key_handle_destroy(key);
      }
    }

    if (idArrayReduced) {
      for (let id of idArrayReduced) {
        let key = this.getPrimaryKeyHandleByKeyIdOrFingerprint(RNPLib.ffi, id);
        if (key.isNull()) {
          continue;
        }

        this.export_pubkey_strip_sigs_uids(key, true, out_binary);

        RNPLib.rnp_key_handle_destroy(key);
      }
    }

    if (idArrayMinimal) {
      for (let id of idArrayMinimal) {
        let key = this.getPrimaryKeyHandleByKeyIdOrFingerprint(RNPLib.ffi, id);
        if (key.isNull()) {
          continue;
        }

        this.export_pubkey_strip_sigs_uids(key, false, out_binary);

        RNPLib.rnp_key_handle_destroy(key);
      }
    }

    if ((rv = RNPLib.rnp_output_finish(out_binary))) {
      throw new Error("rnp_output_finish failed: " + rv);
    }

    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    let exitCode = RNPLib.rnp_output_memory_get_buf(
      out_final,
      result_buf.address(),
      result_len.address(),
      false
    );

    let result = "";
    if (!exitCode) {
      let char_array = lazy.ctypes.cast(
        result_buf,
        lazy.ctypes.char.array(result_len.value).ptr
      ).contents;
      result = char_array.readString();
    }

    RNPLib.rnp_output_destroy(out_binary);
    RNPLib.rnp_output_destroy(out_final);

    return result;
  },

  /**
   * The RNP library may store keys in a format that isn't compatible
   * with GnuPG, see bug 1713621 for an example where this happened.
   *
   * This function modifies the input key to make it compatible.
   *
   * The caller must ensure that the key is unprotected when calling
   * this function, and must apply the desired protection afterwards.
   */
  ensureECCSubkeyIsGnuPGCompatible(tempKey) {
    let algo = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_key_get_alg(tempKey, algo.address())) {
      throw new Error("rnp_key_get_alg failed");
    }
    let algoStr = algo.readString();
    RNPLib.rnp_buffer_destroy(algo);

    if (algoStr.toLowerCase() != "ecdh") {
      return;
    }

    let curve = new lazy.ctypes.char.ptr();
    if (RNPLib.rnp_key_get_curve(tempKey, curve.address())) {
      throw new Error("rnp_key_get_curve failed");
    }
    let curveStr = curve.readString();
    RNPLib.rnp_buffer_destroy(curve);

    if (curveStr.toLowerCase() != "curve25519") {
      return;
    }

    let tweak_status = new lazy.ctypes.bool();
    let rc = RNPLib.rnp_key_25519_bits_tweaked(tempKey, tweak_status.address());
    if (rc) {
      throw new Error("rnp_key_25519_bits_tweaked failed: " + rc);
    }

    // If it's not tweaked yet, then tweak to make it compatible.
    if (!tweak_status.value) {
      rc = RNPLib.rnp_key_25519_bits_tweak(tempKey);
      if (rc) {
        throw new Error("rnp_key_25519_bits_tweak failed: " + rc);
      }
    }
  },

  async backupSecretKeys(fprs, backupPassword) {
    if (!fprs.length) {
      throw new Error("invalid fprs parameter");
    }

    /*
     * Strategy:
     * - copy keys to a temporary space, in-memory only (ffi)
     * - if we failed to decrypt the secret keys, return null
     * - change the password of all secret keys in the temporary space
     * - export from the temporary space
     */

    let out_final = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(out_final.address(), 0);

    let out_binary = new RNPLib.rnp_output_t();
    let rv;
    if (
      (rv = RNPLib.rnp_output_to_armor(
        out_final,
        out_binary.address(),
        "secret key"
      ))
    ) {
      throw new Error("rnp_output_to_armor failed:" + rv);
    }

    let tempFFI = RNPLib.prepare_ffi();
    if (!tempFFI) {
      throw new Error("Couldn't initialize librnp.");
    }

    let exportFlags =
      RNPLib.RNP_KEY_EXPORT_SUBKEYS | RNPLib.RNP_KEY_EXPORT_SECRET;
    let importFlags =
      RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS | RNPLib.RNP_LOAD_SAVE_SECRET_KEYS;

    let unlockFailed = false;
    let pwCache = {
      passwords: [],
    };

    for (let fpr of fprs) {
      let fprStr = fpr;
      let expKey = await this.getKeyHandleByIdentifier(
        RNPLib.ffi,
        "0x" + fprStr
      );

      let output_to_memory = new RNPLib.rnp_output_t();
      if (RNPLib.rnp_output_to_memory(output_to_memory.address(), 0)) {
        throw new Error("rnp_output_to_memory failed");
      }

      if (RNPLib.rnp_key_export(expKey, output_to_memory, exportFlags)) {
        throw new Error("rnp_key_export failed");
      }
      RNPLib.rnp_key_handle_destroy(expKey);
      expKey = null;

      let result_buf = new lazy.ctypes.uint8_t.ptr();
      let result_len = new lazy.ctypes.size_t();
      if (
        RNPLib.rnp_output_memory_get_buf(
          output_to_memory,
          result_buf.address(),
          result_len.address(),
          false
        )
      ) {
        throw new Error("rnp_output_memory_get_buf failed");
      }

      let input_from_memory = new RNPLib.rnp_input_t();
      if (
        RNPLib.rnp_input_from_memory(
          input_from_memory.address(),
          result_buf,
          result_len,
          false
        )
      ) {
        throw new Error("rnp_input_from_memory failed");
      }

      if (
        RNPLib.rnp_import_keys(tempFFI, input_from_memory, importFlags, null)
      ) {
        throw new Error("rnp_import_keys failed");
      }

      RNPLib.rnp_input_destroy(input_from_memory);
      RNPLib.rnp_output_destroy(output_to_memory);
      input_from_memory = null;
      output_to_memory = null;
      result_buf = null;

      let tracker = RnpPrivateKeyUnlockTracker.constructFromFingerprint(
        fprStr,
        tempFFI
      );
      if (!tracker.available()) {
        tracker.release();
        continue;
      }

      tracker.setAllowPromptingUserForPassword(true);
      tracker.setAllowAutoUnlockWithCachedPasswords(true);
      tracker.setPasswordCache(pwCache);
      tracker.setRememberUnlockPassword(true);

      await tracker.unlock();
      if (!tracker.isUnlocked()) {
        unlockFailed = true;
        tracker.release();
        break;
      }

      tracker.unprotect();
      tracker.setPassphrase(backupPassword);

      let sub_count = new lazy.ctypes.size_t();
      if (
        RNPLib.rnp_key_get_subkey_count(
          tracker.getHandle(),
          sub_count.address()
        )
      ) {
        throw new Error("rnp_key_get_subkey_count failed");
      }
      for (let i = 0; i < sub_count.value; i++) {
        let sub_handle = new RNPLib.rnp_key_handle_t();
        if (
          RNPLib.rnp_key_get_subkey_at(
            tracker.getHandle(),
            i,
            sub_handle.address()
          )
        ) {
          throw new Error("rnp_key_get_subkey_at failed");
        }

        let subTracker = new RnpPrivateKeyUnlockTracker(sub_handle);
        if (subTracker.available()) {
          subTracker.setAllowPromptingUserForPassword(true);
          subTracker.setAllowAutoUnlockWithCachedPasswords(true);
          subTracker.setPasswordCache(pwCache);
          subTracker.setRememberUnlockPassword(true);

          await subTracker.unlock();
          if (!subTracker.isUnlocked()) {
            unlockFailed = true;
          } else {
            subTracker.unprotect();
            this.ensureECCSubkeyIsGnuPGCompatible(subTracker.getHandle());
            subTracker.setPassphrase(backupPassword);
          }
        }
        subTracker.release();
        if (unlockFailed) {
          break;
        }
      }

      if (
        !unlockFailed &&
        RNPLib.rnp_key_export(tracker.getHandle(), out_binary, exportFlags)
      ) {
        throw new Error("rnp_key_export failed");
      }

      tracker.release();
      if (unlockFailed) {
        break;
      }
    }
    RNPLib.rnp_ffi_destroy(tempFFI);

    let result = "";
    if (!unlockFailed) {
      if ((rv = RNPLib.rnp_output_finish(out_binary))) {
        throw new Error("rnp_output_finish failed: " + rv);
      }

      let result_buf = new lazy.ctypes.uint8_t.ptr();
      let result_len = new lazy.ctypes.size_t();
      let exitCode = RNPLib.rnp_output_memory_get_buf(
        out_final,
        result_buf.address(),
        result_len.address(),
        false
      );

      if (!exitCode) {
        let char_array = lazy.ctypes.cast(
          result_buf,
          lazy.ctypes.char.array(result_len.value).ptr
        ).contents;
        result = char_array.readString();
      }
    }

    RNPLib.rnp_output_destroy(out_binary);
    RNPLib.rnp_output_destroy(out_final);

    return result;
  },

  async unlockAndGetNewRevocation(id, pass) {
    let result = "";
    let key = await this.getKeyHandleByIdentifier(RNPLib.ffi, id);

    if (key.isNull()) {
      return result;
    }

    let tracker = new RnpPrivateKeyUnlockTracker(key);
    tracker.setAllowPromptingUserForPassword(false);
    tracker.setAllowAutoUnlockWithCachedPasswords(false);
    tracker.unlockWithPassword(pass);
    if (!tracker.isUnlocked()) {
      throw new Error(`Couldn't unlock key ${key.fpr}`);
    }

    let out_final = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(out_final.address(), 0);

    let out_binary = new RNPLib.rnp_output_t();
    let rv;
    if (
      (rv = RNPLib.rnp_output_to_armor(
        out_final,
        out_binary.address(),
        "public key"
      ))
    ) {
      throw new Error("rnp_output_to_armor failed:" + rv);
    }

    if (
      (rv = RNPLib.rnp_key_export_revocation(
        key,
        out_binary,
        0,
        null,
        null,
        null
      ))
    ) {
      throw new Error("rnp_key_export_revocation failed: " + rv);
    }

    if ((rv = RNPLib.rnp_output_finish(out_binary))) {
      throw new Error("rnp_output_finish failed: " + rv);
    }

    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    let exitCode = RNPLib.rnp_output_memory_get_buf(
      out_final,
      result_buf.address(),
      result_len.address(),
      false
    );

    if (!exitCode) {
      let char_array = lazy.ctypes.cast(
        result_buf,
        lazy.ctypes.char.array(result_len.value).ptr
      ).contents;
      result = char_array.readString();
    }

    RNPLib.rnp_output_destroy(out_binary);
    RNPLib.rnp_output_destroy(out_final);
    tracker.release();
    return result;
  },

  enArmorString(input, type) {
    let arr = input.split("").map(e => e.charCodeAt());
    let input_array = lazy.ctypes.uint8_t.array()(arr);

    return this.enArmorCData(input_array, input_array.length, type);
  },

  enArmorCDataMessage(buf, len) {
    return this.enArmorCData(buf, len, "message");
  },

  enArmorCData(buf, len, type) {
    let input_array = lazy.ctypes.cast(buf, lazy.ctypes.uint8_t.array(len));

    let input_from_memory = new RNPLib.rnp_input_t();
    RNPLib.rnp_input_from_memory(
      input_from_memory.address(),
      input_array,
      len,
      false
    );

    let max_out = len * 2 + 150; // extra bytes for head/tail/hash lines

    let output_to_memory = new RNPLib.rnp_output_t();
    RNPLib.rnp_output_to_memory(output_to_memory.address(), max_out);

    if (RNPLib.rnp_enarmor(input_from_memory, output_to_memory, type)) {
      throw new Error("rnp_enarmor failed");
    }

    let result = "";
    let result_buf = new lazy.ctypes.uint8_t.ptr();
    let result_len = new lazy.ctypes.size_t();
    if (
      !RNPLib.rnp_output_memory_get_buf(
        output_to_memory,
        result_buf.address(),
        result_len.address(),
        false
      )
    ) {
      let char_array = lazy.ctypes.cast(
        result_buf,
        lazy.ctypes.char.array(result_len.value).ptr
      ).contents;

      result = char_array.readString();
    }

    RNPLib.rnp_input_destroy(input_from_memory);
    RNPLib.rnp_output_destroy(output_to_memory);

    return result;
  },

  // Will change the expiration date of all given keys to newExpiry.
  // fingerprintArray is an array, containing fingerprints, both
  // primary key fingerprints and subkey fingerprints are allowed.
  // The function assumes that all involved keys have already been
  // unlocked. We shouldn't rely on password callbacks for unlocking,
  // as it would be confusing if only some keys are changed.
  async changeExpirationDate(fingerprintArray, newExpiry) {
    for (let fingerprint of fingerprintArray) {
      let handle = this.getKeyHandleByKeyIdOrFingerprint(
        RNPLib.ffi,
        "0x" + fingerprint
      );

      if (handle.isNull()) {
        continue;
      }

      if (RNPLib.rnp_key_set_expiration(handle, newExpiry)) {
        throw new Error(`rnp_key_set_expiration failed for ${fingerprint}`);
      }
      RNPLib.rnp_key_handle_destroy(handle);
    }

    await this.saveKeyRings();
    return true;
  },

  /**
   * Get a minimal Autocrypt-compatible key for the given key handles.
   * If subkey is given, it must refer to an existing encryption subkey.
   * This is a wrapper around RNP function rnp_key_export_autocrypt.
   *
   * @param {rnp_key_handle_t} primHandle - The handle of a primary key.
   * @param {?rnp_key_handle_t} subHandle - The handle of an encryption subkey or null.
   * @param {string} uidString - The userID to include.
   * @returns {string} The encoded key, or the empty string on failure.
   */
  getAutocryptKeyB64ByHandle(primHandle, subHandle, userId) {
    if (primHandle.isNull()) {
      throw new Error("getAutocryptKeyB64ByHandle invalid parameter");
    }

    let output_to_memory = new RNPLib.rnp_output_t();
    if (RNPLib.rnp_output_to_memory(output_to_memory.address(), 0)) {
      throw new Error("rnp_output_to_memory failed");
    }

    let result = "";

    if (
      RNPLib.rnp_key_export_autocrypt(
        primHandle,
        subHandle,
        userId,
        output_to_memory,
        0
      )
    ) {
      console.debug("rnp_key_export_autocrypt failed");
    } else {
      let result_buf = new lazy.ctypes.uint8_t.ptr();
      let result_len = new lazy.ctypes.size_t();
      let rv = RNPLib.rnp_output_memory_get_buf(
        output_to_memory,
        result_buf.address(),
        result_len.address(),
        false
      );

      if (!rv) {
        // result_len is of type UInt64, I don't know of a better way
        // to convert it to an integer.
        let b_len = parseInt(result_len.value.toString());

        // type casting the pointer type to an array type allows us to
        // access the elements by index.
        let uint8_array = lazy.ctypes.cast(
          result_buf,
          lazy.ctypes.uint8_t.array(result_len.value).ptr
        ).contents;

        let str = "";
        for (let i = 0; i < b_len; i++) {
          str += String.fromCharCode(uint8_array[i]);
        }

        result = btoa(str);
      }
    }

    RNPLib.rnp_output_destroy(output_to_memory);

    return result;
  },

  /**
   * Get a minimal Autocrypt-compatible key for the given key ID.
   * If subKeyId is given, it must refer to an existing encryption subkey.
   * This is a wrapper around RNP function rnp_key_export_autocrypt.
   *
   * @param {string} primaryKeyId - The ID of a primary key.
   * @param {?string} subKeyId - The ID of an encryption subkey or null.
   * @param {string} uidString - The userID to include.
   * @returns {string} The encoded key, or the empty string on failure.
   */
  getAutocryptKeyB64(primaryKeyId, subKeyId, uidString) {
    let subHandle = null;

    if (subKeyId) {
      subHandle = this.getKeyHandleByKeyIdOrFingerprint(RNPLib.ffi, subKeyId);
      if (subHandle.isNull()) {
        // Although subKeyId is optional, if it's given, it must be valid.
        return "";
      }
    }

    let primHandle = this.getKeyHandleByKeyIdOrFingerprint(
      RNPLib.ffi,
      primaryKeyId
    );

    let result = this.getAutocryptKeyB64ByHandle(
      primHandle,
      subHandle,
      uidString
    );

    if (!primHandle.isNull()) {
      RNPLib.rnp_key_handle_destroy(primHandle);
    }
    if (subHandle) {
      RNPLib.rnp_key_handle_destroy(subHandle);
    }
    return result;
  },

  /**
   * Helper function to produce the string that will be shown to the
   * user, when the user is asked to unlock a key. If the key is a
   * subkey, it might help to user to identify the respective key by
   * also mentioning the key ID of the primary key, so both IDs are
   * shown when prompting to unlock a subkey.
   * Parameter nonDefaultFFI is required, if the prompt is related to
   * a key that isn't (yet) stored in the global storage, for example
   * a key that is being prepared for import or export in a temporary
   * ffi space.
   *
   * @param {rnp_key_handle_t} handle - produce a passphrase prompt
   *   string based on the properties of this key.
   * @param {rnp_ffi_t} ffi - the RNP FFI that relates the handle
   * @returns {String} - a string that asks the user to enter the
   *   passphrase for the given string parameter, including details
   *   that allow the user to identify the key.
   */
  async getPassphrasePrompt(handle, ffi) {
    let parentOfHandle = this.getPrimaryKeyHandleIfSub(ffi, handle);
    let useThisHandle = !parentOfHandle.isNull() ? parentOfHandle : handle;

    let keyObj = {};
    if (
      !this.getKeyInfoFromHandle(ffi, useThisHandle, keyObj, false, true, true)
    ) {
      return "";
    }

    let mainKeyId = keyObj.keyId;
    let subKeyId;
    if (!parentOfHandle.isNull()) {
      subKeyId = this.getKeyIDFromHandle(handle);
    }

    if (subKeyId) {
      return l10n.formatValue("passphrase-prompt2-sub", {
        subkey: subKeyId,
        key: mainKeyId,
        date: keyObj.created,
        username_and_email: keyObj.userId,
      });
    }
    return l10n.formatValue("passphrase-prompt2", {
      key: mainKeyId,
      date: keyObj.created,
      username_and_email: keyObj.userId,
    });
  },
};