domain 0.12.0

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

#![warn(missing_docs)]

// TODO:
// - add support for undo/abort.

use crate::base::iana::SecurityAlgorithm;
use crate::base::Name;
use crate::rdata::dnssec::Timestamp;
use serde::{Deserialize, Serialize};
use std::collections::{hash_map, HashMap, HashSet};
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::ops::Add;
use std::str::FromStr;
use std::string::{String, ToString};
use std::time::Duration;
use std::vec::Vec;

#[cfg(test)]
use mock_instant::global::{SystemTime, UNIX_EPOCH};

#[cfg(test)]
use mock_instant::SystemTimeError;

#[cfg(not(test))]
use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};

/// This type maintains a collection keys used to sign a zone.
///
/// The state of this type can be serialized and deserialized. The state
/// includes the state of any key rollovers going on.
#[derive(Clone, Deserialize, Serialize)]
pub struct KeySet {
    name: Name<Vec<u8>>,
    keys: HashMap<String, Key>,

    rollstates: HashMap<RollType, RollState>,
}

impl KeySet {
    /// Create a new key set for a give zone name.
    pub fn new(name: Name<Vec<u8>>) -> Self {
        Self {
            name,
            keys: HashMap::new(),
            rollstates: HashMap::new(),
        }
    }

    /// Add a KSK.
    pub fn add_key_ksk(
        &mut self,
        pubref: String,
        privref: Option<String>,
        algorithm: SecurityAlgorithm,
        key_tag: u16,
        creation_ts: UnixTime,
        available: Available,
    ) -> Result<(), Error> {
        if !self.unique_key_tag(key_tag) {
            return Err(Error::DuplicateKeyTag);
        }
        let keystate = KeyState {
            available: available.to_bool(),
            ..Default::default()
        };
        let key = Key::new(
            privref,
            KeyType::Ksk(keystate),
            algorithm,
            key_tag,
            creation_ts,
        );
        if let hash_map::Entry::Vacant(e) = self.keys.entry(pubref) {
            e.insert(key);
            Ok(())
        } else {
            Err(Error::KeyExists)
        }
    }

    /// Add a ZSK.
    pub fn add_key_zsk(
        &mut self,
        pubref: String,
        privref: Option<String>,
        algorithm: SecurityAlgorithm,
        key_tag: u16,
        creation_ts: UnixTime,
        available: Available,
    ) -> Result<(), Error> {
        if !self.unique_key_tag(key_tag) {
            return Err(Error::DuplicateKeyTag);
        }
        let keystate = KeyState {
            available: available.to_bool(),
            ..Default::default()
        };
        let key = Key::new(
            privref,
            KeyType::Zsk(keystate),
            algorithm,
            key_tag,
            creation_ts,
        );
        if let hash_map::Entry::Vacant(e) = self.keys.entry(pubref) {
            e.insert(key);
            Ok(())
        } else {
            Err(Error::KeyExists)
        }
    }

    /// Add a CSK.
    pub fn add_key_csk(
        &mut self,
        pubref: String,
        privref: Option<String>,
        algorithm: SecurityAlgorithm,
        key_tag: u16,
        creation_ts: UnixTime,
        available: Available,
    ) -> Result<(), Error> {
        if !self.unique_key_tag(key_tag) {
            return Err(Error::DuplicateKeyTag);
        }
        let keystate = KeyState {
            available: available.to_bool(),
            ..Default::default()
        };
        let key = Key::new(
            privref,
            KeyType::Csk(keystate.clone(), keystate),
            algorithm,
            key_tag,
            creation_ts,
        );
        if let hash_map::Entry::Vacant(e) = self.keys.entry(pubref) {
            e.insert(key);
            Ok(())
        } else {
            Err(Error::KeyExists)
        }
    }

    /// Add a public key.
    pub fn add_public_key(
        &mut self,
        pubref: String,
        algorithm: SecurityAlgorithm,
        key_tag: u16,
        creation_ts: UnixTime,
        available: bool,
    ) -> Result<(), Error> {
        if !self.unique_key_tag(key_tag) {
            return Err(Error::DuplicateKeyTag);
        }
        let keystate = KeyState {
            available,
            ..Default::default()
        };
        let key = Key::new(
            None,
            KeyType::Include(keystate),
            algorithm,
            key_tag,
            creation_ts,
        );
        if let hash_map::Entry::Vacant(e) = self.keys.entry(pubref) {
            e.insert(key);
            Ok(())
        } else {
            Err(Error::KeyExists)
        }
    }

    /// Set the decoupled flag of a key.
    pub fn set_decoupled(
        &mut self,
        pubref: &str,
        value: bool,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => key.decoupled = value,
        }
        Ok(())
    }

    /// Set the present flag of a key.
    ///
    /// For CSK set the present in both key states.
    pub fn set_present(
        &mut self,
        pubref: &str,
        value: bool,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                match &mut key.keytype {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Include(keystate) => {
                        keystate.present = value;
                    }
                    KeyType::Csk(ksk_keystate, zsk_keystate) => {
                        ksk_keystate.present = value;
                        zsk_keystate.present = value;
                    }
                };
                if value && key.timestamps.published.is_none() {
                    key.timestamps.published = Some(UnixTime::now());
                }
            }
        }
        Ok(())
    }

    /// Set the signer flag of a key.
    ///
    /// For CSK set the signer in both key states. Return an error if the
    /// key is Include.
    pub fn set_signer(
        &mut self,
        pubref: &str,
        value: bool,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                match &mut key.keytype {
                    KeyType::Ksk(keystate) | KeyType::Zsk(keystate) => {
                        keystate.signer = value;
                    }
                    KeyType::Csk(ksk_keystate, zsk_keystate) => {
                        ksk_keystate.signer = value;
                        zsk_keystate.signer = value;
                    }
                    KeyType::Include(_) => return Err(Error::WrongKeyType),
                };
            }
        }
        Ok(())
    }

    /// Set the at_parent flag of a key.
    ///
    /// For CSK set the signer the KSK state. Return an error if the key is
    /// Include or a ZSK.
    pub fn set_at_parent(
        &mut self,
        pubref: &str,
        value: bool,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                match &mut key.keytype {
                    KeyType::Ksk(keystate) => {
                        keystate.at_parent = value;
                    }
                    KeyType::Csk(ksk_keystate, _) => {
                        ksk_keystate.at_parent = value;
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => {
                        return Err(Error::WrongKeyType)
                    }
                };
            }
        }
        Ok(())
    }

    /// Make a key stale.
    ///
    /// Set old and clear present, signer and at_parent.
    pub fn set_stale(&mut self, pubref: &str) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                match &mut key.keytype {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Include(keystate) => {
                        keystate.old = true;
                        keystate.present = false;
                        keystate.signer = false;
                        keystate.at_parent = false;
                    }
                    KeyType::Csk(ksk_keystate, zsk_keystate) => {
                        ksk_keystate.old = true;
                        ksk_keystate.present = false;
                        ksk_keystate.signer = false;
                        ksk_keystate.at_parent = false;
                        zsk_keystate.old = true;
                        zsk_keystate.present = false;
                        zsk_keystate.signer = false;
                        zsk_keystate.at_parent = false;
                    }
                };
            }
        }
        Ok(())
    }

    /// Set the visible time of a key.
    pub fn set_visible(
        &mut self,
        pubref: &str,
        time: UnixTime,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                key.timestamps.visible = Some(time);
            }
        }
        Ok(())
    }

    /// Set the ds_visible time of a key.
    ///
    /// Note: there is no consistency check. The ds_visible time can be
    /// set even if at_parent is false.
    pub fn set_ds_visible(
        &mut self,
        pubref: &str,
        time: UnixTime,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                key.timestamps.ds_visible = Some(time);
            }
        }
        Ok(())
    }

    /// Set the rrsig_visible time of a key.
    ///
    /// Note: there is no consistency check. The rrsig_visible time can be
    /// set even if signer is false or the key is not signing the zone.
    pub fn set_rrsig_visible(
        &mut self,
        pubref: &str,
        time: UnixTime,
    ) -> Result<(), Error> {
        match self.keys.get_mut(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => {
                key.timestamps.rrsig_visible = Some(time);
            }
        }
        Ok(())
    }

    fn unique_key_tag(&self, key_tag: u16) -> bool {
        self.keys.iter().all(|(_, k)| k.key_tag != key_tag)
    }

    /// Delete a key.
    pub fn delete_key(&mut self, pubref: &str) -> Result<(), Error> {
        match self.keys.get(pubref) {
            None => return Err(Error::KeyNotFound),
            Some(key) => match &key.keytype {
                KeyType::Ksk(keystate)
                | KeyType::Zsk(keystate)
                | KeyType::Include(keystate) => {
                    if !keystate.stale() {
                        return Err(Error::KeyNotOld);
                    }
                }
                KeyType::Csk(ksk_keystate, zsk_keystate) => {
                    if !ksk_keystate.stale() {
                        return Err(Error::KeyNotOld);
                    }
                    if !zsk_keystate.stale() {
                        return Err(Error::KeyNotOld);
                    }
                }
            },
        }

        // The state of the key is checked, now remove the key.
        self.keys.remove(pubref).expect("key should exist");
        Ok(())
    }

    /// Return the zone name this key set belongs to.
    pub fn name(&self) -> &Name<Vec<u8>> {
        &self.name
    }

    /// Return the list of keys in the key set.
    pub fn keys(&self) -> &HashMap<String, Key> {
        &self.keys
    }

    /// Return the current active rolls and their states.
    pub fn rollstates(&self) -> &HashMap<RollType, RollState> {
        &self.rollstates
    }

    /// Start a key roll.
    ///
    /// The parameters are the type of key roll, a list of old keys that need
    /// to be rolled out and a list of new keys that on their way in.
    /// A list of actions is returned. The caller is responsible for
    /// performing the actions.
    pub fn start_roll(
        &mut self,
        rolltype: RollType,
        old: &[&str],
        new: &[&str],
    ) -> Result<Vec<Action>, Error> {
        let next_state = RollState::Propagation1;
        rolltype.rollfn()(RollOp::Start(old, new), self)?;

        self.rollstates.insert(rolltype, next_state.clone());

        Ok(rolltype.roll_actions_fn()(next_state))
    }

    /// A report that the propagation of the first change has completed.
    ///
    /// The user reports that the changes have propagated and provides the
    /// required ttl value. The actual changes to monitor were specified as
    /// an action in the previous state (start_roll). A list of actions is
    /// returned.
    pub fn propagation1_complete(
        &mut self,
        rolltype: RollType,
        ttl: u32,
    ) -> Result<Vec<Action>, Error> {
        // First check if the current roll state is Propagation1.
        let Some(RollState::Propagation1) = self.rollstates.get(&rolltype)
        else {
            return Err(Error::WrongStateForRollOperation);
        };
        let next_state = RollState::CacheExpire1(ttl);
        rolltype.rollfn()(RollOp::Propagation1, self)?;

        self.rollstates.insert(rolltype, next_state.clone());

        Ok(rolltype.roll_actions_fn()(next_state))
    }

    /// A report that any cached values should have expired by now.
    ///
    /// This method should be called at least ttl seconds after the call to
    /// propagation1_complete where ttl is the value of the ttl parameter
    /// passed to the propagation1_complete method. A list of actions is
    /// returned.
    pub fn cache_expired1(
        &mut self,
        rolltype: RollType,
    ) -> Result<Vec<Action>, Error> {
        // First check if the current roll state is CacheExpire1.
        let Some(RollState::CacheExpire1(ttl)) =
            self.rollstates.get(&rolltype)
        else {
            return Err(Error::WrongStateForRollOperation);
        };
        let next_state = RollState::Propagation2;
        rolltype.rollfn()(RollOp::CacheExpire1(*ttl), self)?;
        self.rollstates.insert(rolltype, next_state.clone());

        Ok(rolltype.roll_actions_fn()(next_state))
    }

    /// A report that the propagation of the second change has completed.
    ///
    /// The user reports that the changes have propagated and provides the
    /// required ttl value. The actual changes to monitor were specified as on
    /// action in the previous state (cache_expired1). A list of actions is
    /// returned.
    pub fn propagation2_complete(
        &mut self,
        rolltype: RollType,
        ttl: u32,
    ) -> Result<Vec<Action>, Error> {
        // First check if the current roll state is Propagation2.
        let Some(RollState::Propagation2) = self.rollstates.get(&rolltype)
        else {
            return Err(Error::WrongStateForRollOperation);
        };
        let next_state = RollState::CacheExpire2(ttl);
        rolltype.rollfn()(RollOp::Propagation2, self)?;
        self.rollstates.insert(rolltype, next_state.clone());
        Ok(rolltype.roll_actions_fn()(next_state))
    }

    /// A report that any cached values should have expired by now.
    ///
    /// This method should be called at least ttl seconds after the call to
    /// propagation2_complete where ttl is the value of the ttl parameter
    /// passed to the propagation2_complete method. A list of actions is
    /// returned.
    pub fn cache_expired2(
        &mut self,
        rolltype: RollType,
    ) -> Result<Vec<Action>, Error> {
        // First check if the current roll state is CacheExpire2.
        let Some(RollState::CacheExpire2(ttl)) =
            self.rollstates.get(&rolltype)
        else {
            return Err(Error::WrongStateForRollOperation);
        };
        let next_state = RollState::Done;
        rolltype.rollfn()(RollOp::CacheExpire2(*ttl), self)?;
        self.rollstates.insert(rolltype, next_state.clone());

        Ok(rolltype.roll_actions_fn()(next_state))
    }

    /// The user reports that all actions have been performed and that the
    /// key roll is now complete.
    pub fn roll_done(
        &mut self,
        rolltype: RollType,
    ) -> Result<Vec<Action>, Error> {
        // First check if the current roll state is Done.
        let Some(RollState::Done) = self.rollstates.get(&rolltype) else {
            return Err(Error::WrongStateForRollOperation);
        };
        rolltype.rollfn()(RollOp::Done, self)?;
        self.rollstates.remove(&rolltype);
        Ok(Vec::new())
    }

    /// Return the actions that need to be performed for the current
    /// roll state.
    pub fn actions(&self, rolltype: RollType) -> Vec<Action> {
        if let Some(rollstate) = self.rollstates.get(&rolltype) {
            rolltype.roll_actions_fn()(rollstate.clone())
        } else {
            Vec::new()
        }
    }

    fn update_ksk(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        let mut algs_old = HashSet::new();
        for k in old {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Ksk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };

            // Set old for any key we find.
            keystate.old = true;

            // Add algorithm
            algs_old.insert(key.algorithm);
        }
        let now = UnixTime::now();
        let mut algs_new = HashSet::new();
        for k in new {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Ksk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };
            if *keystate
                != (KeyState {
                    available: true,
                    old: false,
                    signer: false,
                    present: false,
                    at_parent: false,
                })
            {
                return Err(Error::WrongKeyState);
            }

            // Move key state to Incoming.
            keystate.present = true;
            keystate.signer = true;
            key.timestamps.published = Some(now.clone());

            // Add algorithm
            algs_new.insert(key.algorithm);
        }

        // Make sure the sets of algorithms are the same.
        if algs_old != algs_new {
            return Err(Error::AlgorithmSetsMismatch);
        }

        // Make sure we have at least one key in incoming state.
        if !keys.iter().any(|(_, k)| {
            if let KeyType::Ksk(keystate) = &k.keytype {
                !keystate.old && keystate.present
            } else {
                false
            }
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }

    fn update_ksk_double_ds(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        let mut algs_old = HashSet::new();
        for k in old {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Ksk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };

            // Set old for any key we find.
            keystate.old = true;

            // Add algorithm
            algs_old.insert(key.algorithm);
        }
        let mut algs_new = HashSet::new();
        for k in new {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Ksk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };
            if *keystate
                != (KeyState {
                    available: true,
                    old: false,
                    signer: false,
                    present: false,
                    at_parent: false,
                })
            {
                return Err(Error::WrongKeyState);
            }

            keystate.at_parent = true;

            // Add algorithm
            algs_new.insert(key.algorithm);
        }

        // Make sure the sets of algorithms are the same.
        if algs_old != algs_new {
            return Err(Error::AlgorithmSetsMismatch);
        }

        // Make sure we have at least one key in the right state.
        if !keys.iter().any(|(_, k)| {
            if let KeyType::Ksk(keystate) = &k.keytype {
                !keystate.old && keystate.at_parent
            } else {
                false
            }
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }

    fn update_zsk(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        let mut algs_old = HashSet::new();
        for k in old {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Zsk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };

            // Set old for any key we find.
            keystate.old = true;

            // Add algorithm
            algs_old.insert(key.algorithm);
        }
        let now = UnixTime::now();
        let mut algs_new = HashSet::new();
        for k in new {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Zsk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };
            if *keystate
                != (KeyState {
                    available: true,
                    old: false,
                    signer: false,
                    present: false,
                    at_parent: false,
                })
            {
                return Err(Error::WrongKeyState);
            }

            // Move key state to Incoming.
            keystate.present = true;
            key.timestamps.published = Some(now.clone());

            // Add algorithm
            algs_new.insert(key.algorithm);
        }

        // Make sure the sets of algorithms are the same.
        if algs_old != algs_new {
            return Err(Error::AlgorithmSetsMismatch);
        }

        // Make sure we have at least one key in incoming state.
        if !keys.iter().any(|(_, k)| {
            if let KeyType::Zsk(keystate) = &k.keytype {
                !keystate.old || keystate.present
            } else {
                false
            }
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }

    fn update_zsk_double_signature(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        let mut algs_old = HashSet::new();
        for k in old {
            let Some(ref mut key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Zsk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };

            // Set old for any key we find.
            keystate.old = true;

            // Add algorithm
            algs_old.insert(key.algorithm);
        }
        let now = UnixTime::now();
        let mut algs_new = HashSet::new();
        for k in new {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            let KeyType::Zsk(ref mut keystate) = key.keytype else {
                return Err(Error::WrongKeyType);
            };
            if *keystate
                != (KeyState {
                    available: true,
                    old: false,
                    signer: false,
                    present: false,
                    at_parent: false,
                })
            {
                return Err(Error::WrongKeyState);
            }

            // Move key state to Incoming.
            keystate.present = true;
            keystate.signer = true;
            key.timestamps.published = Some(now.clone());

            // Add algorithm
            algs_new.insert(key.algorithm);
        }

        // Make sure the sets of algorithms are the same.
        if algs_old != algs_new {
            return Err(Error::AlgorithmSetsMismatch);
        }

        // Make sure we have at least one key in incoming state.
        if !keys.iter().any(|(_, k)| {
            if let KeyType::Zsk(keystate) = &k.keytype {
                !keystate.old || keystate.present
            } else {
                false
            }
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }

    fn update_csk(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        let mut algs_old = HashSet::new();
        for k in old {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            match key.keytype {
                KeyType::Ksk(ref mut keystate)
                | KeyType::Zsk(ref mut keystate) => {
                    keystate.old = true;
                }
                KeyType::Csk(ref mut ksk_keystate, ref mut zsk_keystate) => {
                    ksk_keystate.old = true;
                    zsk_keystate.old = true;
                }
                KeyType::Include(_) => {
                    return Err(Error::WrongKeyType);
                }
            }

            // Add algorithm
            algs_old.insert(key.algorithm);
        }
        let now = UnixTime::now();
        let mut algs_new = HashSet::new();
        for k in new {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            match key.keytype {
                KeyType::Ksk(ref mut keystate) => {
                    if *keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Active.
                    keystate.present = true;
                    keystate.signer = true;
                    key.timestamps.published = Some(now.clone());
                }
                KeyType::Zsk(ref mut keystate) => {
                    if *keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Incoming.
                    keystate.present = true;
                    key.timestamps.published = Some(now.clone());
                }
                KeyType::Csk(ref mut ksk_keystate, ref mut zsk_keystate) => {
                    if *ksk_keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Active.
                    ksk_keystate.present = true;
                    ksk_keystate.signer = true;

                    if *zsk_keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Incoming.
                    zsk_keystate.present = true;

                    key.timestamps.published = Some(now.clone());
                }
                _ => {
                    return Err(Error::WrongKeyType);
                }
            }

            // Add algorithm
            algs_new.insert(key.algorithm);
        }

        // Make sure the sets of algorithms are the same.
        if algs_old != algs_new {
            return Err(Error::AlgorithmSetsMismatch);
        }

        // Make sure we have at least one KSK key in incoming state.
        if !keys.iter().any(|(_, k)| match &k.keytype {
            KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                !keystate.old && keystate.present
            }
            _ => false,
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        // Make sure we have at least one ZSK key in incoming state.
        if !keys.iter().any(|(_, k)| match &k.keytype {
            KeyType::Zsk(keystate) | KeyType::Csk(_, keystate) => {
                !keystate.old && keystate.present
            }
            _ => false,
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }

    fn update_algorithm(
        &mut self,
        mode: Mode,
        old: &[&str],
        new: &[&str],
    ) -> Result<(), Error> {
        let mut tmpkeys = self.keys.clone();
        let keys: &mut HashMap<String, Key> = match mode {
            Mode::DryRun => &mut tmpkeys,
            Mode::ForReal => &mut self.keys,
        };
        for k in old {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            match key.keytype {
                KeyType::Ksk(ref mut keystate)
                | KeyType::Zsk(ref mut keystate) => {
                    keystate.old = true;
                }
                KeyType::Csk(ref mut ksk_keystate, ref mut zsk_keystate) => {
                    ksk_keystate.old = true;
                    zsk_keystate.old = true;
                }
                KeyType::Include(_) => {
                    return Err(Error::WrongKeyType);
                }
            }
        }
        let now = UnixTime::now();
        for k in new {
            let Some(key) = keys.get_mut(&(k.to_string())) else {
                return Err(Error::KeyNotFound);
            };
            match key.keytype {
                KeyType::Ksk(ref mut keystate)
                | KeyType::Zsk(ref mut keystate) => {
                    if *keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Active.
                    keystate.present = true;
                    keystate.signer = true;
                    key.timestamps.published = Some(now.clone());
                }
                KeyType::Csk(ref mut ksk_keystate, ref mut zsk_keystate) => {
                    if *ksk_keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Active.
                    ksk_keystate.present = true;
                    ksk_keystate.signer = true;

                    if *zsk_keystate
                        != (KeyState {
                            available: true,
                            old: false,
                            signer: false,
                            present: false,
                            at_parent: false,
                        })
                    {
                        return Err(Error::WrongKeyState);
                    }

                    // Move key state to Active.
                    zsk_keystate.present = true;
                    zsk_keystate.signer = true;

                    key.timestamps.published = Some(now.clone());
                }
                _ => {
                    return Err(Error::WrongKeyType);
                }
            }
        }

        // Make sure we have at least one KSK key in incoming state.
        if !keys.iter().any(|(_, k)| match &k.keytype {
            KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                !keystate.old && keystate.present
            }
            _ => false,
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        // Make sure we have at least one ZSK key in incoming state.
        if !keys.iter().any(|(_, k)| match &k.keytype {
            KeyType::Zsk(keystate) | KeyType::Csk(_, keystate) => {
                !keystate.old && keystate.present
            }
            _ => false,
        }) {
            return Err(Error::NoSuitableKeyPresent);
        }
        Ok(())
    }
}

/// The state of a single key.
///
/// The state includes a way to refer to the public key and optionally a
/// way to refer to the private key. The state includes the type of the
/// key (which in itself includes the key state) and a list of timestamps
/// that mark the various stages in the life of a key.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Key {
    privref: Option<String>,

    decoupled: bool,

    keytype: KeyType,
    algorithm: SecurityAlgorithm,
    key_tag: u16,
    timestamps: KeyTimestamps,
}

impl Key {
    /// Return the 'reference' to the private key (if present).
    pub fn privref(&self) -> Option<&str> {
        self.privref.as_deref()
    }

    /// Return whether the key is decoupled from the underlying key storage
    /// or not.
    pub fn decoupled(&self) -> bool {
        self.decoupled
    }

    /// Return the key type (which includes the state of the key).
    pub fn keytype(&self) -> KeyType {
        self.keytype.clone()
    }

    /// Return the public key algorithm.
    pub fn algorithm(&self) -> SecurityAlgorithm {
        self.algorithm
    }

    /// Return the key tag.
    pub fn key_tag(&self) -> u16 {
        self.key_tag
    }

    /// Return the timestamps.
    pub fn timestamps(&self) -> &KeyTimestamps {
        &self.timestamps
    }

    fn new(
        privref: Option<String>,
        keytype: KeyType,
        algorithm: SecurityAlgorithm,
        key_tag: u16,
        creation_ts: UnixTime,
    ) -> Self {
        let timestamps = KeyTimestamps {
            creation: Some(creation_ts),
            ..Default::default()
        };
        Self {
            privref,
            decoupled: false,
            keytype,
            algorithm,
            key_tag,
            timestamps,
        }
    }
}

/// The different types of keys.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum KeyType {
    /// Key signing key (KSK).
    Ksk(KeyState),

    /// Zone signing key (ZSK).
    Zsk(KeyState),

    /// Combined signing key (CSK).
    ///
    /// Note that this key has two states, one for its KSK role and one for
    /// the ZSK role.
    Csk(KeyState, KeyState),

    /// Included key that belongs to another signer in a nulti-signer setup.
    Include(KeyState),
}

/// State of a key.
///
/// The state is expressed as five booleans.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct KeyState {
    /// The key is available as an incoming key during key rolls.
    available: bool,
    /// Set if the key is on its way out.
    old: bool,
    /// Set if the key either signes the DNSKEY RRset or the rest of the zone.
    signer: bool,
    /// Whether the key is present in the DNSKEY RRset.
    present: bool,
    /// If the key has to have a DS record at the parent.
    at_parent: bool,
}

impl KeyState {
    /// Return whether the key is old, i.e. on its way out.
    pub fn old(&self) -> bool {
        self.old
    }

    /// Return whether the key is a signer, i.e. signs the DNSKEY RRset or
    /// the zone.
    pub fn signer(&self) -> bool {
        self.signer
    }

    /// Return whether the key is present in the DNSKEY RRset.
    pub fn present(&self) -> bool {
        self.present
    }

    /// Return whether the key needs to have a DS record at the parent.
    pub fn at_parent(&self) -> bool {
        self.at_parent
    }

    /// Return whether this key is no long in use.
    pub fn stale(&self) -> bool {
        self.old && !self.signer && !self.present && !self.at_parent
    }
}

impl Display for KeyState {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        let mut first = true;
        if self.old {
            write!(f, "Old")?;
            first = false;
        }
        if self.signer {
            write!(f, "{}Signer", if first { "" } else { ", " })?;
            first = false;
        }
        if self.present {
            write!(f, "{}Present", if first { "" } else { ", " })?;
            first = false;
        }
        if self.at_parent {
            write!(f, "{}At Parent", if first { "" } else { ", " })?;
        }
        match (self.old, self.signer, self.present) {
            (false, false, false) => write!(f, "(Future)")?,
            (false, false, true) => write!(f, " (Incoming)")?,
            (false, true, true) => write!(f, " (Active)")?,
            (true, true, true) => write!(f, " (Leaving)")?,
            (true, false, true) => write!(f, " (Retired)")?,
            (true, false, false) => write!(f, " (Stale)")?,
            (_, _, _) => (),
        }
        Ok(())
    }
}

/// This type contains the various timestamps in the life of a key.
///
/// All timestamps are optional. The following timestamps are supported:
/// * when the key was created,
/// * when the key was first published in the DNSKEY RRset,
/// * when the DNSKEY RRset with the key was first visible,
/// * when the DS record for the key was first visible,
/// * when RRSIG records signed by the key were first visible,
/// * when the key was withdrawn from the DNSKEY RRset.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct KeyTimestamps {
    creation: Option<UnixTime>,
    published: Option<UnixTime>,
    visible: Option<UnixTime>,
    ds_visible: Option<UnixTime>,
    rrsig_visible: Option<UnixTime>,
    withdrawn: Option<UnixTime>,
}

impl KeyTimestamps {
    /// Return the creation time of a key.
    pub fn creation(&self) -> Option<UnixTime> {
        self.creation.clone()
    }

    /// Return the time when a key was first published in the DNSKEY RRset.
    pub fn published(&self) -> Option<UnixTime> {
        self.published.clone()
    }

    /// Return the time when DNSKEY RRset with a key was first visible.
    pub fn visible(&self) -> Option<UnixTime> {
        self.visible.clone()
    }

    /// Return the time when a DS record for a key was first visible.
    pub fn ds_visible(&self) -> Option<UnixTime> {
        self.ds_visible.clone()
    }

    /// Return the time when an RRSIG record signed by the key was first
    /// visible.
    pub fn rrsig_visible(&self) -> Option<UnixTime> {
        self.rrsig_visible.clone()
    }

    /// Return the time when the key was removed from the DNSKEY RRset.
    pub fn withdrawn(&self) -> Option<UnixTime> {
        self.withdrawn.clone()
    }
}

/// A type that contains Unix time.
///
/// Unix time is the number of seconds since midnight January first
/// 1970 GMT.
#[derive(
    Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize,
)]
pub struct UnixTime(Duration);

impl UnixTime {
    /// Create a value for the current time.
    pub fn now() -> Self {
        let dur = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("System time is expected to be after UNIX_EPOCH");
        UnixTime(dur)
    }

    /// Return how much time has elapsed since the current timestamp.
    pub fn elapsed(&self) -> Duration {
        let dur = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("System time is expected to be after UNIX_EPOCH");
        if dur < self.0 {
            // Clamp elapsed to zero.
            Duration::ZERO
        } else {
            dur - self.0
        }
    }
}

impl TryFrom<SystemTime> for UnixTime {
    type Error = SystemTimeError;
    fn try_from(t: SystemTime) -> Result<Self, SystemTimeError> {
        Ok(Self(t.duration_since(UNIX_EPOCH)?))
    }
}

impl From<Timestamp> for UnixTime {
    fn from(t: Timestamp) -> Self {
        Self(Duration::from_secs(t.into_int() as u64))
    }
}

impl From<UnixTime> for Duration {
    fn from(t: UnixTime) -> Self {
        t.0
    }
}

impl Add<Duration> for UnixTime {
    type Output = UnixTime;
    fn add(self, d: Duration) -> Self {
        Self(self.0 + d)
    }
}

impl Display for UnixTime {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        // 'impl Display for jiff::Timestamp' formats per RFC3339.
        //
        // '{:.0}' explicitly disables sub-second precision.
        write!(f, "{:.0}", jiff::Timestamp::UNIX_EPOCH + self.0)
    }
}

/// States of a key roll.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum RollState {
    /// Waiting for the first change (actions that result in DNSKEY, CDS, DS,
    /// RRSIG, etc. updates) to propagate.
    Propagation1,
    /// Waiting for old data to expire from caches.
    ///
    /// This is data that prevents the first change from getting loaded in the
    /// cache. The TTL of the old data is a parameter.
    CacheExpire1(u32),
    /// Waiting for the second change (actions that result in DNSKEY, CDS, DS,
    /// RRSIG, etc. updates) to propagate.
    Propagation2,
    /// Waiting for old data to expire from caches.
    ///
    /// This is data that prevents the second change from getting loaded in the
    /// cache. The TTL of the old data is a parameter.
    CacheExpire2(u32),

    /// The key roll is done.
    ///
    /// This state gives the user the chance to execute the remaining actions.
    Done,
}

impl FromStr for RollType {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "ksk-roll" {
            Ok(RollType::KskRoll)
        } else if s == "ksk-double-ds-roll" {
            Ok(RollType::KskDoubleDsRoll)
        } else if s == "zsk-roll" {
            Ok(RollType::ZskRoll)
        } else if s == "zsk-double-signature-roll" {
            Ok(RollType::ZskDoubleSignatureRoll)
        } else if s == "csk-roll" {
            Ok(RollType::CskRoll)
        } else if s == "algorithm-roll" {
            Ok(RollType::AlgorithmRoll)
        } else {
            Err(Error::UnknownRollType)
        }
    }
}

/// When adding a key, this specifies whether the key is available to
/// key rolls or not.
pub enum Available {
    /// Key is available to key rolls.
    Available,
    /// Key is not available to key rolls.
    NotAvailable,
}

impl Available {
    fn to_bool(&self) -> bool {
        match self {
            Available::Available => true,
            Available::NotAvailable => false,
        }
    }
}

enum Mode {
    DryRun,
    ForReal,
}

/// Actions that have to be performed by the user.
///
/// Note that if a list contains multiple report actions then the user
/// has to wait until all action have completed and has to report the
/// highest TTL value among the values to report.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Action {
    /// Generate a new version of the zone with an updated DNSKEY RRset.
    UpdateDnskeyRrset,

    /// Generate a new version of the zone with CDS and CDNSKEY RRsets.
    CreateCdsRrset,

    /// Generate a new version of the zone without CDS and CDNSKEY RRsets.
    RemoveCdsRrset,

    /// Update the DS RRset at the parent.
    UpdateDsRrset,

    /// Generate a new version of the zone with updated RRSIG records.
    UpdateRrsig,

    /// Report whether an updated DNSKEY RRset has propagated to all
    /// secondaries that serve the zone. Also report the TTL of the
    /// DNSKEY RRset.
    ReportDnskeyPropagated,

    /// Wait for the DNSKEY RRset to propagate before moving to the next
    /// state. Waiting is not needed for the correctness of the key roll
    /// algorithm. However without waiting, the state of keyset may not reflect
    /// reality.
    WaitDnskeyPropagated,

    /// Report whether updated DS records have propagated to all
    /// secondaries that serve the parent zone. Also report the TTL of
    /// the DS records.
    ReportDsPropagated,

    /// Wait for the update FS records to have propagated to all
    /// secondaries that serve the parent zone. Waiting is necessary to
    /// avoid removing the CDS and CDNSKEY records too soon.
    WaitDsPropagated,

    /// Report whether updated RRSIG records have propagated to all
    /// secondaries that the serve the zone. For propagation it is
    /// sufficient to track the signatures on the SOA record. Report the
    /// highest TTL among all signatures.
    ReportRrsigPropagated,

    /// Wait for updated RRSIG records to propagate before moving to the next
    /// state. Waiting is not needed for the correctness of the key roll
    /// algorithm. However without waiting, the state of keyset may not reflect
    /// reality.
    WaitRrsigPropagated,
}

/// The type of key roll to perform.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum RollType {
    /// A KSK roll. This implements the Double-Signature KSK Roll as described
    /// in Section 4.1.2 of RFC 6781.
    KskRoll,

    /// An alternative KSK roll. This implements the Double-DS KSK Roll as
    /// described in Section 4.1.2 of RFC 6781.
    KskDoubleDsRoll,

    /// A ZSK roll. This implements the Pre-Publish ZSK Roll as described
    /// in Section 4.1.1.1. of RFC 6781.
    ZskRoll,

    /// An alternative ZSK roll. This implements the Double-Signature ZSK
    /// Roll as described in Section 4.1.1.2. of RFC 6781.
    ZskDoubleSignatureRoll,

    /// A CSK roll. This implements neither of the two algorithms in
    /// Section 4.1.3. of RFC 6781.
    CskRoll,

    /// An algorithm roll. This implements the 'liberal approach' as
    /// described in Section 4.1.4 of RFC 6781.
    AlgorithmRoll,
}

impl RollType {
    fn rollfn(&self) -> fn(RollOp<'_>, &mut KeySet) -> Result<(), Error> {
        match self {
            RollType::KskRoll => ksk_roll,
            RollType::KskDoubleDsRoll => ksk_double_ds_roll,
            RollType::ZskRoll => zsk_roll,
            RollType::ZskDoubleSignatureRoll => zsk_double_signature_roll,
            RollType::CskRoll => csk_roll,
            RollType::AlgorithmRoll => algorithm_roll,
        }
    }
    fn roll_actions_fn(&self) -> fn(RollState) -> Vec<Action> {
        match self {
            RollType::KskRoll => ksk_roll_actions,
            RollType::KskDoubleDsRoll => ksk_double_ds_roll_actions,
            RollType::ZskRoll => zsk_roll_actions,
            RollType::ZskDoubleSignatureRoll => {
                zsk_double_signature_roll_actions
            }
            RollType::CskRoll => csk_roll_actions,
            RollType::AlgorithmRoll => algorithm_roll_actions,
        }
    }
}

#[derive(Debug)]
enum RollOp<'a> {
    Start(&'a [&'a str], &'a [&'a str]),
    Propagation1,
    CacheExpire1(u32),
    Propagation2,
    CacheExpire2(u32),
    Done,
}

/// The various errors that can be returned.
#[derive(Debug)]
pub enum Error {
    /// The listed key already exists in the key set.
    KeyExists,

    /// The listed key cannot be found in the key set.
    KeyNotFound,

    /// The key cannot be deleted because it is not old.
    KeyNotOld,

    /// Attempt to add key with a key tag that already exists in the KeySet.
    DuplicateKeyTag,

    /// The key has to wrong type.
    WrongKeyType,

    /// The key is in the wrong state.
    WrongKeyState,

    /// The operation would cause no suitable key to be present.
    NoSuitableKeyPresent,

    /// The key set is in the wrong state for the requested key roll operation.
    WrongStateForRollOperation,

    /// A conflicting key roll is currently in progress.
    ConflictingRollInProgress,

    /// Algorithm set mismatch in non-algorithm key-roll.
    AlgorithmSetsMismatch,

    /// The operation is too early. The Duration parameter specifies how long
    /// to wait.
    Wait(Duration),

    /// Unable to parse a string as a roll type.
    UnknownRollType,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::KeyExists => write!(f, "key already exists"),
            Error::KeyNotFound => write!(f, "key not found"),
            Error::KeyNotOld => write!(f, "key is still in use, not old"),
            Error::DuplicateKeyTag => write!(f, "Key tag already present"),
            Error::WrongKeyType => write!(f, "key has the wrong type"),
            Error::WrongKeyState => write!(f, "key is in the wrong state"),
            Error::NoSuitableKeyPresent => {
                write!(f, "no suitable key present after key roll")
            }
            Error::WrongStateForRollOperation => {
                write!(f, "wrong roll state for operation")
            }
            Error::ConflictingRollInProgress => {
                write!(f, "conflicting roll is in progress")
            }
            Error::AlgorithmSetsMismatch => {
                write!(f, "algorithm set mismatch for non-algorithm key roll")
            }
            Error::Wait(d) => write!(f, "wait for duration {d:?}"),
            Error::UnknownRollType => {
                write!(f, "unable to parse string as roll type")
            }
        }
    }
}

fn ksk_roll(rollop: RollOp<'_>, ks: &mut KeySet) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current KSK-roll state is idle. We need to
            // check all conflicting key rolls as well. The way we check is
            // to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().find(|k| {
                **k != RollType::ZskRoll
                    && **k != RollType::ZskDoubleSignatureRoll
            }) {
                if *rolltype == RollType::KskRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_ksk(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_ksk(Mode::ForReal, old, new)
                .expect("Should have been checked by DryRun");
        }
        RollOp::Propagation1 => {
            // Set the visible time of new KSKs to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                k.timestamps.visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.stale() {
                    continue;
                }

                let visible = k
                    .timestamps
                    .visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            for k in &mut ks.keys.values_mut() {
                if let KeyType::Ksk(ref mut keystate) = k.keytype {
                    if keystate.old && keystate.present {
                        keystate.at_parent = false;
                    }

                    if !keystate.old && keystate.present {
                        keystate.at_parent = true;
                    }
                }
            }
        }
        RollOp::Propagation2 => {
            // Set the published time of new DS records to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.at_parent {
                    continue;
                }

                k.timestamps.ds_visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.stale() {
                    continue;
                }

                let ds_visible = k
                    .timestamps
                    .ds_visible
                    .as_ref()
                    .expect("Should have been set in Propagation2");
                let elapsed = ds_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move old keys out
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref mut keystate) = k.keytype else {
                    continue;
                };
                if keystate.old && keystate.present {
                    keystate.signer = false;
                    keystate.present = false;
                    k.timestamps.withdrawn = Some(UnixTime::now());
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn ksk_double_ds_roll(
    rollop: RollOp<'_>,
    ks: &mut KeySet,
) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current KSK-roll state is idle. We need to
            // check all conflicting key rolls as well. The way we check is
            // to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().find(|k| {
                **k != RollType::ZskRoll
                    && **k != RollType::ZskDoubleSignatureRoll
            }) {
                if *rolltype == RollType::KskDoubleDsRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_ksk_double_ds(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_ksk_double_ds(Mode::ForReal, old, new)
                .expect("Should have been checked by DryRun");
        }
        RollOp::Propagation1 => {
            // Set the ds_visible time of new KSKs to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.at_parent {
                    continue;
                }

                k.timestamps.ds_visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.at_parent {
                    continue;
                }

                let ds_visible = k
                    .timestamps
                    .ds_visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = ds_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Old keys are no longer present and signing, new keys will
            // be present and signing. Set published.
            let now = UnixTime::now();
            for k in &mut ks.keys.values_mut() {
                if let KeyType::Ksk(ref mut keystate) = k.keytype {
                    if keystate.old && keystate.present {
                        keystate.present = false;
                        keystate.signer = false;
                    }

                    if !keystate.old && keystate.at_parent {
                        keystate.present = true;
                        keystate.signer = true;
                        k.timestamps.published = Some(now.clone());
                    }
                }
            }
        }
        RollOp::Propagation2 => {
            // Set the visible time of new keys to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                k.timestamps.visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Ksk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                let visible = k
                    .timestamps
                    .ds_visible
                    .as_ref()
                    .expect("Should have been set in Propagation2");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move old DS records out
            for k in ks.keys.values_mut() {
                let KeyType::Ksk(ref mut keystate) = k.keytype else {
                    continue;
                };
                if keystate.old && keystate.at_parent {
                    keystate.at_parent = false;
                    k.timestamps.withdrawn = Some(UnixTime::now());
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn ksk_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::ReportDnskeyPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::CreateCdsRrset);
            actions.push(Action::UpdateDsRrset);
            actions.push(Action::ReportDsPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => {
            actions.push(Action::RemoveCdsRrset);
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::WaitDnskeyPropagated);
        }
    }
    actions
}

fn ksk_double_ds_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::CreateCdsRrset);
            actions.push(Action::UpdateDsRrset);
            actions.push(Action::ReportDsPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::RemoveCdsRrset);
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::ReportDnskeyPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => {
            actions.push(Action::CreateCdsRrset);
            actions.push(Action::UpdateDsRrset);
            actions.push(Action::WaitDsPropagated);
        } // Missing: RemoveCdsRrset, This would require one more state,
    }
    actions
}

fn zsk_roll(rollop: RollOp<'_>, ks: &mut KeySet) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current ZSK-roll state is idle. We need
            // to check all conflicting key rolls as well. The way we check
            // is to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().find(|k| {
                **k != RollType::KskRoll && **k != RollType::KskDoubleDsRoll
            }) {
                if *rolltype == RollType::ZskRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_zsk(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_zsk(Mode::ForReal, old, new)
                .expect("Should have been checked with DryRun");
        }
        RollOp::Propagation1 => {
            // Set the visible time of new ZSKs to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                k.timestamps.visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                let visible = k
                    .timestamps
                    .visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move the Incoming keys to Active. Move the Leaving keys to
            // Retired.
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref mut keystate) = k.keytype else {
                    continue;
                };
                if !keystate.old && keystate.present {
                    keystate.signer = true;
                }
                if keystate.old {
                    keystate.signer = false;
                }
            }
        }
        RollOp::Propagation2 => {
            // Set the published time of new RRSIG records to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                k.timestamps.rrsig_visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                let rrsig_visible = k
                    .timestamps
                    .rrsig_visible
                    .as_ref()
                    .expect("Should have been set in Propagation2");
                let elapsed = rrsig_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move old keys out
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref mut keystate) = k.keytype else {
                    continue;
                };
                if keystate.old && !keystate.signer {
                    keystate.present = false;
                    k.timestamps.withdrawn = Some(UnixTime::now());
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn zsk_double_signature_roll(
    rollop: RollOp<'_>,
    ks: &mut KeySet,
) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current ZSK-roll state is idle. We need
            // to check all conflicting key rolls as well. The way we check
            // is to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().find(|k| {
                **k != RollType::KskRoll && **k != RollType::KskDoubleDsRoll
            }) {
                if *rolltype == RollType::ZskDoubleSignatureRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_zsk_double_signature(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_zsk_double_signature(Mode::ForReal, old, new)
                .expect("Should have been checked with DryRun");
        }
        RollOp::Propagation1 => {
            // Set the visible time of new ZSKs to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                k.timestamps.visible = Some(now.clone());
                k.timestamps.rrsig_visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                let visible = k
                    .timestamps
                    .visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move the Leaving keys to Retired.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                let KeyType::Zsk(ref mut keystate) = k.keytype else {
                    continue;
                };
                if keystate.old {
                    keystate.present = false;
                    keystate.signer = false;
                    k.timestamps.withdrawn = Some(now.clone());
                }
            }
        }
        RollOp::Propagation2 => {
            // No need to do anything here.
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let KeyType::Zsk(ref keystate) = k.keytype else {
                    continue;
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                // Logically we should be waiting for the signatures
                // created with the old ZSK to expire from caches. We
                // can't do that because we don't keep track of when a key
                // stops signing (maybe we should?). However, in this case,
                // old cached signatures don't do any harm. So we can just
                // continue. We get if the signatures created using the
                // new key are in the cache, but that should be a no-op.
                let rrsig_visible = k
                    .timestamps
                    .rrsig_visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = rrsig_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn zsk_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::ReportDnskeyPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::UpdateRrsig);
            actions.push(Action::ReportRrsigPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::WaitDnskeyPropagated);
        }
    }
    actions
}

fn zsk_double_signature_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::UpdateRrsig);
            actions.push(Action::ReportDnskeyPropagated);
            actions.push(Action::ReportRrsigPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::UpdateRrsig);
            actions.push(Action::ReportDnskeyPropagated);
            actions.push(Action::ReportRrsigPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => (),
    }
    actions
}

fn csk_roll(rollop: RollOp<'_>, ks: &mut KeySet) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current CSK-roll state is idle. We need
            // to check all conflicting key rolls as well. The way we check
            // is to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().next() {
                if *rolltype == RollType::CskRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_csk(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_csk(Mode::ForReal, old, new)
                .expect("Should have been checked with DryRun");
        }
        RollOp::Propagation1 => {
            // Set the visible time of new KSKs, ZSKs and CSKs to the current
            // time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                match &k.keytype {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Csk(keystate, _) => {
                        if keystate.old || !keystate.present {
                            continue;
                        }

                        k.timestamps.visible = Some(now.clone());
                    }
                    KeyType::Include(_) => (),
                }
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let keystate = match &k.keytype {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Csk(keystate, _) => keystate,
                    KeyType::Include(_) => continue,
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                let visible = k
                    .timestamps
                    .visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            for k in ks.keys.values_mut() {
                match k.keytype {
                    KeyType::Ksk(ref mut keystate) => {
                        if keystate.old && keystate.present {
                            keystate.at_parent = false;
                        }

                        // Put Active keys at parent.
                        if !keystate.old && keystate.present {
                            keystate.at_parent = true;
                        }
                    }
                    KeyType::Zsk(ref mut keystate) => {
                        // Move the Incoming keys to Active.
                        if !keystate.old && keystate.present {
                            keystate.signer = true;
                        }
                        if keystate.old {
                            keystate.signer = false;
                        }
                    }
                    KeyType::Csk(
                        ref mut ksk_keystate,
                        ref mut zsk_keystate,
                    ) => {
                        if ksk_keystate.old && ksk_keystate.present {
                            ksk_keystate.at_parent = false;
                        }

                        // Put Active keys at parent.
                        if !ksk_keystate.old && ksk_keystate.present {
                            ksk_keystate.at_parent = true;
                        }

                        // Move the Incoming keys to Active.
                        if !zsk_keystate.old && zsk_keystate.present {
                            zsk_keystate.signer = true;
                        }
                        if zsk_keystate.old {
                            zsk_keystate.signer = false;
                        }
                    }
                    _ => (),
                }
            }
        }
        RollOp::Propagation2 => {
            // Set the published time of new DS records to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                match &k.keytype {
                    KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                        if keystate.old || !keystate.present {
                            continue;
                        }

                        k.timestamps.ds_visible = Some(now.clone());
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => (),
                }
            }

            // Set the published time of new RRSIG records to the current time.
            for k in ks.keys.values_mut() {
                let keystate = match &k.keytype {
                    KeyType::Zsk(keystate) | KeyType::Csk(_, keystate) => {
                        keystate
                    }
                    KeyType::Ksk(_) | KeyType::Include(_) => continue,
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                k.timestamps.rrsig_visible = Some(now.clone());
            }
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let keystate = match &k.keytype {
                    KeyType::Zsk(keystate) | KeyType::Csk(_, keystate) => {
                        keystate
                    }
                    KeyType::Ksk(_) | KeyType::Include(_) => continue,
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                let rrsig_visible = k
                    .timestamps
                    .rrsig_visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = rrsig_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move old keys out
            for k in ks.keys.values_mut() {
                match k.keytype {
                    KeyType::Ksk(ref mut keystate)
                    | KeyType::Csk(ref mut keystate, _) => {
                        if keystate.old && keystate.present {
                            keystate.signer = false;
                            keystate.present = false;
                            k.timestamps.withdrawn = Some(UnixTime::now());
                        }
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => (),
                }
            }
            for k in ks.keys.values_mut() {
                match k.keytype {
                    KeyType::Zsk(ref mut keystate)
                    | KeyType::Csk(_, ref mut keystate) => {
                        if keystate.old && !keystate.signer {
                            keystate.present = false;
                            k.timestamps.withdrawn = Some(UnixTime::now());
                        }
                    }
                    KeyType::Ksk(_) | KeyType::Include(_) => (),
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn csk_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::ReportDnskeyPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::CreateCdsRrset);
            actions.push(Action::UpdateDsRrset);
            actions.push(Action::UpdateRrsig);
            actions.push(Action::ReportDsPropagated);
            actions.push(Action::ReportRrsigPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => {
            actions.push(Action::RemoveCdsRrset);
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::WaitDnskeyPropagated);
        }
    }
    actions
}

// An algorithm roll is similar to a CSK roll. The main difference is that
// the zone is signed with all keys before introducing the DS records for
// the new KSKs or CSKs.
fn algorithm_roll(rollop: RollOp<'_>, ks: &mut KeySet) -> Result<(), Error> {
    match rollop {
        RollOp::Start(old, new) => {
            // First check if the current algorithm-roll state is idle. We need
            // to check all conflicting key rolls as well. The way we check
            // is to allow specified non-conflicting rolls and consider
            // everything else as a conflict.
            if let Some(rolltype) = ks.rollstates.keys().next() {
                if *rolltype == RollType::AlgorithmRoll {
                    return Err(Error::WrongStateForRollOperation);
                } else {
                    return Err(Error::ConflictingRollInProgress);
                }
            }
            // Check if we can move the states of the keys
            ks.update_algorithm(Mode::DryRun, old, new)?;
            // Move the states of the keys
            ks.update_algorithm(Mode::ForReal, old, new)
                .expect("Should have been check with DryRun");
        }
        RollOp::Propagation1 => {
            // Set the visible time of new KSKs, ZSKs and CSKs to the current
            // time. Set RRSIG visible for new ZSKs and CSKs.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                match &mut k.keytype {
                    KeyType::Ksk(keystate) => {
                        if keystate.old || !keystate.present {
                            continue;
                        }

                        k.timestamps.visible = Some(now.clone());
                    }
                    KeyType::Zsk(keystate) | KeyType::Csk(keystate, _) => {
                        if keystate.old || !keystate.present {
                            continue;
                        }

                        k.timestamps.visible = Some(now.clone());
                        k.timestamps.rrsig_visible = Some(now.clone());
                    }
                    KeyType::Include(_) => (),
                }
            }
        }
        RollOp::CacheExpire1(ttl) => {
            for k in ks.keys.values() {
                let keystate = match &k.keytype {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Csk(keystate, _) => keystate,
                    KeyType::Include(_) => continue,
                };
                if keystate.old || !keystate.present {
                    continue;
                }

                let visible = k
                    .timestamps
                    .visible
                    .as_ref()
                    .expect("Should have been set in Propagation1");
                let elapsed = visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            for k in ks.keys.values_mut() {
                match k.keytype {
                    KeyType::Ksk(ref mut keystate)
                    | KeyType::Csk(ref mut keystate, _) => {
                        if keystate.old && keystate.present {
                            keystate.at_parent = false;
                        }

                        // Put Active keys at parent.
                        if !keystate.old && keystate.present {
                            keystate.at_parent = true;
                        }
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => (),
                }
            }
        }
        RollOp::Propagation2 => {
            // Set the published time of new DS records to the current time.
            let now = UnixTime::now();
            for k in ks.keys.values_mut() {
                match &k.keytype {
                    KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                        if keystate.old || !keystate.present {
                            continue;
                        }

                        k.timestamps.ds_visible = Some(now.clone());
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => (),
                }
            }
        }
        RollOp::CacheExpire2(ttl) => {
            for k in ks.keys.values() {
                let keystate = match &k.keytype {
                    KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                        keystate
                    }
                    KeyType::Zsk(_) | KeyType::Include(_) => continue,
                };
                if keystate.old || !keystate.signer {
                    continue;
                }

                let ds_visible = k
                    .timestamps
                    .ds_visible
                    .as_ref()
                    .expect("Should have been set in Propagation2");
                let elapsed = ds_visible.elapsed();
                let ttl = Duration::from_secs(ttl.into());
                if elapsed < ttl {
                    return Err(Error::Wait(ttl - elapsed));
                }
            }

            // Move old keys out
            for k in ks.keys.values_mut() {
                match k.keytype {
                    KeyType::Ksk(ref mut keystate)
                    | KeyType::Zsk(ref mut keystate) => {
                        if keystate.old && keystate.present {
                            keystate.signer = false;
                            keystate.present = false;
                            k.timestamps.withdrawn = Some(UnixTime::now());
                        }
                    }
                    KeyType::Csk(
                        ref mut ksk_keystate,
                        ref mut zsk_keystate,
                    ) => {
                        if ksk_keystate.old && ksk_keystate.present {
                            ksk_keystate.signer = false;
                            ksk_keystate.present = false;
                            zsk_keystate.signer = false;
                            zsk_keystate.present = false;
                            k.timestamps.withdrawn = Some(UnixTime::now());
                        }
                    }
                    KeyType::Include(_) => (),
                }
            }
        }
        RollOp::Done => (),
    }
    Ok(())
}

fn algorithm_roll_actions(rollstate: RollState) -> Vec<Action> {
    let mut actions = Vec::new();
    match rollstate {
        RollState::Propagation1 => {
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::UpdateRrsig);
            actions.push(Action::ReportDnskeyPropagated);
            actions.push(Action::ReportRrsigPropagated);
        }
        RollState::CacheExpire1(_) => (),
        RollState::Propagation2 => {
            actions.push(Action::CreateCdsRrset);
            actions.push(Action::UpdateDsRrset);
            actions.push(Action::ReportDsPropagated);
        }
        RollState::CacheExpire2(_) => (),
        RollState::Done => {
            actions.push(Action::RemoveCdsRrset);
            actions.push(Action::UpdateDnskeyRrset);
            actions.push(Action::UpdateRrsig);
            actions.push(Action::WaitDnskeyPropagated);
            actions.push(Action::WaitRrsigPropagated);
        }
    }
    actions
}

#[cfg(test)]
mod tests {
    use crate::base::Name;
    use crate::dnssec::sign::keys::keyset::SecurityAlgorithm;
    use crate::dnssec::sign::keys::keyset::{
        Action, Available, KeySet, KeyType, RollType, UnixTime,
    };
    use crate::std::string::ToString;
    use mock_instant::global::MockClock;
    use std::str::FromStr;
    use std::string::String;
    use std::time::Duration;
    use std::vec::Vec;

    #[test]
    fn test_name() {
        let ks = KeySet::new(Name::from_str("example.com").unwrap());

        assert_eq!(ks.name().to_string(), "example.com");
    }

    #[test]
    fn test_rolls() {
        let mut ks = KeySet::new(Name::from_str("example.com").unwrap());

        ks.add_key_ksk(
            "first KSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            0,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();
        ks.add_key_zsk(
            "first ZSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            1,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        let actions = ks
            .start_roll(
                RollType::AlgorithmRoll,
                &[],
                &["first KSK", "first ZSK"],
            )
            .unwrap();
        assert_eq!(
            actions,
            [
                Action::UpdateDnskeyRrset,
                Action::UpdateRrsig,
                Action::ReportDnskeyPropagated,
                Action::ReportRrsigPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "first ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["first ZSK"]);
        assert_eq!(ds_keys(&ks), Vec::<String>::new());

        let actions = ks
            .propagation1_complete(RollType::AlgorithmRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired1(RollType::AlgorithmRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::ReportDsPropagated,
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "first ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["first ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks
            .propagation2_complete(RollType::AlgorithmRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::AlgorithmRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::RemoveCdsRrset,
                Action::UpdateDnskeyRrset,
                Action::UpdateRrsig,
                Action::WaitDnskeyPropagated,
                Action::WaitRrsigPropagated,
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "first ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["first ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks.roll_done(RollType::AlgorithmRoll).unwrap();
        assert_eq!(actions, []);

        ks.add_key_ksk(
            "second KSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            2,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();
        ks.add_key_zsk(
            "second ZSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            3,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        println!("line {} = {:?}", line!(), ks.keys().get("second ZSK"));
        let actions = ks
            .start_roll(RollType::ZskRoll, &["first ZSK"], &["second ZSK"])
            .unwrap();
        println!("line {} = {:?}", line!(), ks.keys().get("second ZSK"));
        assert_eq!(
            actions,
            [Action::UpdateDnskeyRrset, Action::ReportDnskeyPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "first ZSK", "second ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        println!("keys = {:?}", ks.keys());
        assert_eq!(zone_sigs(&ks), ["first ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions =
            ks.propagation1_complete(RollType::ZskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired1(RollType::ZskRoll).unwrap();
        assert_eq!(
            actions,
            [Action::UpdateRrsig, Action::ReportRrsigPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "first ZSK", "second ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["second ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions =
            ks.propagation2_complete(RollType::ZskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::ZskRoll).unwrap();
        assert_eq!(
            actions,
            [Action::UpdateDnskeyRrset, Action::WaitDnskeyPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "second ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["second ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks.roll_done(RollType::ZskRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("first ZSK").unwrap();

        ks.add_key_zsk(
            "third ZSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            4,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        let actions = ks
            .start_roll(
                RollType::ZskDoubleSignatureRoll,
                &["second ZSK"],
                &["third ZSK"],
            )
            .unwrap();
        assert_eq!(
            actions,
            [
                Action::UpdateDnskeyRrset,
                Action::UpdateRrsig,
                Action::ReportDnskeyPropagated,
                Action::ReportRrsigPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "second ZSK", "third ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        let mut zs = zone_sigs(&ks);
        zs.sort();
        assert_eq!(zs, ["second ZSK", "third ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks
            .propagation1_complete(RollType::ZskDoubleSignatureRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions =
            ks.cache_expired1(RollType::ZskDoubleSignatureRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::UpdateDnskeyRrset,
                Action::UpdateRrsig,
                Action::ReportDnskeyPropagated,
                Action::ReportRrsigPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "third ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks
            .propagation2_complete(RollType::ZskDoubleSignatureRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions =
            ks.cache_expired2(RollType::ZskDoubleSignatureRoll).unwrap();
        assert_eq!(actions, []);
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "third ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions = ks.roll_done(RollType::ZskDoubleSignatureRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("second ZSK").unwrap();

        let actions = ks
            .start_roll(RollType::KskRoll, &["first KSK"], &["second KSK"])
            .unwrap();
        assert_eq!(
            actions,
            [Action::UpdateDnskeyRrset, Action::ReportDnskeyPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "second KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first KSK", "second KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["first KSK"]);

        let actions =
            ks.propagation1_complete(RollType::KskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired1(RollType::KskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::ReportDsPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first KSK", "second KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first KSK", "second KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["second KSK"]);

        let actions =
            ks.propagation2_complete(RollType::KskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::KskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::RemoveCdsRrset,
                Action::UpdateDnskeyRrset,
                Action::WaitDnskeyPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["second KSK", "third ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["second KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["second KSK"]);

        let actions = ks.roll_done(RollType::KskRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("first KSK").unwrap();

        ks.add_key_ksk(
            "third KSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            5,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        let actions = ks
            .start_roll(
                RollType::KskDoubleDsRoll,
                &["second KSK"],
                &["third KSK"],
            )
            .unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::ReportDsPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["second KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["second KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        let mut dsks = ds_keys(&ks);
        dsks.sort();
        assert_eq!(dsks, ["second KSK", "third KSK"]);

        let actions = ks
            .propagation1_complete(RollType::KskDoubleDsRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired1(RollType::KskDoubleDsRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::RemoveCdsRrset,
                Action::UpdateDnskeyRrset,
                Action::ReportDnskeyPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["third KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["third KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        let mut dsks = ds_keys(&ks);
        dsks.sort();
        assert_eq!(dsks, ["second KSK", "third KSK"]);

        let actions = ks
            .propagation2_complete(RollType::KskDoubleDsRoll, 3600)
            .unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::KskDoubleDsRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::WaitDsPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["third KSK", "third ZSK"]);
        assert_eq!(dnskey_sigs(&ks), ["third KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["third KSK"]);

        let actions = ks.roll_done(RollType::KskDoubleDsRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("second KSK").unwrap();

        ks.add_key_csk(
            "first CSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            0,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        let actions = ks
            .start_roll(
                RollType::CskRoll,
                &["third KSK", "third ZSK"],
                &["first CSK"],
            )
            .unwrap();
        assert_eq!(
            actions,
            [Action::UpdateDnskeyRrset, Action::ReportDnskeyPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first CSK", "third KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first CSK", "third KSK"]);
        assert_eq!(zone_sigs(&ks), ["third ZSK"]);
        assert_eq!(ds_keys(&ks), ["third KSK"]);

        let actions =
            ks.propagation1_complete(RollType::CskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired1(RollType::CskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::UpdateRrsig,
                Action::ReportDsPropagated,
                Action::ReportRrsigPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first CSK", "third KSK", "third ZSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first CSK", "third KSK"]);
        assert_eq!(zone_sigs(&ks), ["first CSK"]);
        assert_eq!(ds_keys(&ks), ["first CSK"]);

        let actions =
            ks.propagation2_complete(RollType::CskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::CskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::RemoveCdsRrset,
                Action::UpdateDnskeyRrset,
                Action::WaitDnskeyPropagated
            ]
        );
        assert_eq!(dnskey(&ks), ["first CSK"]);
        assert_eq!(dnskey_sigs(&ks), ["first CSK"]);
        assert_eq!(zone_sigs(&ks), ["first CSK"]);
        assert_eq!(ds_keys(&ks), ["first CSK"]);

        let actions = ks.roll_done(RollType::CskRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("third KSK").unwrap();
        ks.delete_key("third ZSK").unwrap();

        ks.add_key_csk(
            "second CSK".to_string(),
            None,
            SecurityAlgorithm::ECDSAP256SHA256,
            4,
            UnixTime::now(),
            Available::Available,
        )
        .unwrap();

        let actions = ks
            .start_roll(RollType::CskRoll, &["first CSK"], &["second CSK"])
            .unwrap();
        assert_eq!(
            actions,
            [Action::UpdateDnskeyRrset, Action::ReportDnskeyPropagated]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first CSK", "second CSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first CSK", "second CSK"]);
        assert_eq!(zone_sigs(&ks), ["first CSK"]);
        assert_eq!(ds_keys(&ks), ["first CSK"]);

        let actions =
            ks.propagation1_complete(RollType::CskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        println!("CSK roll cache expired1");
        let actions = ks.cache_expired1(RollType::CskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::CreateCdsRrset,
                Action::UpdateDsRrset,
                Action::UpdateRrsig,
                Action::ReportDsPropagated,
                Action::ReportRrsigPropagated
            ]
        );
        let mut dk = dnskey(&ks);
        dk.sort();
        assert_eq!(dk, ["first CSK", "second CSK"]);
        let mut dks = dnskey_sigs(&ks);
        dks.sort();
        assert_eq!(dks, ["first CSK", "second CSK"]);
        assert_eq!(zone_sigs(&ks), ["second CSK"]);
        assert_eq!(ds_keys(&ks), ["second CSK"]);

        let actions =
            ks.propagation2_complete(RollType::CskRoll, 3600).unwrap();
        assert_eq!(actions, []);

        MockClock::advance_system_time(Duration::from_secs(3600));

        let actions = ks.cache_expired2(RollType::CskRoll).unwrap();
        assert_eq!(
            actions,
            [
                Action::RemoveCdsRrset,
                Action::UpdateDnskeyRrset,
                Action::WaitDnskeyPropagated
            ]
        );
        assert_eq!(dnskey(&ks), ["second CSK"]);
        assert_eq!(dnskey_sigs(&ks), ["second CSK"]);
        assert_eq!(zone_sigs(&ks), ["second CSK"]);
        assert_eq!(ds_keys(&ks), ["second CSK"]);

        let actions = ks.roll_done(RollType::CskRoll).unwrap();
        assert_eq!(actions, []);
        ks.delete_key("first CSK").unwrap();
    }

    fn dnskey(ks: &KeySet) -> Vec<String> {
        ks.keys()
            .iter()
            .filter(|(_, k)| {
                let status = match k.keytype() {
                    KeyType::Ksk(keystate)
                    | KeyType::Zsk(keystate)
                    | KeyType::Csk(keystate, _)
                    | KeyType::Include(keystate) => keystate,
                };
                status.present()
            })
            .map(|(pr, _)| pr.to_string())
            .collect()
    }

    fn dnskey_sigs(ks: &KeySet) -> Vec<String> {
        let keys = ks.keys();
        let mut vec = Vec::new();
        for (pubref, key) in keys {
            match key.keytype() {
                KeyType::Ksk(keystate) | KeyType::Csk(keystate, _) => {
                    if keystate.signer() {
                        vec.push(pubref.to_string());
                    }
                }
                KeyType::Zsk(_) | KeyType::Include(_) => (),
            }
        }
        vec
    }
    fn zone_sigs(ks: &KeySet) -> Vec<String> {
        let keys = ks.keys();
        let mut vec = Vec::new();
        for (pubref, key) in keys {
            match key.keytype() {
                KeyType::Zsk(keystate) | KeyType::Csk(_, keystate) => {
                    if keystate.signer() {
                        vec.push(pubref.to_string());
                    }
                }
                KeyType::Ksk(_) | KeyType::Include(_) => (),
            }
        }
        vec
    }
    fn ds_keys(ks: &KeySet) -> Vec<String> {
        let keys = ks.keys();
        let mut vec = Vec::new();
        for (pubref, key) in keys {
            let status = match key.keytype() {
                KeyType::Ksk(keystate)
                | KeyType::Zsk(keystate)
                | KeyType::Csk(keystate, _)
                | KeyType::Include(keystate) => keystate,
            };
            if status.at_parent() {
                vec.push(pubref.to_string());
            }
        }
        vec
    }
}