1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
// SPDX-License-Identifier: MPL-2.0
//
// Part of Auguth Labs open-source softwares.
// Built for the Substrate framework.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2026 Auguth Labs (OPC) Pvt Ltd, India
// ===============================================================================
// ```````````````````````````` PALLET CHAIN-MANAGER `````````````````````````````
// ===============================================================================
//! The **Chain Manager pallet** is the primary orchestration layer for
//! managing **session validators** as a coordinated, session-driven system.
//!
//! It governs the full validator lifecycle spanning participation,
//! election, activation, rewards, and penalties by materializing the
//! abstractions defined in [`frame_suite::blockchain`]
//! into a concrete runtime execution model.
//!
//! This pallet does not introduce new primitives. Instead, it binds together
//! traits, plugins, and adapters to drive deterministic validator selection
//! and behavior across sessions, enabling the game-theoretic guarantees
//! required for a decentralized network.
//!
//! - [`Config`] - Runtime configuration
//! - [`Call`] - Dispatchable extrinsics (includes unsigned)
//! - [`Pallet`] - External usage and trait implementations
//!
//! ## Overview
//!
//! A **validator (author)** in this system is an actor who:
//!
//! - signals intent to participate in validation,
//! - submits affidavit data (backers) for election,
//! - competes in a session-based selection process,
//! - becomes an active session validator upon selection,
//! - receives rewards or penalties based on behavior.
//!
//! Validators are modeled as **session-scoped actors**, where
//! participation, selection, and compensation are tied to
//! deterministic session transitions.
//!
//! ## Architectural Role
//!
//! The pallet acts as an **orchestration boundary**, integrating:
//!
//! - role management and funding via [`Config::RoleAdapter`]
//! - election logic via [`Config::ElectionAdapter`]
//! - asset interactions via [`Config::Asset`]
//! - session and authorship via [`pallet_session`] and [`pallet_authorship`]
//! - offence handling via [`pallet_offences`]
//!
//! It only tightly integrates with these essential core pallets, allowing
//! any Substrate runtime that composes them to adopt this pallet
//! for validator lifecycle and session management.
//!
//! ## Validator Lifecycle
//!
//! The system progresses through **session-scoped phases**:
//!
//! - **Pursuing Validation**
//! Authors signal intent to validate and may pause participation (`chill`).
//!
//! - **Affidavit Phase**
//! Active participants submit affidavit declarations representing
//! election weights for the upcoming validator set.
//!
//! - **Election Phase**
//! Elections are executed for all active participants to determine
//! the next session validators.
//!
//! - **Activation**
//! Elected authors transition into active session validators.
//!
//! - **Reward & Penalty**
//! Validators are compensated or penalized based on behavior.
//!
//! All transitions are derived relative to session progression,
//! ensuring predictable and deterministic execution.
//!
//! ## Execution Model
//!
//! The pallet operates as a **session-driven orchestration engine**,
//! primarily driven by **offchain workers and unsigned extrinsics**.
//!
//! Once validation intent is externally invoked by an author, the system
//! progresses automatically:
//!
//! - **Offchain workers**
//! coordinate affidavit submission, election execution, and key rotation
//!
//! - **Unsigned extrinsics**
//! are submitted to finalize deterministic state transitions
//!
//! - **Block hooks (`on_initialize`)**
//! process accumulated state and scheduled transitions
//!
//! This enables:
//!
//! - automated validator lifecycle progression
//! - continuous election participation for active candidates
//! - minimal manual interaction beyond intent signaling
//!
//! ## Economic Model
//!
//! Rewards and penalties are **externally defined and injected**:
//!
//! - [`Config::InflationModel`]: derives total session payout
//! - [`Config::RewardModel`]: distributes rewards from points
//! - [`Config::PenaltyModel`]: transforms and normalizes penalties
//!
//! Final application is delegated via [`Config::RoleAdapter`],
//! ensuring consistent integration with role and funding systems.
//!
//! ## Design Intent
//!
//! This pallet is a **composition layer**, not a monolithic system:
//!
//! - structure is defined via traits
//! - behavior is injected via plugins
//! - coordination is driven by sessions and routines
//!
//! enabling a modular, replaceable, and evolvable validator system
//! while preserving strong type safety and deterministic execution.
//!
//! ## Development Feature Gate
//!
//! This pallet includes a `dev` feature gate for development and testing.
//!
//! Core functionality is exposed via public APIs for RPC and UI usage.
//! The `dev` feature provides thin wrapper extrinsics and extended
//! event emissions for direct inspection.
//!
//! This feature must be disabled in production runtimes due to
//! additional debugging overhead.
#![cfg_attr(not(feature = "std"), no_std)]
// ===============================================================================
// `````````````````````````````````` MODULES ````````````````````````````````````
// ===============================================================================
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
pub(crate) mod mock;
mod mocks {
#[path = "balances.rs"]
#[cfg(test)]
pub mod balances;
#[path = "xp.rs"]
#[cfg(test)]
pub mod xp;
}
#[cfg(test)]
mod tests;
mod blockchain;
mod offence;
mod roles;
mod routines;
mod session;
pub mod types;
pub mod crypto;
pub mod weights;
// Re-Exports for `Config` usage
pub use crate::crypto::AffidavitCryptoEd25519;
pub use crate::crypto::AffidavitCryptoSr25519;
// ===============================================================================
// `````````````````````````````` PALLET MODULE ``````````````````````````````````
// ===============================================================================
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
// ===============================================================================
// ````````````````````````````````` IMPORTS `````````````````````````````````````
// ===============================================================================
// --- Local crate imports ---
use super::*;
use crate::{
crypto::ValidatePayload,
routines::*,
types::*,
weights::*,
};
// --- Core / Std ---
use core::fmt::Debug;
// --- FRAME Suite ---
use frame_suite::{
Countable, ForkLocalDepot, ForksHandler, blockchain::*, elections::*, plugin_types, roles::*, routines::*
};
// --- FRAME Support ---
use frame_support::{
dispatch::DispatchResult,
pallet_prelude::{StorageValue, *},
traits::{
fungible::{Inspect, Mutate},
EstimateNextSessionRotation,
},
};
// --- FRAME System ---
use frame_system::{
offchain::{AppCrypto, SignedPayload},
pallet_prelude::{BlockNumberFor, *},
};
// --- Substrate primitives ---
use sp_core::Get;
use sp_runtime::{
RuntimeAppPublic, SaturatedConversion, WeakBoundedVec, traits::{Convert, IdentifyAccount, Saturating}
};
// ===============================================================================
// `````````````````````````````` PALLET MARKER ``````````````````````````````````
// ===============================================================================
/// Primary Marker type for the **Chain Manager pallet**.
///
/// This pallet provides implementations for traits from
/// [`blockchain`](frame_suite::blockchain), [`roles`](frame_suite::roles),
/// [`session`](pallet_session), [`offences`](sp_staking::offence)
///
/// Implemented traits:
///
/// - [`AuthorPoints`]
/// - [`ElectionAffidavits`]
/// - [`SessionManager`](pallet_session::SessionManager)
/// - [`OnOffenceHandler`](sp_staking::offence::OnOffenceHandler)
/// - [`RoleActivity`]
/// - [`Convert<AuthorId, Option<SessionId>>`](sp_runtime::traits::Convert)
#[pallet::pallet]
pub struct Pallet<T>(PhantomData<T>);
// ===============================================================================
// ```````````````````````````` INTERNAL PALLET MARKER ```````````````````````````
// ===============================================================================
/// Internal helper struct for implementing not-exposable
/// [`blockchain`](frame_suite::blockchain) trait operations.
///
/// `Internals` implements the blockchain low-level helper traits:
///
/// - [`RewardAuthors`](frame_suite::blockchain::RewardAuthors)
/// - [`ElectAuthors`](frame_suite::blockchain::ElectAuthors)
/// - [`PenalizeAuthors`](frame_suite::blockchain::PenalizeAuthors)
pub(crate) struct Internals<T: Config>(PhantomData<T>);
// ===============================================================================
// `````````````````````````````` CONFIG TRAIT ```````````````````````````````````
// ===============================================================================
/// Configuration trait for the Chain Manager pallet.
///
/// This trait defines the types, constants, and dependencies
/// that the runtime must provide for this pallet to function.
///
/// It extends several other FRAME pallets' `Config` traits, ensuring tight
/// integration with Substrate's session, authorship, time-management and
/// offence-handling subsystems.
///
/// ### Dependencies
///
/// Dependencies other than [`frame_system::Config`]:
/// - [`pallet_authorship::Config`]: Provides access to the current block author
/// and authorship tracking, used to assign and record block production points.
/// - [`pallet_offences::Config`]: Enables detection and handling of offences for
/// misbehaving authors, required for penalty enforcement.
/// - [`pallet_session::Config`]: Manages session rotation and validator/author sets;
/// supports session-aware election and reward cycles.
/// - [`pallet_session::historical::Config`]: Provides access to historical session
/// data for offence handling.
/// - [`pallet_timestamp::Config`] : Provides access to a monotonic deterministic
/// onchain unix timestamp.
/// - [`frame_system::offchain::CreateSignedTransaction`]: Enables offchain workers
/// to sign and submit transactions. Required for unsigned extrinsics that rely
/// on signed payload verification ([`ValidateUnsigned`]).
#[pallet::config]
pub trait Config: frame_system::Config
+ pallet_authorship::Config
+ pallet_offences::Config
+ pallet_session::Config
+ pallet_session::historical::Config
+ pallet_timestamp::Config
+ frame_system::offchain::CreateSignedTransaction<<Self as frame_system::Config>::RuntimeCall>
{
// --- Runtime Anchors ---
/// Extrinsic calls aggregation type for the runtime.
type RuntimeCall: From<Call<Self>> + Into<<Self as frame_system::Config>::RuntimeCall>;
/// Events aggregation type for the runtime.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
// --- Pallet Adapters ---
/// Adapter type for **author role, and compensation management**.
///
/// This associated type integrates multiple traits that together define how
/// authors are **managed**, **rewarded**, and **funded**.
///
/// It acts as a unified interface between this pallet and the underlying
/// role-management, and reward systems.
///
/// ## Required Traits
/// - [`RoleManager`]: Core author management - handles registration and membership.
/// - [`CompensateRoles`]: Defines logic for author **rewards and penalties**.
/// - [`FundRoles`]: Enables **external funding or backing** mechanisms for authors.
type RoleAdapter: RoleManager<AuthorOf<Self>>
// Since `OnOffenceHandler` uses `Perbill` directly hence
+ CompensateRoles<AuthorOf<Self>, Ratio = PenaltyRatio>
+ FundRoles<AuthorOf<Self>>;
/// Adapter type for role **author election management system**.
///
/// This associated type integrates multiple traits that together define how
/// authors are **elected**.
///
/// ## Required Traits
/// - [`ElectionManager`]: Conducts author **elections** on behalf of this pallet.
/// - [`InspectWeight`]: Provides APIs to **query election weights** for authors.
type ElectionAdapter: ElectionManager<AuthorOf<Self>>
+ InspectWeight<AuthorOf<Self>, ElectionVia<Self>>;
/// The **asset type** used for distributing rewards and penalties.
///
/// This represents a fungible unit (e.g., a token balance) over which
/// the pallet performs **reward**, **penalty**, and **funding** operations.
///
/// ## Requirements
/// - Must implement [`Inspect`], enabling the pallet to query and verify
/// account balances or holdings of authors.
///
/// ## Example
/// ```ignore
/// type Asset = pallet_assets::Pallet<T>;
/// ```
type Asset: Inspect<
AuthorOf<Self>,
// Ensures that the pallet's `Asset` type aligns with the assets
// used by role-manager system.
//
// Guarantees that rewards, penalties, and funding operations
// use a **consistent asset type**.
Balance = AssetOf<Self>,
> + Mutate<AuthorOf<Self>>;
/// Adapter for managing and querying **author points**.
///
/// Provides the implementation for tracking points (e.g., block production
/// or performance metrics) associated with each author.
///
/// This can be set to [`Pallet<Self>`] if using the chain-manager pallet's
/// internal implementation, or provided externally via another pallet or adapter.
type PointsAdapter: AuthorPoints<AuthorOf<Self>, Self::Points>;
// --- Pallets-exposed Additional Types ---
/// Provides the logic to **estimate the length of the next session**.
///
/// Used to compute
/// - affidavit submission windows,
/// - election start blocks, and
/// - session timing.
type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
/// Custom application crypto for **affidavit submission and rotation**.
///
/// Defines the cryptographic scheme used by offchain workers when
/// submitting and rotating affidavits. This associated type creates
/// a dedicated `KeyId` namespace for affidavit-related operations.
///
/// ## Supported Cryptography
/// - [`AffidavitCryptoEd25519`]
/// - [`AffidavitCryptoSr25519`]
///
/// Either scheme may be used depending on the desired security and
/// performance characteristics.
type AffidavitCrypto: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>;
// --- Scalars ---
/// Type representing **good-behaviour points** accumulated by an author.
///
/// This is an abstract point type used to measure good behaviour
/// (e.g. block production) within a session.
///
/// ## Design Notes
/// - Points are **session-scoped** and non-transferable.
/// - This is **not** an economic asset.
/// - Points are interpreted later by reward and penalty logic
/// and may be transformed into actual asset movements.
type Points: Countable;
// --- Plugins ---
// Plugin for computing **inflation-adjusted total payout**.
plugin_types!(
input: AssetOf<Self>,
output: AssetOf<Self>,
/// Inflation adjustment **plugin model**.
///
/// This model defines the logic used to transform the raw total asset
/// (`AssetOf`) into an inflation-adjusted payout before distribution
/// to authors.
///
/// Conceptually similar to `PayoutModel` in `RewardAuthors`, but focused
/// specifically on inflation-based adjustments in a more layman-friendly
/// abstraction.
///
/// ## Input
/// - [`AssetOf`]: The raw total asset for the current cycle.
///
/// ## Output
/// - [`AssetOf`]: The total asset after applying inflation rules.
///
/// Designed to be runtime-configurable via [`Self::InflationContext`].
///
/// Designed to be selectable using template plugin models in
/// [`frame_plugins::rewards::payout`] or custom model defining
/// macros via [`frame_suite::plugins`].
model: InflationModel,
/// Runtime **context** for the inflation adjustment plugin model.
///
/// Provides configurable parameters that influence how the
/// [`Self::InflationModel`] behaves at runtime.
///
/// ## Examples
/// - Inflation rates
/// - Upper or lower payout caps
/// - Scaling coefficients or dampening factors
///
/// This allows the inflation logic to be tuned without changing the model
/// implementation itself.
context: InflationContext,
);
// Plugin for computing **per-author rewards** from total payout and points.
plugin_types!(
input: (AssetOf<Self>, PayoutFor<Self>),
output: PayeeList<Self>,
/// Per-author **reward distribution plugin model**.
///
/// Responsible for mapping each author's contribution to a concrete payout.
/// Conceptually performs:
///
/// `(Author, Points)` -> `(Author, AssetOf)`
///
/// ## Input
/// - ([`AssetOf`], [`PayoutFor`]):
/// The total payout for the cycle and the per-author points allocation.
///
/// ## Output
/// - [`PayeeList`]:
/// The finalized list of authors and their respective rewards.
///
/// ## Notes
/// - Maps each author's points to their final reward share.
/// - Designed to be runtime-configurable via [`Self::RewardContext`].
///
/// Designed to be selectable using template plugin models in
/// [`frame_plugins::rewards::payee`] or custom model defining
/// macros via [`frame_suite::plugins`].
model: RewardModel,
/// Runtime **context** for configuring reward plugin computation.
///
/// Supplies parameters that influence how rewards are calculated and
/// distributed by the [`Self::RewardModel`].
///
/// ## Examples
/// - Multipliers or weights
/// - Per-author or global caps
/// - Curves, thresholds, or smoothing factors
///
/// This separation allows payout logic to evolve independently from
/// runtime tuning and governance decisions.
context: RewardContext,
);
// Plugin for **transforming penalties** of authors.
plugin_types!(
input: PenaltyFor<Self>,
output: PenaltyFor<Self>,
/// **Penalty transformation plugin model**.
///
/// Defines how author penalties are adjusted before being applied.
/// Conceptually performs:
///
/// `(Author, Penalty)` -> `(Author, Penalty)`
///
/// ## Input
/// - [`PenaltyFor`]:
/// The raw per-author penalties for the current cycle.
///
/// ## Output
/// - [`PenaltyFor`]:
/// The penalties after applying transformation rules.
///
/// ## Notes
/// - Supports caps, scaling, or other penalty transformation logic.
/// - Runtime behavior is influenced by [`Self::PenaltyContext`].
///
/// Designed to be selectable using template plugin models in
/// [`frame_plugins::penalty`] or custom model defining
/// macros via [`frame_suite::plugins`].
model: PenaltyModel,
/// Runtime **context** for penalty plugin transformation.
///
/// Supplies parameters that configure how the [`Self::PenaltyModel`] operates
/// at runtime.
///
/// ## Examples
/// - Multipliers or dampening factors
/// - Upper or lower penalty caps
/// - Thresholds or step functions
///
/// This allows penalty policy changes without modifying the model
/// implementation.
context: PenaltyContext,
);
// --- Weights ---
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
// --- Constants ---
/// **Flag for reward inflation model**.
///
/// Determines how the total reward pool is computed:
/// - `true`: total asset supply is used to calculate inflation/rewards.
/// - `false`: total locked stake of authors is used instead.
///
/// This allows flexible reward strategies depending on economic design.
#[pallet::constant]
type InflateViaSupply: Get<bool> + Clone + Debug;
/// Maximum number of **weights an author can submit in an affidavit**.
///
/// Weight represents backers or collateral information essential for
/// conducting elections.
///
/// Limits storage and ensures predictable handling of submitted affidavits.
/// If an author submits more than this number, the weights may be truncated.
///
/// Each weight must remain sortable (`Ord`) for ensuring priority ordering during
/// truncation to this upper bound.
#[pallet::constant]
type MaxAffidavitWeights: Get<u32> + Clone + Debug;
const MAX_FORKS: u32;
const MAX_FORK_RECOVERY_TRAVERSAL: u32;
/// Controls emission of [`Event`] via `deposit_event`.
///
/// Recommended:
/// - `false` for production runtimes (to reduce overhead)
/// - `true` for development and mock runtimes (for testing and
/// observability)
#[pallet::constant]
type EmitEvents: Get<bool> + Clone + Debug;
}
// ===============================================================================
// ``````````````````````````````` GENESIS CONFIG ````````````````````````````````
// ===============================================================================
/// Genesis configuration for the **Chain Manager pallet**.
///
/// Provides the **initial runtime parameters** governing session-driven
/// validator orchestration, including affidavit flow, election timing,
/// transaction prioritization, and finality safeguards at chain genesis.
///
/// These values define the **baseline execution schedule and coordination rules**
/// for validator lifecycle before any sessions are processed.
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
/// Whether affidavit submission is enabled.
/// - `true`: authors may submit affidavit data during the configured window.
/// - `false`: affidavit submission is entirely disabled.
pub allow_affidavits: bool,
/// Relative point within a session at which the affidavit phase begins.
///
/// Expressed as a fraction of the session (e.g., `0.2` = 20% into the session).
/// Defines when authors can start submitting affidavit.
/// Submissions made before this point are not permitted.
pub afdvt_begins_at: Duration,
/// Relative point within a session at which the affidavit phase ends.
///
/// Must be greater than `afdvt_begins_at` and within session bounds.
/// After this point, no new affidavit submissions are accepted.
pub afdvt_ends_at: Duration,
/// Relative point within a session at which election execution begins.
///
/// Typically aligned with or after the affidavit phase to ensure
/// all candidate data is available for selection.
pub election_begins_at: Duration,
/// Number of points awarded to the author responsible for executing elections.
///
/// Acts as an incentive for offchain workers or authors coordinating
/// election execution in a timely manner.
pub election_runner_points: T::Points,
/// Transaction priority assigned to validation-related unsigned extrinsics.
///
/// Higher priority ensures inclusion in blocks under contention.
/// Should typically be the highest among lifecycle operations.
pub validate_tx_priority: TransactionPriority,
/// Transaction priority assigned to affidavit submission extrinsics.
///
/// Balanced to allow fair participation without starving higher-priority
/// operations such as validation.
pub affidavit_tx_priority: TransactionPriority,
/// Transaction priority assigned to election execution extrinsics.
///
/// Ensures elections are processed in time, but typically lower than
/// validation and affidavit priorities.
pub election_tx_priority: TransactionPriority,
/// Time-based delay (in milliseconds) before an operation is considered final.
///
/// Helps mitigate premature execution in unstable network conditions
/// or during short-lived forks.
pub finality_after: u64,
/// Block-based confirmation threshold for finality.
///
/// Represents the number of distinct blocks that must pass before
/// an operation is finalized, providing deterministic safety
/// against reorgs.
pub finality_ticks: BlockNumberFor<T>,
}
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
allow_affidavits: false,
afdvt_begins_at: Duration::from_rational(2u32, 10u32), // 20%
afdvt_ends_at: Duration::from_rational(8u32, 10u32), // 80%
election_begins_at: Duration::from_rational(5u32, 10u32), // 50%
election_runner_points: 10u8.into(),
validate_tx_priority: 1_000_000,
affidavit_tx_priority: 850_000,
election_tx_priority: 700_000,
// 1 minute delay
finality_after: 60_000,
// 5 distinct blocks
finality_ticks: 5u32.into(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
// --- Affidavit window ---
assert!(
self.afdvt_begins_at < self.afdvt_ends_at,
"`AffidavitBeginsAt` must be less than `AffidavitEndsAt`"
);
assert!(
self.afdvt_ends_at <= Duration::one(),
"`AffidavitEndsAt` cannot exceed 100%"
);
assert!(
self.election_begins_at <= Duration::one(),
"`ElectionBeginsAt` must be within 0-100% of affidavit window"
);
// --- Tx priorities ---
assert!(self.validate_tx_priority > 0);
assert!(self.election_tx_priority > 0);
assert!(self.affidavit_tx_priority > 0);
// --- Finality ---
assert!(self.finality_after > 0);
assert!(self.finality_ticks > Zero::zero());
AllowAffidavits::<T>::put(self.allow_affidavits);
AffidavitBeginsAt::<T>::put(self.afdvt_begins_at);
AffidavitEndsAt::<T>::put(self.afdvt_ends_at);
ElectionBeginsAt::<T>::put(self.election_begins_at);
ElectionRunnerPoints::<T>::put(self.election_runner_points);
ValidateTxPriority::<T>::put(self.validate_tx_priority);
ElectionTxPriority::<T>::put(self.election_tx_priority);
AffidavitTxPriority::<T>::put(self.affidavit_tx_priority);
let moment: Moment<T> = self.finality_after.saturated_into();
FinalityAfter::<T>::put(moment);
FinalityTicks::<T>::put(self.finality_ticks);
}
}
// ===============================================================================
// ```````````````````````````````` STORAGE TYPES ````````````````````````````````
// ===============================================================================
/// The **current running session index**.
///
/// Used to track session-aware operations such as:
/// - Author points accumulation ([`AuthorPoints`])
/// - Reward and penalty distribution
/// - Affidavit submission and election preparation
#[pallet::storage]
pub type CurrentSession<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
/// Storage mapping of **authors' submitted affidavits per session**.
///
/// Keyed by:
/// 1. [`SessionIndex`] - the session for which the affidavit applies for election.
/// 2. [`AuthorOf`] - the author submitting the affidavit
///
/// Value is a tuple of:
/// - [`BlockNumberFor`]: the block when the affidavit was submitted and,
/// - A `WeakBoundedVec` of [`ElectionWeight`]: the author's declared weights,
/// bounded to prevent excessive storage
///
/// This storage is used for:
/// - Preparing election candidates for the next session
#[pallet::storage]
pub type AuthorAffidavits<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, SessionIndex>,
NMapKey<Blake2_128Concat, AuthorOf<T>>,
),
(
BlockNumberFor<T>,
WeakBoundedVec<ElectionWeight<T>, T::MaxAffidavitWeights>,
),
OptionQuery,
>;
/// **Author points accumulated per session**.
///
/// This storage tracks **block-level points** awarded to authors for good behavior
/// during block production. Each increment represents a positive contribution,
/// such as successfully producing a block or validating transactions correctly.
///
/// Keyed by:
/// 1. [`SessionIndex`]: the session in which points are earned.
/// 2. [`AuthorOf`]: the author receiving the points.
///
/// Value:
/// - [`Config::Points`]: the total points accumulated by the author in that session.
///
/// Notes:
/// - This serves as the **high-level points store** for reward calculation.
/// - Each block-level good behavior contributes **one point** to this tally.
/// - Points are **session-scoped and ephemeral**; typically cleared after reward distribution.
/// - Can be used as a reference for evaluating other contributions or behaviors of authors.
#[pallet::storage]
pub type BlockPointsStore<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, SessionIndex>,
NMapKey<Blake2_128Concat, AuthorOf<T>>,
),
T::Points,
OptionQuery,
>;
/// **Start block of the current session**.
///
/// Tracks the block number when the current session began.
/// Used for:
/// - Computing session-relative timing for elections and affidavits.
#[pallet::storage]
pub type SessionStartAt<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
/// **Flag to enable or disable affidavit submissions**.
///
/// Controls whether authors can submit self-reported election weights.
/// When `true`, affidavit-related functions are active; when `false`, submissions
/// are blocked. Initially, this is expected to be `false` and gradually enabled once
/// the required authors are ready.
#[pallet::storage]
pub type AllowAffidavits<T: Config> = StorageValue<_, bool, ValueQuery>;
// /// **Flag for reward inflation model**.
// ///
// /// Determines how the total reward pool is computed:
// /// - `true`: total asset supply is used to calculate inflation/rewards.
// /// - `false`: total locked stake of authors is used instead.
// ///
// /// This allows flexible reward strategies depending on economic design.
// #[pallet::storage]
// pub type InflateViaSupply<T: Config> = StorageValue<_, bool, ValueQuery>;
/// **Start of affidavit submission window** as a percentage ([`PerThing`]) of the
/// current session. Authors submit affidavits for the **next upcoming session**
/// starting from this point.
///
/// ## Examples
/// - If the current session is 1000 blocks long and `AffidavitBeginsAt = 20%`,
/// affidavit submissions can start at block `200` of the current session.
/// - Authors cannot submit affidavits before this block, even if they are ready.
#[pallet::storage]
pub type AffidavitBeginsAt<T: Config> = StorageValue<_, Duration, ValueQuery>;
/// **End of affidavit submission window** as a percentage ([`PerThing`]) of the
/// current session.
///
/// Authors must submit affidavits **before this block**, leaving room for the
/// election process for the next upcoming session.
///
/// ## Examples
/// - If the current session is 100 blocks long and `AffidavitEndsAt = 80%`,
/// affidavit submissions must end by block `800`.
/// - The period from `AffidavitBeginsAt` to `AffidavitEndsAt` defines the **affidavit
/// submission window**.
/// - Elections for the next session should be conducted before this period ends.
#[pallet::storage]
pub type AffidavitEndsAt<T: Config> = StorageValue<_, Duration, ValueQuery>;
/// **Start of the election window** as a percentage ([`PerThing`]) of the **affidavit
/// submission period** in the current session.
///
/// This does **not** refer to a percentage of the full session, but rather the **relative
/// position within the affidavit submission window**. Authors submit affidavits first, then
/// after this point, the election process can start.
///
/// ## Examples
/// - Suppose the affidavit window spans blocks 200-800 (`AffidavitBeginsAt = 20%`,
/// `AffidavitEndsAt = 80%` in a 100-block session).
/// - If `ElectionBeginsAt = 50%`, then the election starts halfway through the
/// affidavit window: 200 + 50% * (800 - 200) = block 500.
/// - Timeline:
/// - 200-500: affidavit submission period
/// - 500-800: election preparation
#[pallet::storage]
pub type ElectionBeginsAt<T: Config> = StorageValue<_, Duration, ValueQuery>;
/// **Block points allocated for the election runner**.
///
/// Determines how many [`Config::Points`] are required or suitable for an author
/// to act as the election runner in the upcoming session.
///
/// This value is used to assess election participation eligibility or priority.
#[pallet::storage]
pub type ElectionRunnerPoints<T: Config> = StorageValue<_, T::Points, ValueQuery>;
/// **Pending upgrade of election runner points**.
///
/// When an upgrade occurs, this should be set to `None` after being applied.
///
/// ## Notes
/// - Upgrades should occur **after all author rewards have been distributed**
/// and before the next reward cycle starts.
/// - Ensures fairness: if upgraded mid-session, authors who have not yet
/// submitted affidavits may be disadvantaged in election chances.
/// - Any user of [`ElectionRunnerPoints`] should take this storage value into account
/// for the upcoming session.
#[pallet::storage]
pub type ElectionRunnerPointsUpgrade<T: Config> =
StorageValue<_, Option<T::Points>, ValueQuery>;
/// **Offchain affidavit keys registered by an author for a given session**.
///
/// Retrieves the author who submitted affidavit keys, tied to a specific session.
///
/// - Authenticate offchain submissions (affidavits) for the upcoming session.
/// - Ensure that only valid authors can participate in elections or submit weights.
/// - Maintain session-specific separation, so keys do not persist beyond their intended session.
///
/// ## Storage Structure
/// - [`SessionIndex`]: the session for which the keys are valid.
/// - [`AffidavitId`]: the actual affidavit public key ID, type chosen by
/// the runtime configuration [`Config::AffidavitCrypto`].
/// - [`AuthorOf<T>`]: the author who owns the key-pairs for signing.
#[pallet::storage]
pub type AffidavitKeys<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, SessionIndex>,
NMapKey<Blake2_128Concat, AffidavitId<T>>,
),
AuthorOf<T>,
OptionQuery,
>;
/// **Tracks the author who prepared the election for a given session**.
///
/// Stores the identity of the election runner and the block number at which
/// they executed the election process for the **upcoming session**.
///
/// This storage is **tied to the session index** and may be **overwritten**
/// if multiple election runs occur within the same session.
/// This ensures that the latest election runner and block number are always recorded.
///
/// This allows the pallet to:
/// - Identify which author acted as the election runner for auditing or reward purposes.
/// - Record the exact block when the election was conducted, ensuring deterministic session transitions.
/// - Keep track of the most recent election preparation for the session.
///
/// ## Storage Structure
/// - [`SessionIndex`]: the session for which the election was prepared.
/// - ([`AuthorOf`], [`BlockNumberFor`]): tuple of the election runner and the block number of execution.
/// - [`OptionQuery`]: returns `None` if no election has been prepared for the session or yet.
#[pallet::storage]
pub type ElectsPreparedBy<T: Config> = StorageMap<
_,
Blake2_128Concat,
SessionIndex,
(AuthorOf<T>, BlockNumberFor<T>),
OptionQuery,
>;
/// Transaction priority for the [`Pallet::validate`] extrinsic.
///
/// Used because `validate` is an **unsigned extrinsic** that carries a
/// signed payload, rather than relying on a conventional signed origin.
///
/// This extrinsic **is propagated to other peers** and participates in
/// normal transaction pool ordering, so its priority directly affects
/// inclusion and ordering behavior.
#[pallet::storage]
pub type ValidateTxPriority<T: Config> = StorageValue<_, TransactionPriority, ValueQuery>;
/// Transaction priority for the [`Pallet::elect`] extrinsic.
///
/// This extrinsic is **submitted locally by an offchain worker** and
/// **not propagated to other peers** via the transaction pool.
///
/// The priority therefore only affects **local block construction**
/// and ordering relative to other locally submitted transactions.
#[pallet::storage]
pub type ElectionTxPriority<T: Config> = StorageValue<_, TransactionPriority, ValueQuery>;
/// Transaction priority for the [`Pallet::declare`] extrinsic.
///
/// Controls the relative importance of affidavit submissions in the
/// transaction pool.
///
/// This extrinsic **is propagated to other peers**, so its priority
/// influences network-wide inclusion and ordering behavior.
#[pallet::storage]
pub type AffidavitTxPriority<T: Config> = StorageValue<_, TransactionPriority, ValueQuery>;
/// Wall-clock delay (in timestamp units) that must elapse after the
/// first observation of a value before it becomes eligible to
/// strengthen its confidence signal.
///
/// Measured from the timestamp of the initial observation:
///
/// `current_timestamp >= first_observation_timestamp + FinalityAfter`
///
/// This acts as a stability window to prevent immediate confidence
/// escalation for newly observed values.
///
/// ### Note
/// - Must be strictly greater than zero.
/// - Should be large enough to tolerate short-lived forks.
#[pallet::storage]
pub type FinalityAfter<T: Config> = StorageValue<_, Moment<T>, ValueQuery>;
/// Number of distinct block observations required *after* the
/// [`FinalityAfter`] window has elapsed in order to strengthen
/// the confidence signal of a value.
///
/// Observations are block-scoped:
/// - At most one observation per block is counted.
/// - Multiple observations within the same block do not increase the count.
///
/// A value may strengthen its confidence only when:
/// 1. The [`FinalityAfter`] delay has elapsed, and
/// 2. It has been observed in at least `FinalityTicks`
/// distinct blocks thereafter.
///
/// ### Note
/// - Must be strictly greater than zero.
/// - Larger values increase fork tolerance but delay confidence.
#[pallet::storage]
pub type FinalityTicks<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
// ===============================================================================
// ```````````````````````````````````` ERROR ````````````````````````````````````
// ===============================================================================
#[pallet::error]
pub enum Error<T> {
/// The requested affidavit-ready author was not found.
///
/// This may happen if:
/// - The author has not declared readiness for validation via
/// `validate` extrinsic
/// - The author has not declared affidavit keys for the upcoming session
/// - The provided affidavit key is invalid
AffidavitAuthorNotFound,
/// Block production points for the specified author were not found.
BlockPointsNotFound,
/// The author has exhausted the maximum allowed block production points
/// for the current session.
///
/// Consider scaling the points type or constraining accumulation
/// according to block production frequency.
BlockPointsExhausted,
/// The specified author has not submitted an affidavit
/// for the upcoming session.
AffidavitNotFound,
/// Affidavit submissions are not enabled by configuration.
AffidavitsNotAllowed,
/// The affidavit submission window for the upcoming session
/// has not started yet in the current session.
NotAffidavitPeriod,
/// The affidavit submission window for the upcoming session has ended.
///
/// The author must wait for the next session's affidavit period.
AffidavitPeriodEnded,
/// The election period for the upcoming session
/// has not started yet in the current session.
NotElectionPeriod,
/// Invalid affidavit configuration.
///
/// `AffidavitBeginsAt` must be less than or equal to `AffidavitEndsAt`.
InvalidAffidavitPeriod,
/// The election period for the upcoming session has ended.
///
/// The author must wait for the next session's election period.
ElectionPeriodEnded,
/// The author has not registered ownership of the given affidavit key.
///
/// The key itself may be valid, but it does not belong to the author.
AuthorNotAffidavitOwner,
/// Failed to query the session ID for the author.
///
/// This usually indicates that the author does not hold
/// an active author role.
SessionIdQueryFailed,
/// The author cannot chill immediately because they are
/// an elected validator in the current session.
ValidatorCannotChill,
/// The author cannot chill immediately because they have submitted
/// an affidavit and are a candidate for election.
CandidateCannotChill,
/// The author cannot chill immediately because they are elected
/// for the upcoming session.
ElectedCannotChill,
/// An active affidavit key already exists in the node's local keystore.
///
/// No new key generation is required. If the node has a valid author role,
/// it may already be ready for `validate` extrinsic.
///
/// Or if the author is ready to declare affidavit he is eligible to do so.
AffidavitKeyExists,
/// A next-session affidavit key already exists in the node's local keystore.
///
/// An affidavit declaration is ready to be posted and the key
/// is ready for rotation.
NextAffidavitKeyExists,
/// Failed to sign the affidavit submission extrinsic payload
/// using the active affidavit key.
CannotSignAffidavitTxPayload,
/// Failed to construct and sign validate payload
/// using the active affidavit key.
CannotSignValidateTxPayload,
/// The node is expected to hold an active affidavit key, but none was found.
///
/// This indicates an inconsistency between earlier logic and current storage.
/// The OCW will retry, but persistent failure suggests storage corruption.
ExpectedToHoldActiveAffidavitKey,
/// The node is expected to not hold a active affidavit key in offchain storage,
/// but it is available.
///
/// This indicates an inconsistency between earlier logic and current storage.
/// The OCW will retry, but persistent failure suggests storage corruption.
ExpectedToNotHoldActiveAffidavitKey,
/// The node is expected to hold the next affidavit key during
/// the key-rotation lifecycle, but it is missing.
///
/// This indicates an inconsistency between earlier logic and current storage.
/// The OCW will retry, but persistent failure suggests storage corruption.
ExpectedToHoldNextAffidavitKey,
/// The node is expected to hold a finalized next affidavit key
/// in offchain storage, but it is missing.
///
/// This indicates an inconsistency between earlier logic and current storage.
/// The OCW will retry, but persistent failure suggests storage corruption.
ExpectedToHoldFinalizedNextAffidavitKey,
/// An offchain storage operation failed.
///
/// The OCW halts further decisions for safety.
/// Thus, re-runs in next block execution.
OCWStorageDecisionHalt,
/// The offchain worker failed to submit the affidavit extrinsic
/// for unknown reasons.
CannotSubmitAffidavitTx,
/// Extrinsic submission for declaring an affidavit failed.
FailedToDeclareAffidavit,
/// The election period for the upcoming session
/// has not started yet.
YetToElectAuthors,
/// Failed to sign the election extrinsic payload using
/// the very recently rotated affidavit key.
///
/// Subsequent OCW executions at next block shall attempt again.
CannotSignElectionTxPayload,
/// The offchain worker failed to submit the election extrinsic
/// for unknown reasons.
///
/// Subsequent OCW executions at next block shall attempt again.
CannotSubmitElectionTx,
/// Extrinsic submission for electing authors failed.
///
/// Subsequent OCW executions at next block shall attempt again.
ExtrinsicFailedToElectAuthors,
/// A new affidavit key was generated but failed to persist locally.
///
/// The OCW will attempt another affidavit submission with a new key.
///
/// Persistent failure indicates storage corruption.
SetNewAffidavitKeyFailed,
/// A new affidavit key for rotation and promotion as active
/// affidavit key was generated but failed to persist locally.
///
/// The OCW will attempt another affidavit key-rotation with a new key.
///
/// Persistent failure indicates storage corruption.
SetNextAffidavitKeyFailed,
/// The active affidavit key is expected in the local keystore
/// but could not be found.
///
/// Recovery requires regenerating the key under the configured
/// `KeyTypeId` or chilling and restarting validation.
ExpectedActiveAffidavitKeyPairNotFound,
/// The rotated next affidavit key is expected in the local keystore
/// but could not be found.
///
/// Recovery requires regenerating the key under the configured
/// `KeyTypeId` or chilling and restarting validation.
ExpectedNextAffidavitKeyPairNotFound,
/// Validation has been stopped due to affidavit key rotation failure,
/// storage corruption, or failed submissions.
///
/// Manual re-validation via `validate` extrinsic is required.
ValidationStopped,
/// The author is actively validating in the current session.
///
/// The `chill` extrinsic is blocked until validation completes
/// or the session ends.
ActivelyValidating,
/// The author has submitted an affidavit and is actively
/// participating in the election.
///
/// The author may `chill` if allowed or wait until
/// the election concludes to check assigned duty.
ActivelyContestingElection,
/// The author has been elected for the upcoming session
/// and is preparing for validation duties.
///
/// The `chill` extrinsic is blocked until duties complete.
ActivelyWarmingForValidation,
/// The author is detected as active, but the specific duty
/// cannot be determined due to inconsistent state.
///
/// The `chill` extrinsic may be attempted to resolve the state.
CannotDetermineAuthorActiveDuty,
/// Offchain storage Active Affidavit Key is not yet finalized.
///
/// The key exists optimistically in fork-aware storage, but the block
/// containing the finalized value may still be subject to re-org.
/// Until finalized, speculative forks may observe different values.
///
/// Until it is finalized subsequent OCWs may result in this state.
ActiveAfdtKeyNotYetFinalized,
/// Failed to decode the finalized Active Affidavit Key public key value
/// from persistent offchain storage.
///
/// Persistent failure indicates either storage corruption or a type
/// mismatch. Manual intervention may be required. Clearing both
/// fork-aware and persistent offchain storage allows OCWs to
/// reinitialize the key lifecycle.
ActiveAfdtKeyFinalizedValueDecodeFail,
/// Failed to decode the speculative hash of the Active Affidavit Key
/// public key from fork-aware offchain storage.
///
/// This hash is used to reference the actual value stored in
/// persistent offchain storage. Persistent failure indicates
/// corruption or decoding inconsistencies.
/// Clearing both fork-aware and persistent storage may resolve it.
ActiveAfdtKeySpeculativeHashDecodeFail,
/// Concurrent mutation detected while accessing the finalized
/// Active Affidavit Key public key value.
///
/// The operation will be retried by the OCW. Persistent failure
/// indicates a potential deadlock or storage corruption.
/// Clearing both fork-aware and persistent offchain storage
/// may be required.
ActiveAfdtKeyFinalizedValueConcurrentMutation,
/// Concurrent mutation detected while accessing the speculative
/// hash of the Active Affidavit Key public key.
///
/// The hash resides in fork-aware storage while the actual value
/// exists in persistent storage. The operation will be retried
/// by the OCW. Persistent failure indicates storage corruption
/// or a deadlock condition.
ActiveAfdtKeySpeculativeHashConcurrentMutation,
/// A finalized Active Affidavit Key public key value exists in
/// persistent offchain storage without a corresponding
/// fork-aware hash.
///
/// This results in a hanging value with no canonical reference.
/// The persistent value will be cleared automatically. Any
/// remaining fork-aware entries may also become hanging and
/// will be cleaned on access.
ActiveAfdtKeyFinalizedHangingValue,
/// A speculative fork-aware hash for the Active Affidavit Key exists
/// without a corresponding persistent public key value.
///
/// Since the actual value cannot be recovered, the hanging
/// speculative hash will be cleared automatically.
ActiveAfdtKeySpeculativeHangingHash,
/// Offchain storage Next Affidavit Key is not yet finalized.
///
/// The key exists optimistically in fork-aware storage, but the block
/// containing the finalized value may still be subject to re-org.
/// Until finalized, speculative forks may observe different values.
///
/// Until it is finalized subsequent OCWs may result in this state.
NextAfdtKeyNotYetFinalized,
/// Failed to decode the finalized Next Affidavit Key public key value
/// from persistent offchain storage.
///
/// Persistent failure indicates either storage corruption or a type
/// mismatch. Manual intervention may be required. Clearing both
/// fork-aware and persistent offchain storage allows OCWs to
/// reinitialize the key lifecycle.
NextAfdtKeyFinalizedValueDecodeFail,
/// Failed to decode the speculative hash of the Next Affidavit Key
/// public key from fork-aware offchain storage.
///
/// This hash is used to reference the actual value stored in
/// persistent offchain storage. Persistent failure indicates
/// corruption or decoding inconsistencies.
/// Clearing both fork-aware and persistent storage may resolve it.
NextAfdtKeySpeculativeHashDecodeFail,
/// Concurrent mutation detected while accessing the finalized
/// Next Affidavit Key public key value.
///
/// The operation will be retried by the OCW. Persistent failure
/// indicates a potential deadlock or storage corruption.
/// Clearing both fork-aware and persistent offchain storage
/// may be required.
NextAfdtKeyFinalizedValueConcurrentMutation,
/// Concurrent mutation detected while accessing the speculative
/// hash of the Next Affidavit Key public key.
///
/// The hash resides in fork-aware storage while the actual value
/// exists in persistent storage. The operation will be retried
/// by the OCW. Persistent failure indicates storage corruption
/// or a deadlock condition.
NextAfdtKeySpeculativeHashConcurrentMutation,
/// A finalized Next Affidavit Key public key value exists in
/// persistent offchain storage without a corresponding
/// fork-aware hash.
///
/// This results in a hanging value with no canonical reference.
/// The persistent value will be cleared automatically. Any
/// remaining fork-aware entries may also become hanging and
/// will be cleaned on access.
NextAfdtKeyFinalizedHangingValue,
/// A speculative fork-aware hash for the Next Affidavit Key exists
/// without a corresponding persistent public key value.
///
/// Since the actual value cannot be recovered, the hanging
/// speculative hash will be cleared automatically.
NextAfdtKeySpeculativeHangingHash,
/// The affidavit submission extrinsic has been sent by the OCW
/// and is awaiting on-chain state confirmation and key rotation.
AffidavitTxAwaitingStatus,
/// Not an error.
///
/// Indicates that a neccessary election attempt was made early,
/// so the OCW will proceed with affidavit submission instead.
ProceedingToAffidavitSubmission,
/// Affidavit submission was declined because the author
/// has already rotated keys for the next session.
///
/// The author must wait for the next affidavit window.
DeclareDuringNextAffidavitSession,
/// An affidavit is declared and the key is rotated before the
/// current affidavit submission period itself.
DeclaredBeforeAffidavitPeriod,
/// The given affidavit key is not the recently rotated affidavit key,
/// from the recently declared affidavit.
///
/// This implies the author have declared their affidavit and have rotated
/// a new key for the the election after the upcoming election.
InvalidRotatedAffidavitKey,
/// The requested block author of this very current block is not available.
BlockAuthorNotFound,
/// An election is attempted by a non-block author. Elections can only be
/// processed by block-authors only in their authored blocks only.
TriedElectingByNonBlockAuthor,
/// The active affidavit key is utilized for affidavit-declaration and
/// not for processing election.
///
/// Election can only be processed by recently rotated affidavit key, which
/// poses for the next affidavit-declaration session also.
///
/// All these can be valid only if the author started validating, else its
/// a dormant affidavit key
AffidavitKeyForDeclaration,
/// The provided value must be non-zero.
///
/// Returned when a parameter or input is required to be strictly
/// greater than zero.
ValueCannotBeZero,
/// Internal success signal for the affidavit key initialization routine.
///
/// Used to indicate successful execution of the initialization flow.
InitAffidavitKeyRoutineSuccess,
/// Internal success signal for the election execution routine.
///
/// Indicates that the election process completed successfully.
TryElectionRoutineSuccess,
/// Internal success signal for the affidavit declaration routine.
///
/// Indicates that the affidavit has been successfully declared.
DeclarAffidavitRoutineSuccess,
/// Internal success signal for the affidavit key rotation routine.
///
/// Indicates that the key rotation process completed successfully.
RotateAffidavitKeyRoutineSuccess,
/// The author is already in a chilled (inactive) state.
///
/// Returned when attempting to chill an author that is already inactive.
AuthorAlreadyChilling,
/// Authors are successfully elected, but cannot be revealed for
/// some reasons unknown.
ElectedButCannotReveal,
/// Author declared an affidavit, but it could not be retrieved
/// for reasons unknown.
DeclaredAffidavitNotFound,
/// The caller is not the current block author.
///
/// Returned when an operation requires block authorship,
/// but the caller does not match the current block author.
NotABlockAuthor,
/// No public key matching the given affidavit identifier was found
/// in the node-local keystore.
///
/// The key may have been lost, never generated on this node, or
/// the identifier does not correspond to any locally held key pair.
AfdtPublicKeyNotFound,
/// No affidavit key is registered for the author in any relevant
/// future session scope (next session or next affidavit session).
///
/// The author has not called [`Pallet::validate`] or has already chilled.
AffidavitKeyPairNotFound,
/// The election result could not be revealed.
///
/// No election has been executed for the current session, or the
/// underlying election manager returned no result.
UnableToRevealElected,
/// The fork graph has reached the maximum number of concurrent forks.
///
/// No new sibling branch can be created until an existing fork is
/// resolved or pruned. This indicates an unusually high degree of
/// chain instability relative to the configured `MAX_FORKS` constant.
MaxOCWForksAttained,
/// Fork-aware offchain storage was accessed before the fork graph
/// was initialized via `ForksHandler::start`.
OCWForksNotEnabled,
/// The fork graph is in an inconsistent state.
///
/// An internal invariant was violated, such as a branch entry that
/// cannot be decoded or a divider that references a non-existent branch.
/// Persistent failure indicates offchain storage corruption.
OCWForksInconsistent,
}
// ===============================================================================
// ```````````````````````````````````` EVENTS ```````````````````````````````````
// ===============================================================================
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Emitted when an election attempt fails.
ElectionAttemptFailed {
session: SessionIndex,
error: DispatchError,
runner: AuthorOf<T>,
},
/// Emitted after a successful election instance.
ElectedInstance {
session: SessionIndex,
runner: AuthorOf<T>,
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
elects: ElectionElects<T>,
},
/// Emitted after a reward is successfully delegated to be
/// applied to an author via [`CompensateRoles`].
RewardInitiated {
author: AuthorOf<T>,
value: AssetOf<T>,
},
/// Emitted when rewarding an author via [`CompensateRoles`] fails.
RewardFailed {
author: AuthorOf<T>,
error: DispatchError,
},
/// Emitted after a penalty is successfully delegated to be
/// applied to an author via [`CompensateRoles`].
PenaltyInitiated {
author: AuthorOf<T>,
penalty: PenaltyRatio,
},
/// Emitted when applying a penalty to an author via
/// [`CompensateRoles`] fails.
PenaltyFailed {
author: AuthorOf<T>,
error: DispatchError,
},
/// Emitted after a successful affidavit submission for the
/// election to be conducted for the upcoming session.
AffidavitSubmitted {
afdt_id: AffidavitId<T>,
session: SessionIndex,
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
author: AuthorOf<T>,
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
affidavit: ElectionVia<T>
},
/// Emitted when an author successfully declares their affidavit signing
/// key for the next session
ValidationBegins {
author: AuthorOf<T>,
for_session: SessionIndex
},
/// Emitted when an author successfully initiates the chilling process
/// by removing their affidavit key for a future session.
ChillingBegins {
author: AuthorOf<T>,
for_session: SessionIndex
},
/// Emitted by [`Pallet::inspect_affidavit`] for direct inspection of a
/// stored affidavit and its declared election weights.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
InspectAffidavit {
author: AuthorOf<T>,
afdt_id: AffidavitId<T>,
session: SessionIndex,
affidavit: ElectionVia<T>
},
/// Emitted by [`Pallet::inspect_elects`] for direct inspection of the
/// currently revealed elected author set.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
InspectElects {
elects: ElectionElects<T>
},
/// Emitted by [`Pallet::prepare_validation_payload`] exposing the signed
/// payload and signature required to submit a [`Pallet::validate`] extrinsic.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
InspectValidatePayload {
payload: ValidatePayloadOf<T>,
signature: T::Signature,
},
/// A genesis config parameter was updated forcefully.
GenesisConfigUpdated(ForceGenesisConfig<T>),
}
// ===============================================================================
// ```````````````````````````````````` HOOKS ````````````````````````````````````
// ===============================================================================
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
/// Offchain Worker entry point coordinating affidavit lifecycle and elections.
///
/// This function acts as a **deterministic orchestrator** for a sequence of
/// structured offchain routines, executed once per block in best-effort mode.
/// It does not implement business logic itself; instead, it delegates all
/// responsibility to well-defined [`Routines`] and [`RoutineOf`] abstractions.
///
/// ## Execution Model
///
/// All routines execute inside [`ForksHandler::start`], which resolves and
/// persists the current fork graph branch before any routine runs.
/// Each routine calls [`Routines::run_service`] directly, followed by
/// [`Routines::on_ran_service`] on success. The routines are executed
/// **imperatively and sequentially** with **fail-fast semantics**:
///
/// 1. Initialize the node-local active affidavit key (if required).
/// 2. Attempt to run the election early (if the election window permits).
/// 3. Declare an affidavit for the upcoming session (if eligible).
/// 4. Rotate affidavit keys for the next session.
///
/// If any routine fails, execution stops immediately for the current block.
/// All failures are already logged by the routine itself; the OCW hook
/// performs no retries, compensation, or error interpretation.
///
/// ## Semantics & Guarantees
/// - **Best-effort execution**: no transactional rollback is assumed.
/// - **Idempotent by design**: repeated execution across blocks or forks is safe.
/// - **Authorization-aware**: each routine explicitly determines its authorized
/// signer via [`RoutineOf::who`] before execution.
/// - **Fork-safe**: correctness is preserved across re-orgs through
/// fork-aware ([`frame_suite::ForkAware`]) and
/// finalized ([`frame_suite::Finalized`]) offchain
/// storage semantics.
///
/// ## Notes
/// - This function intentionally returns early on failure.
/// - All observability is provided via structured logging inside routines.
/// - Progress is achieved through repeated OCW invocations over time.
fn offchain_worker(block: BlockNumberFor<T>) {
<Pallet<T> as ForksHandler<T, ForkLocalDepot>>::start(None, None, ||{
//------ Initiate Affidavit Key ---------
let init = InitAffidavitKey { at: block };
let Ok(_) =
<InitAffidavitKey<T> as Routines<BlockNumberFor<T>>>::run_service(&init) else {
return;
};
<InitAffidavitKey<T> as Routines<BlockNumberFor<T>>>::on_ran_service(&init);
//------ Try Electing Authors Early ---------
let Ok(new_afdt_key) =
<TryElection<T> as RoutineOf<T::Public, BlockNumberFor<T>>>::who(&block) else {
return;
};
let election = TryElection {
by: new_afdt_key,
at: block,
};
let Ok(_) =
<TryElection<T> as Routines<BlockNumberFor<T>>>::run_service(&election) else {
return;
};
<TryElection<T> as Routines<BlockNumberFor<T>>>::on_ran_service(&election);
//------ Declare Affidavit ---------
let Ok(afdt_key) =
<DeclareAffidavit<T> as RoutineOf<T::Public, BlockNumberFor<T>>>::who(&block) else {
return;
};
let declare = DeclareAffidavit {
by: afdt_key,
at: block,
};
let Ok(_) =
<DeclareAffidavit<T> as Routines<BlockNumberFor<T>>>::run_service(&declare) else {
return;
};
<DeclareAffidavit<T> as Routines<BlockNumberFor<T>>>::on_ran_service(&declare);
//------ Rotate Affidavit Keys ---------
let Ok(next_afdt_key) =
<RotateAffidavitKey<T> as RoutineOf<T::Public, BlockNumberFor<T>>>::who(&block) else {
return;
};
let rotate = RotateAffidavitKey {
by: next_afdt_key,
at: block,
};
let Ok(_) =
<RotateAffidavitKey<T> as Routines<BlockNumberFor<T>>>::run_service(&rotate) else {
return;
};
<RotateAffidavitKey<T> as Routines<BlockNumberFor<T>>>::on_ran_service(&rotate);
});
}
/// Called at the beginning of each block.
///
/// Awards block production points to the current block author.
fn on_initialize(_block: BlockNumberFor<T>) -> Weight {
// Try to get the current block author from the authorship pallet
let Some(author) = pallet_authorship::Pallet::<T>::author() else {
// If no author is found (weight for 1 read operation),
return T::DbWeight::get().reads(1);
};
// Increment the block points for the author.
// Ignoring errors here, as missing role checks or exhausted points are handled elsewhere.
let _ = <Pallet<T> as AuthorPoints<AuthorOf<T>, T::Points>>::add_point(&author);
<T as Config>::WeightInfo::on_initialize_with_author()
}
}
// ===============================================================================
// `````````````````````````````````` EXTRINSICS `````````````````````````````````
// ===============================================================================
#[pallet::call]
impl<T: Config> Pallet<T> {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ```````````````````````````````` DISPATCHABLES ````````````````````````````````
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Register an author's new **affidavit signing key** for the upcoming session's
/// participation as a validator.
///
/// This extrinsic allows an author to declare their **off-chain signing key** that
/// will be used to sign affidavits for the next session's election.
///
/// It ensures that only valid and available authors can register keys.
///
/// ## Notes
/// - Affidavit Keys are session-specific and are updated each session.
/// - This extrinsic allows submission of affidavit for next session only.
/// - Affidavit Declaration/Submission will rotate keys once every submission
/// for further sessions then.
///
/// ## Errors
/// Returns a `DispatchError` if author-role authorization fails.
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::validate())]
pub fn validate(
origin: OriginFor<T>,
payload: ValidatePayloadOf<T>,
// Signature verification happens via `ValidateUnsigned::validate::unsigned`
// can avoid here
_signature: T::Signature,
) -> DispatchResult {
// Verify signed origin i.e., author
let author = ensure_signed(origin)?;
// Ensure the author exists and is available in the role system
<T::RoleAdapter as RoleManager<AuthorOf<T>>>::role_exists(&author)?;
<T::RoleAdapter as RoleManager<AuthorOf<T>>>::is_available(&author)?;
// Compute the session for which the key is valid
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
let public = SignedPayload::<T>::public(&payload);
let affidavit_pub: AffidavitId<T> = public.clone().into_account().into();
// Store the key for the upcoming session
AffidavitKeys::<T>::insert((for_session, affidavit_pub), author.clone());
Self::deposit_event(Event::<T>::ValidationBegins { author, for_session });
Ok(())
}
/// Submit an **affidavit for the upcoming session election**.
///
/// This extrinsic allows an author to declare their election weights
/// (affidavit) for the next session. It also rotates the author's signing
/// key for the subsequent affidavit.
///
/// ## Parameters
/// - `origin`: Must be a signed account corresponding to the author
/// submitting the affidavit.
/// - `payload`: The payload that was signed off-chain representing the
/// affidavit data.
/// - `signature`: The author's signature of the payload, used for verification.
/// - `new_key`: A new affidavit signing key to replace the current one for the
/// next upcoming session.
///
/// ## Notes
/// - Affidavit submissions are session-specific.
/// - Key rotation ensures authors maintain fresh signing keys for security.
/// - Only validated and available authors can submit affidavits.
///
/// ## Errors
/// Returns a `DispatchError` if un-privileged to submit an affidavit.
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::declare())]
pub fn declare(
origin: OriginFor<T>,
payload: AffidavitPayloadOf<T>,
// Signature verification happens via `ValidateUnsigned::validate::unsigned`
// can avoid here
_signature: T::Signature,
) -> DispatchResult {
ensure_none(origin)?;
let public = SignedPayload::<T>::public(&payload);
let new_affidavit_pub = payload.rotate.clone();
let affidavit_pub: AffidavitId<T> = public.clone().into_account().into();
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
// Ensure author has a registered key for the upcoming session
let author = AffidavitKeys::<T>::get((for_session, &affidavit_pub))
.ok_or(Error::<T>::AffidavitAuthorNotFound)?;
// Process the affidavit
<Pallet<T> as ElectionAffidavits<AffidavitId<T>, ElectionVia<T>>>::process_affidavit(
&affidavit_pub.clone(),
)?;
// Rotate key for the next affidavit
AffidavitKeys::<T>::insert(
(
for_session.saturating_add(One::one()),
new_affidavit_pub.clone(),
),
&author,
);
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
{
if !T::EmitEvents::get() {
let block = frame_system::Pallet::<T>::block_number();
let Ok(affidavit) = Self::get_affidavit(&affidavit_pub) else {
debug_assert!(
false,
"author declared affidavit for session {:?} at block {:?}, but it could not be retrieved",
for_session, block
);
return Err(Error::<T>::DeclaredAffidavitNotFound.into());
};
Self::deposit_event(Event::<T>::AffidavitSubmitted {
afdt_id: affidavit_pub,
session: for_session,
author,
affidavit,
});
}
}
#[cfg(not(any(feature = "dev", feature = "runtime-benchmarks")))]
{
if !T::EmitEvents::get() {
Self::deposit_event(Event::<T>::AffidavitSubmitted {
afdt_id: affidavit_pub,
session: for_session,
});
}
}
Ok(())
}
/// Execute the election for the upcoming session.
///
/// This extrinsic allows an author to act as the **election runner**
/// for the election session (next-session). It verifies the author's
/// affidavit-based signature, prepares the election using all submitted
/// affidavits, and records the runner for audit and reward attribution.
///
/// Since this is an **unsigned extrinsic**, it is constructed and
/// submitted by validator offchain workers (OCWs).
///
/// Although unsigned, it is treated as a **pseudo-inherent**:
/// - It is authorized via affidavit signature verification
/// - It may carry rewards for successfully running the election
/// - It is **expected** to be submitted locally by validators rather
/// than propagated by external transaction authors
///
/// ## Errors
/// Returns a `DispatchError` if election execution or authorization fails.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::elect())]
pub fn elect(
origin: OriginFor<T>,
payload: ElectionPayloadOf<T>,
// Signature verification happens via `ValidateUnsigned`
// can avoid here
_signature: T::Signature,
) -> DispatchResult {
ensure_none(origin)?;
// Determine the session for which this election applies (next session)
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
let public = SignedPayload::<T>::public(&payload);
let affidavit_pub: AffidavitId<T> = public.clone().into_account().into();
// Ensure the author has a valid affidavit key registered
// Election keys are registered for session+2 because:
// - Current session: ongoing
// - Next session: affidavits are submitted
// - Session after next: election is executed
// Hence authors who submitted affidavits, submit next election key, hence
// queriable.
// This makes only authors who submitted affidavits to run election
let author = AffidavitKeys::<T>::get((
for_session.saturating_add(One::one()),
&affidavit_pub.clone(),
))
.ok_or(Error::<T>::AffidavitAuthorNotFound)?;
let block_author =
pallet_authorship::Pallet::<T>::author().ok_or(Error::<T>::BlockAuthorNotFound)?;
// This ensures authors who have bypassed `ValidateUnsigned` via
// `propagate = false` for `elect` unsigned extrinsic
// shall be captured by the runtime itself
ensure!(
author == block_author,
Error::<T>::TriedElectingByNonBlockAuthor
);
// Run the election preparation logic
if let Err(error) = Internals::<T>::prepare_election(&Some(author.clone())) {
if !T::EmitEvents::get() {
Self::deposit_event(Event::<T>::ElectionAttemptFailed {
session: for_session,
runner: author.clone(),
error,
});
}
return Err(error);
};
// Record the election runner and the block at which the election was conducted
let current_block = frame_system::Pallet::<T>::block_number();
ElectsPreparedBy::<T>::insert(for_session, (&author, current_block));
#[cfg(not(any(feature = "dev", feature = "runtime-benchmarks")))]
{
if !T::EmitEvents::get() {
Self::deposit_event(Event::<T>::ElectedInstance {
session: for_session,
runner: author,
});
}
}
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
{
if !T::EmitEvents::get() {
let Some(elects) = Internals::<T>::reveal() else {
debug_assert!(
false,
"authors elected for session {:?} at
block {:?} by election runner {:?},
but reveal unavailable",
for_session, current_block, &author
);
return Err(Error::<T>::ElectedButCannotReveal.into());
};
Self::deposit_event(Event::<T>::ElectedInstance {
session: for_session,
runner: author,
elects,
});
}
}
Ok(())
}
/// Request to **step back or "chill" immediately from election participation**
/// by erasing affidavit keys.
///
/// This safely avoids penalties by pausing an author's duties.
///
/// This extrinsic allows an author to withdraw from participating in upcoming
/// elections or prevent submitting future affidavits. The actual effect
/// depends on the **current block** relative to the **affidavit submissions
/// and election windows**.
///
/// Note that its always advised to `chill` validation before `resign` author role
/// to skip unnecessary invalid affidavit declarations.
///
/// ## Parameters
/// - `origin`: Must be a signed account corresponding to the author i.e.,
/// controller/role account.
/// - `affidavit_pub` : Public affidavit key registered for a new session's
/// affidavit submission.
///
/// ## Notes
/// - Removing affidavit keys ensures authors cannot unfairly influence
/// future elections.
/// - By inspecting returned errors, callers can **compute the optimal
/// chill window**.
///
/// ## Errors
/// Returns a `DispatchError` with diagnostic in case of irrevocable
/// duties assigned.
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::chill())]
pub fn chill(origin: OriginFor<T>, affidavit_pub: AffidavitId<T>) -> DispatchResult {
let author = ensure_signed(origin)?;
Self::can_chill(author.clone(), affidavit_pub.clone())?;
let current_session = CurrentSession::<T>::get();
let next_session = current_session.saturating_add(One::one());
let next_afdt_session = next_session.saturating_add(One::one());
// If rotated key exists, remove it.
if AffidavitKeys::<T>::contains_key((next_afdt_session, &affidavit_pub)) {
AffidavitKeys::<T>::remove((next_afdt_session, &affidavit_pub));
Self::deposit_event(Event::<T>::ChillingBegins { author, for_session: next_afdt_session });
return Ok(());
}
// Otherwise remove next-session key if it still exists.
if AffidavitKeys::<T>::contains_key((next_session, &affidavit_pub)) {
AffidavitKeys::<T>::remove((next_session, &affidavit_pub));
}
Self::deposit_event(Event::<T>::ChillingBegins { author, for_session: next_session });
Ok(())
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ````````````````````````````````` INSPECTORS ``````````````````````````````````
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Emit the currently revealed elected author set as an event for inspection.
///
/// This is a **read-only convenience extrinsic** that does not mutate any state.
/// It retrieves the election result from the underlying election manager via
/// [`Pallet::get_elects`] and emits it as an [`Event::InspectElects`] event.
///
/// ## Notes
/// - Gated by the `dev` feature. Must not be included in production runtimes.
/// - Fails if no election result is available, i.e. no election has been
/// executed or the result cannot be revealed.
///
/// ## Errors
/// Returns [`Error::UnableToRevealElected`] if the election result is unavailable.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::inspect_elects())]
pub fn inspect_elects(
origin: OriginFor<T>,
) -> DispatchResult {
ensure_signed(origin)?;
let elects = Self::get_elects()?;
Self::deposit_event(Event::InspectElects { elects });
Ok(())
}
/// Construct and emit a signed [`ValidatePayload`] and its signature as an event.
///
/// This is a **read-only convenience extrinsic** that does not mutate any on-chain state.
/// It is intended to support the [`Self::validate`] extrinsic workflow by producing
/// the signed payload and signature required to call it.
///
/// Since [`Self::validate`] accepts both a signed origin and an unsigned payload,
/// callers need a way to obtain a correctly signed payload before submitting.
/// This extrinsic bridges that gap by performing the signing on behalf of the
/// local node and emitting the result as an [`Event::InspectValidatePayload`] event.
///
/// ## Execution Model
/// This extrinsic reads from **node-local offchain storage** to retrieve the
/// active affidavit key. It is therefore **client-specific**: the result reflects
/// the state of the validator node executing the call, and may differ across nodes.
///
/// ## Notes
/// - Gated by the `dev` feature. Must not be included in production runtimes.
/// - The emitted payload and signature can be submitted directly to [`Self::validate`].
/// - Requires that the node holds a finalized active affidavit key in offchain storage.
///
/// ## Errors
/// Returns a `DispatchError` if the active affidavit key is not finalized,
/// not found in the local keystore, or signing fails.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::prepare_validation_payload())]
pub fn prepare_validation_payload(
origin: OriginFor<T>,
) -> DispatchResult {
ensure_signed(origin)?;
let (payload, signature) = Self::sign_validate_payload()?;
Self::deposit_event(Event::InspectValidatePayload { payload, signature });
Ok(())
}
/// Emit the stored affidavit for a given affidavit identifier as an event.
///
/// This is a **read-only convenience extrinsic** that does not mutate any state.
/// It retrieves the affidavit associated with the provided [`AffidavitId`] from
/// storage and emits it as an [`Event::InspectAffidavit`] event, making the
/// affidavit weights observable without requiring direct storage queries.
///
/// The retrieved affidavit corresponds to the **upcoming session's election**
/// (current session index + 1).
///
/// ## Notes
/// - Gated by the `dev` feature. Must not be included in production runtimes.
/// - Useful for verifying that a previously submitted affidavit was stored correctly
/// before the election window opens.
///
/// ## Errors
/// Returns [`Error::AffidavitAuthorNotFound`] if no author is mapped to the given key,
/// or [`Error::AffidavitNotFound`] if no affidavit has been submitted for that author.
#[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
#[pallet::call_index(6)]
#[pallet::weight(<T as Config>::WeightInfo::inspect_affidavit())]
pub fn inspect_affidavit(
origin: OriginFor<T>,
afdt_id: AffidavitId<T>,
) -> DispatchResult {
let author = ensure_signed(origin)?;
let affidavit = Self::get_affidavit(&afdt_id)?;
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
Self::deposit_event(Event::InspectAffidavit { author, session: for_session, afdt_id, affidavit });
Ok(())
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ``````````````````````````````` ROOT PRIVILEGED ```````````````````````````````
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Force-update a selected genesis configuration parameter.
///
/// **Origin:** Root only.
///
/// This extrinsic allows privileged modification of runtime parameters
/// that were originally defined at genesis.
///
/// - `AllowAffidavits` - Enables or disables affidavit submission.
/// - `AffidavitBeginsAt` - Updates the start of the affidavit submission window.
/// - `AffidavitEndsAt` - Updates the end of the affidavit submission window.
/// - `ElectionBeginsAt` - Updates when election execution begins within the session.
/// - `ElectionRunnerPointsUpgrade` - Updates the reward points for election runners.
/// - `ValidateTxPriority` - Updates the priority for validation-related extrinsics.
/// - `ElectionTxPriority` - Updates the priority for election execution extrinsics.
/// - `AffidavitTxPriority` - Updates the priority for affidavit submission extrinsics.
/// - `FinalityAfter` - Updates the time-based delay before operations are considered final.
/// - `FinalityTicks` - Updates the block-based confirmation threshold for finality.
///
/// The call enforces consistency constraints where applicable:
/// - Affidavit window ordering:
/// - `AffidavitBeginsAt < AffidavitEndsAt`
/// - `AffidavitEndsAt > AffidavitBeginsAt`
/// - The following values must be non-zero:
/// - transaction priorities
/// - finality thresholds (`FinalityAfter`, `FinalityTicks`)
///
/// This call directly overwrites storage and emits an event containing the
/// updated configuration variant.
#[pallet::call_index(7)]
#[pallet::weight(<T as Config>::WeightInfo::force_allow_affidavits()
.max(<T as Config>::WeightInfo::force_affidavit_begins_at())
.max(<T as Config>::WeightInfo::force_affidavit_ends_at())
.max(<T as Config>::WeightInfo::force_election_begins_at())
.max(<T as Config>::WeightInfo::force_election_runner_points_upgrade())
.max(<T as Config>::WeightInfo::force_validate_tx_priority())
.max(<T as Config>::WeightInfo::force_election_tx_priority())
.max(<T as Config>::WeightInfo::force_affidavit_tx_priority())
.max(<T as Config>::WeightInfo::force_finality_after())
.max(<T as Config>::WeightInfo::force_finality_ticks())
)]
pub fn force_genesis_config(
origin: OriginFor<T>,
field: ForceGenesisConfig<T>,
) -> DispatchResult {
ensure_root(origin)?;
match field {
ForceGenesisConfig::AllowAffidavits(value) => AllowAffidavits::<T>::put(value),
ForceGenesisConfig::AffidavitBeginsAt(aff_begins) => {
ensure!(
aff_begins < AffidavitEndsAt::<T>::get(),
Error::<T>::InvalidAffidavitPeriod
);
AffidavitBeginsAt::<T>::put(aff_begins);
}
ForceGenesisConfig::AffidavitEndsAt(aff_ends) => {
ensure!(
aff_ends > AffidavitBeginsAt::<T>::get(),
Error::<T>::InvalidAffidavitPeriod
);
AffidavitEndsAt::<T>::put(aff_ends);
}
ForceGenesisConfig::ElectionBeginsAt(elect_begins) => {
ElectionBeginsAt::<T>::put(elect_begins);
}
ForceGenesisConfig::ElectionRunnerPointsUpgrade(points) => {
ElectionRunnerPointsUpgrade::<T>::put(points);
}
ForceGenesisConfig::ValidateTxPriority(priority) => {
ensure!(priority > Zero::zero(), Error::<T>::ValueCannotBeZero);
ValidateTxPriority::<T>::put(priority);
}
ForceGenesisConfig::ElectionTxPriority(priority) => {
ensure!(priority > Zero::zero(), Error::<T>::ValueCannotBeZero);
ElectionTxPriority::<T>::put(priority);
}
ForceGenesisConfig::AffidavitTxPriority(priority) => {
ensure!(priority > Zero::zero(), Error::<T>::ValueCannotBeZero);
AffidavitTxPriority::<T>::put(priority);
}
ForceGenesisConfig::FinalityAfter(moment) => {
ensure!(moment > Zero::zero(), Error::<T>::ValueCannotBeZero);
FinalityAfter::<T>::put(moment);
}
ForceGenesisConfig::FinalityTicks(block) => {
ensure!(block > Zero::zero(), Error::<T>::ValueCannotBeZero);
FinalityTicks::<T>::put(block);
}
}
Self::deposit_event(Event::GenesisConfigUpdated(field));
Ok(())
}
}
// ===============================================================================
// ````````````````````````````````` PUBLIC APIS `````````````````````````````````
// ===============================================================================
impl<T: Config> Pallet<T> {
/// Returns `Ok(())` if the author is permitted to submit the [`Self::chill`] extrinsic
/// using the given affidavit key.
///
/// Performs a read-only pre-check verifying that chilling does not
/// conflict with any active or pending duty. The check branches on which
/// session scope the key belongs to:
///
/// - **Next affidavit session (current + 2)**: author has already declared and
/// rotated. Chilling is allowed only after the election window closes and
/// the author is not in the revealed elected set.
///
/// - **Next session (current + 1)**: author has registered but may not have
/// declared yet. Chilling is allowed before the affidavit window or after
/// it closes without a declaration. Rejected if a declaration exists but
/// the key is stale relative to the expected post-rotation key.
///
/// ## Parameters
/// - `author`: The author requesting to chill.
/// - `affidavit_pub`: The affidavit key registered via [`Self::validate`]
/// or rotated during [`Self::declare`].
///
/// ## Returns
/// - `Ok(())` if chilling is permitted.
/// - `Err(ValidatorCannotChill)` if the author is active in the current session.
/// - `Err(CandidateCannotChill)` if the election window is still open.
/// - `Err(ElectedCannotChill)` if the author appears in the revealed elected set.
/// - `Err(InvalidRotatedAffidavitKey)` if a declaration exists but the key is stale.
/// - `Err(DispatchError)` for ownership, timing, or configuration violations.
pub fn can_chill(author: AuthorOf<T>, affidavit_pub: AffidavitId<T>) -> DispatchResult {
let current_session = CurrentSession::<T>::get();
let next_session = current_session.saturating_add(One::one());
let next_afdt_session = next_session.saturating_add(One::one());
// Convert author -> validator id for the current session
// If conversion fails, runtime cannot determine validator status
let Some(validator) =
<Pallet<T> as Convert<AuthorOf<T>, Option<SessionId<T>>>>::convert(author.clone())
else {
return Err(Error::<T>::SessionIdQueryFailed.into());
};
// Active validators of the *current* session are not allowed to chill.
// Reason: they may still be required if elections fail or re-run.
ensure!(
!pallet_session::Pallet::<T>::validators().contains(&validator),
Error::<T>::ValidatorCannotChill
);
// Compute affidavit submission window for the upcoming election
let aff_window = Self::compute_affidavit_window()?;
let start_affidavit = aff_window.start;
let end_affidavit = aff_window.end;
// Ensure configuration is sane: submission window must be valid
debug_assert!(
start_affidavit < end_affidavit,
"Affidavit submission period invalid: starts at {:?}, ends at {:?}",
start_affidavit,
end_affidavit
);
ensure!(
start_affidavit < end_affidavit,
Error::<T>::InvalidAffidavitPeriod
);
let current_block = frame_system::Pallet::<T>::block_number();
// CASE 1: Key belongs to next-next session (already rotated)
//
// Optimistically we need to check.
//
// This means:
// - Author already declared an affidavit for `next_session`
// - During declaration, a new key was rotated for `next_afdt_session`
// Hence this author may very-well be a candidate for the ongoing election.
if let Some(id) = AffidavitKeys::<T>::get((next_afdt_session, &affidavit_pub)) {
ensure!(id == author, Error::<T>::AuthorNotAffidavitOwner);
// Sanity: a rotated key implies the affidavit must have been declared
// within the valid submission window.
debug_assert!(
!(current_block < start_affidavit),
"affidavit key is for next-next session, effectively means it
declared affidavit and rotated next key, but it happened before
affidavit submission period itself? for author {:?} and afdt key {:?},
rotated during elected session {:?}, and rotated for session {:?}",
author,
affidavit_pub,
next_session,
next_afdt_session
);
ensure!(
!(current_block < start_affidavit),
Error::<T>::DeclaredBeforeAffidavitPeriod
);
// If still within affidavit submission window:
// author is an active candidate -> cannot chill.
// It is possible that the author is not present in the elected
// list at this stage.
// In that case, we ideally should purge:
// - the declared affidavit for `next_session`,
// - the affidavit key for `next_session`,
// - and the rotated affidavit key for `next_afdt_session`.
// However, at this point we only have access to the
// `next_afdt_session` affidavit key i.e., rotated key.
ensure!(
current_block >= end_affidavit,
Error::<T>::CandidateCannotChill
);
// After the election period:
// Only authors who were NOT elected are allowed to chill.
//
// We already enforced earlier that active validators of the *current session*
// cannot chill. This guarantees that even if the `reveal` result here is
// slightly outdated or later ignored by the session (e.g. the same validators
// are re-posted due to election issues), safety is preserved.
//
// Therefore:
// - If the author appears in the revealed elected set -> they must not chill.
// - If the author does NOT appear -> they are not part of the upcoming elected set.
// - Even if the reveal is stale, it can only reflect a previous valid election
// outcome, and cannot incorrectly allow a current validator to chill.
//
// Hence, it is safe to rely on this check to prevent elected (or soon-to-be
// elected) authors from chilling.
let elected = <Internals<T> as ElectAuthors<AuthorOf<T>, ElectionVia<T>>>::reveal();
if let Some(elected) = elected {
for elect in elected.into_iter() {
if author == elect {
return Err(Error::<T>::ElectedCannotChill.into());
}
}
}
// Election finished and author not elected:
// author can chill at next-next election.
return Ok(());
}
// CASE 2: Key belongs to next session
//
// This means the author has registered an affidavit key but may NOT yet
// declared the affidavit for the upcoming election.
let id = AffidavitKeys::<T>::get((next_session, &affidavit_pub))
.ok_or(Error::<T>::AffidavitAuthorNotFound)?;
ensure!(id == author, Error::<T>::AuthorNotAffidavitOwner);
// Subcase A: Before affidavit submission window begins
//
// Author is simply opting out before participating in election.
if current_block < start_affidavit {
let afdt_decl = AuthorAffidavits::<T>::contains_key((next_session, &author));
// Sanity: affidavit should not be declared before submission window.
debug_assert!(
!afdt_decl,
"affidavit is declared before affidavit submission period
by author {:?} for election conducted for session {:?} using
afdt-key {:?}",
author, next_session, affidavit_pub
);
ensure!(!afdt_decl, Error::<T>::DeclaredBeforeAffidavitPeriod);
return Ok(());
}
// Subcase B: During or after affidavit submission window
match AuthorAffidavits::<T>::contains_key((next_session, &author)) {
true => {
// Affidavit has already been declared for `next_session`.
//
// Normally, this implies that a new (rotated) affidavit key for `next_afdt_session`
// should have been registered as part of the declaration flow.
//
// If we still reached here with the current key, it likely means the provided key
// is stale or does not correspond to the rotated key expected after declaration.
//
// However, we must not blindly assume rotation always changes the key. In some
// implementations (e.g., custom declaration flows outside this pallet's OCWs),
// the same affidavit key might be reused during rotation.
//
// Therefore, rather than mutating any state based on uncertain assumptions,
// we conservatively reject the call with an explicit error.
return Err(Error::<T>::InvalidRotatedAffidavitKey.into());
}
false => {
// Either still inside submission window but not yet declared,
// or window already ended and author implicitly chilled.
return Ok(());
}
}
}
/// Returns `Ok(())` if the author is eligible to submit a [`Self::validate`] extrinsic.
///
/// Performs a pre-check for validation readiness by verifying that:
/// - the author is not already an active validator in the current session,
/// - the author exists in the role system via [`Config::RoleAdapter`], and
/// - the author is currently marked as available.
///
/// Intended for use by offchain workers and RPC consumers before constructing
/// and submitting a [`Self::validate`] extrinsic.
///
/// ## Parameters
/// - `author`: The author whose validation eligibility is being checked.
///
/// ## Returns
/// - `Ok(())` if all conditions for validation readiness are satisfied.
/// - `Err(ActivelyValidating)` if the author is already in the active validator set.
/// - `Err(DispatchError)` if the role check or availability check fails.
pub fn can_validate(author: AuthorOf<T>) -> DispatchResult {
if Self::is_validating(author.clone()) {
return Err(Error::<T>::ActivelyValidating.into());
}
<T::RoleAdapter as RoleManager<AuthorOf<T>>>::role_exists(&author)?;
<T::RoleAdapter as RoleManager<AuthorOf<T>>>::is_available(&author)?;
Ok(())
}
/// Returns `true` if the author is an active validator in the **current session**.
///
/// Converts the author identifier into its session-specific validator id using
/// the configured [`Convert`] implementation, then checks whether that validator
/// appears in the current session's active validator set via [`pallet_session`].
///
/// Returns `false` if the author-to-validator conversion fails, as the runtime
/// cannot determine validator status without a valid session identity.
///
/// ## Parameters
/// - `author`: The author whose active validation status is being checked.
pub fn is_validating(author: AuthorOf<T>) -> bool {
// Convert author -> validator id for the current session
let Some(validator) =
<Pallet<T> as Convert<AuthorOf<T>, Option<SessionId<T>>>>::convert(author.clone())
else {
return false;
};
// Active validators of the *current* session.
if pallet_session::Pallet::<T>::validators().contains(&validator) {
return true;
}
false
}
/// Returns `true` if the author has no registered affidavit key in any
/// relevant future session scope and is therefore in a **chilled** state.
///
/// This is the logical inverse of [`Self::is_pursuing`] and delegates
/// directly to [`Self::get_runtime_afdt_key`].
///
/// ## Parameters
/// - `author`: The author whose chilling status is being checked.
pub fn is_chilling(author: AuthorOf<T>) -> bool {
Self::get_runtime_afdt_key(author).is_err()
}
/// Retrieve the author's registered affidavit key and its associated session
/// from the two relevant future session scopes.
///
/// Searches across:
/// - the **next affidavit session** (current + 2), checked first, and
/// - the **next session** (current + 1), checked second.
///
/// The next affidavit session is checked first because a key stored there
/// indicates a more advanced lifecycle state: the author has already declared
/// an affidavit for the next session and rotated to a fresh key for the
/// session after.
///
/// ## Parameters
/// - `author`: The author whose registered affidavit key is being retrieved.
///
/// ## Returns
/// - `Ok((session, affidavit_key))` if a key owned by the author is found
/// in either future session scope.
/// - `Err(AffidavitKeyPairNotFound)` if no registered key exists for the author.
pub fn get_runtime_afdt_key(
author: AuthorOf<T>,
) -> Result<(SessionIndex, AffidavitId<T>), DispatchError> {
let current_session = CurrentSession::<T>::get();
let next_session = current_session.saturating_add(One::one());
let next_afdt_session = next_session.saturating_add(One::one());
if let Some((affidavit_pub, _)) = AffidavitKeys::<T>::iter_prefix((next_afdt_session,))
.find(|(_, owner)| *owner == author)
{
return Ok((next_afdt_session, affidavit_pub));
}
if let Some((affidavit_pub, _)) =
AffidavitKeys::<T>::iter_prefix((next_session,)).find(|(_, owner)| *owner == author)
{
return Ok((next_session, affidavit_pub));
}
Err(Error::<T>::AffidavitKeyPairNotFound.into())
}
/// Resolve an affidavit account identifier to its corresponding public key
/// in the **node-local keystore**.
///
/// Iterates all locally available affidavit application keys, derives the
/// account-form identifier for each, and returns the public key whose derived
/// account matches the provided `afdt_key`.
///
/// ## Parameters
/// - `afdt_key`: The affidavit account identifier to resolve.
///
/// ## Returns
/// - `Ok(public_key)` if a matching key is found in the local keystore.
/// - `Err(AfdtPublicKeyNotFound)` if no locally held key derives to the given identifier.
///
/// ## Note
/// This function reads from the node-local keystore and may return different
/// results across nodes depending on which keys each node holds.
pub fn get_public_key(afdt_key: AffidavitId<T>) -> Result<T::Public, DispatchError> {
let all_keys =
<<T::AffidavitCrypto as AppCrypto<T::Public, T::Signature>>::RuntimeAppPublic
as RuntimeAppPublic>::all();
for key in all_keys.into_iter() {
let generic_pub: <T::AffidavitCrypto as AppCrypto<T::Public, T::Signature>>::GenericPublic =
key.into();
let public: T::Public = generic_pub.into();
let account: AffidavitId<T> = public.clone().into_account().into();
if account == afdt_key {
return Ok(public);
}
}
Err(Error::<T>::AfdtPublicKeyNotFound.into())
}
/// Retrieve the currently finalized **active affidavit key** from node-local
/// offchain storage.
///
/// Reads the active affidavit key using finalized offchain storage semantics
/// and returns it only when its confidence level is [`Confidence::Safe`].
/// Keys that exist but have not yet reached safe confidence are rejected,
/// as they may still be subject to re-org.
///
/// ## Returns
/// - `Ok(key)` if a finalized key exists and is marked as [`Confidence::Safe`].
/// - `Err(ActiveAfdtKeyFinalizedHangingValue)` if a finalized value exists
/// without a corresponding fork-aware reference.
/// - `Err(ActiveAfdtKeyNotYetFinalized)` if the key exists but has not yet
/// reached safe confidence.
/// - `Err(DispatchError)` if the offchain storage read itself fails.
///
/// ## Note
/// This value is maintained in node-local offchain storage and is not part
/// of on-chain state. Results may differ across nodes.
pub fn get_finalized_afdt_key() -> Result<AffidavitId<T>, DispatchError> {
let result = Finalized::<T, AffidavitId<T>, DeclareAffidavit<T>, Pallet<T>>::get(
ACTIVE_AFDT_KEY,
LOG_TARGET_AFDT,
None,
);
match result {
Ok(None) => Err(Error::<T>::ActiveAfdtKeyFinalizedHangingValue.into()),
Ok(Some(Confidence::Safe(key))) => Ok(key),
Ok(Some(_)) => Err(Error::<T>::ActiveAfdtKeyNotYetFinalized.into()),
Err(e) => Err(e),
}
}
/// Construct and sign a [`ValidatePayload`] using the currently finalized
/// active affidavit key from node-local offchain storage.
///
/// Performs the following steps in sequence:
/// - retrieves the finalized active affidavit key via [`Self::get_finalized_afdt_key`],
/// - resolves that key to a local public key via [`Self::get_public_key`],
/// - constructs a [`ValidatePayload`] wrapping the resolved public key, and
/// - signs the payload using the configured [`Config::AffidavitCrypto`] scheme.
///
/// The resulting payload and signature are the exact inputs required by
/// the [`Self::validate`] extrinsic.
///
/// ## Returns
/// - `Ok((payload, signature))` if the key is finalized, locally available,
/// and signing succeeds.
/// - `Err(CannotSignValidateTxPayload)` if signing fails.
/// - `Err(DispatchError)` if key retrieval or resolution fails.
///
/// ## Note
/// This function reads from node-local offchain storage and the local keystore.
/// Results are node-specific and may differ across validators.
pub fn sign_validate_payload() -> Result<(ValidatePayloadOf<T>, T::Signature), DispatchError> {
let active_afdt_key = Self::get_finalized_afdt_key()?;
let afdt_pub = Self::get_public_key(active_afdt_key)?;
let payload = ValidatePayload { public: afdt_pub };
let Some(signature) = <ValidatePayload<T::Public> as SignedPayload<T>>::sign::<
T::AffidavitCrypto,
>(&payload) else {
return Err(Error::<T>::CannotSignValidateTxPayload.into());
};
Ok((payload, signature))
}
/// Retrieve the currently revealed elected author set from the election manager.
///
/// Delegates to [`ElectAuthors::reveal`] and returns the result as a
/// concrete [`ElectionElects`] value.
///
/// This function does not trigger or re-run an election. It only reads
/// the result of the most recently completed election preparation.
/// If no election has been executed or the result is unavailable,
/// it returns an error.
///
/// ## Returns
/// - `Ok(ElectionElects)` containing the elected author set.
/// - `Err(UnableToRevealElected)` if no election result is currently available.
pub fn get_elects() -> Result<ElectionElects<T>, DispatchError> {
let Some(elects) = <Internals<T> as ElectAuthors<AuthorOf<T>, ElectionVia<T>>>::reveal() else {
return Err(Error::<T>::UnableToRevealElected.into())
};
Ok(elects)
}
/// Retrieve the submitted affidavit for a given affidavit identifier
/// targeting the **upcoming session's election**.
///
/// Resolves the affidavit key to its owning author, then returns the
/// author's declared election weights for the next session (current + 1).
///
/// ## Parameters
/// - `afdt_id`: The affidavit key identifier to look up.
///
/// ## Returns
/// - `Ok(ElectionVia)` containing the author's declared election weights.
/// - `Err(DispatchError)` otherwise.
pub fn fetch_affidavit(afdt_id: AffidavitId<T>) -> Result<ElectionVia<T>, DispatchError> {
Self::get_affidavit(&afdt_id)
}
/// Retrieve the submitted affidavit for a given affidavit identifier
/// targeting a **specific session**.
///
/// Unlike [`Self::fetch_affidavit`], which always targets the upcoming session,
/// this function allows querying affidavits for any session by index.
/// It resolves the affidavit key to its registered author for the given session,
/// then returns that author's declared election weights.
///
/// ## Parameters
/// - `afdt_id`: The affidavit key identifier to look up.
/// - `session`: The session index for which the affidavit is queried.
///
/// ## Returns
/// - `Ok(ElectionVia)` containing the author's declared election weights for the session.
/// - `Err(AffidavitKeyPairNotFound)` if the key is not registered for the given session.
/// - `Err(AffidavitNotFound)` if the author has not submitted an affidavit for that session.
pub fn fetch_affidavit_for(afdt_id: AffidavitId<T>, session: SessionIndex) -> Result<ElectionVia<T>, DispatchError> {
let Some(author) = AffidavitKeys::<T>::get((session, afdt_id)) else { return Err(Error::<T>::AffidavitKeyPairNotFound.into()) };
let Some((_, affidavit)) = AuthorAffidavits::<T>::get((session, author)) else { return Err(Error::<T>::AffidavitNotFound.into()) };
Ok(affidavit.into_iter().collect())
}
/// Returns `true` if the author has submitted an affidavit and is
/// actively contesting the **upcoming session's election**.
///
/// An author is considered contesting when a valid affidavit entry exists
/// in storage for the next session (current + 1). This indicates that the
/// author has declared election weights and is a candidate for selection.
///
/// ## Parameters
/// - `author`: The author whose election candidacy is being checked.
///
/// ## Returns
/// - `true` if the author has a stored affidavit for the upcoming session.
/// - `false` otherwise, including when the author has never submitted
/// an affidavit or has withdrawn.
pub fn is_contesting(author: AuthorOf<T>) -> bool {
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
let Some((_, _)) = AuthorAffidavits::<T>::get((for_session, author)) else { return false };
true
}
/// Returns `true` if the author is actively **pursuing validation**
/// by maintaining a registered affidavit key for a future session.
///
/// An author is considered pursuing when they have a registered affidavit key
/// in either the next session or the next affidavit session scope, meaning
/// they have not chilled and intend to participate in upcoming elections.
///
/// This is the logical inverse of [`Self::is_chilling`].
///
/// ## Parameters
/// - `author`: The author whose pursuit status is being checked.
///
/// ## Returns
/// - `true` if the author holds an affidavit key for any relevant future session.
/// - `false` if the author has no registered keys and is effectively chilled.
pub fn is_pursuing(author: AuthorOf<T>) -> bool {
!Self::is_chilling(author)
}
/// Returns `Ok(())` if the author identified by the given affidavit key
/// is eligible to submit an affidavit declaration for the upcoming session.
///
/// This function performs a full pre-check for the [`Self::declare`] extrinsic,
/// verifying that:
/// - the affidavit key is registered for the upcoming session,
/// - the global [`AllowAffidavits`] flag is enabled,
/// - the author associated with the key is available in the role system, and
/// - the current block falls within the configured affidavit submission window.
///
/// Intended for use by offchain workers and RPC consumers to determine
/// whether an affidavit declaration can be safely submitted at the current block.
///
/// ## Parameters
/// - `afdt_id`: The affidavit key identifier to evaluate.
///
/// ## Returns
/// - `Ok(())` if all conditions for affidavit submission are satisfied.
/// - `Err(DispatchError)` otherwise.
pub fn can_declare(afdt_id: AffidavitId<T>) -> DispatchResult {
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
ensure!(
AffidavitKeys::<T>::contains_key((for_session, &afdt_id)),
Error::<T>::AffidavitAuthorNotFound
);
Self::can_submit_affidavit(&afdt_id)
}
/// Returns `Ok(())` if the given author is eligible to submit an election
/// extrinsic at the current block.
///
/// This function performs a full pre-check for the [`Self::elect`] extrinsic,
/// verifying that:
/// - the current block has an identifiable block author,
/// - the provided author matches the current block author, and
/// - the current block falls within the configured election window.
///
/// Only the block author may run the election for a given block, ensuring
/// that election submissions cannot be spoofed by non-producing validators.
///
/// ## Parameters
/// - `author`: The author asserting eligibility to run the election.
///
/// ## Returns
/// - `Ok(())` if the author is the current block author and the election window is open.
/// - `Err(DispatchError)` otherwise.
pub fn can_elect(author: AuthorOf<T>) -> DispatchResult {
let block_author = pallet_authorship::Pallet::<T>::author().ok_or(Error::<T>::BlockAuthorNotFound)?;
ensure!(
author == block_author,
Error::<T>::NotABlockAuthor
);
<Internals<T> as ElectAuthors<AuthorOf<T>, ElectionVia<T>>>::can_process_election(&Some(block_author))?;
Ok(())
}
/// Computes the affidavit submission window for the current session.
///
/// The window is derived from the session start and average session length:
/// ```text
/// start = session_start + (affidavit_begins_at * avg_session_length)
/// end = session_start + (affidavit_ends_at * avg_session_length)
/// ```
///
/// Note: `affidavit_begins_at` and `affidavit_ends_at` are **percentages**
/// of the session length and are applied to compute block offsets.
///
/// ## Returns
/// - `Ok(AffidavitWindow)` containing start and end blocks
/// - `DispatchError` otherwise
///
/// ## Notes
/// - The resulting window is session-relative and recalculated each session.
/// - Affidavits submitted outside this window should be rejected.
pub fn compute_affidavit_window() -> Result<AffidavitWindow<T>, DispatchError> {
let session_start = SessionStartAt::<T>::get();
let avg_session_len =
<<T as crate::Config>::NextSessionRotation as EstimateNextSessionRotation<
BlockNumberFor<T>,
>>::average_session_length();
let begin_at = AffidavitBeginsAt::<T>::get();
let begin_offset = begin_at.mul_floor(avg_session_len);
let start_block = session_start.saturating_add(begin_offset);
let ends_at = AffidavitEndsAt::<T>::get();
let invariant = ends_at > begin_at;
debug_assert!(
invariant,
"invalid affidavit period configured during genesis or
root update to storage values, affidavit begins at {:?}
and ends at {:?}",
begin_at, ends_at
);
ensure!(invariant, Error::<T>::InvalidAffidavitPeriod);
let end_offset = ends_at.mul_floor(avg_session_len);
let end_block = session_start.saturating_add(end_offset);
let aff_window = AffidavitWindow::<T> {
start: start_block,
end: end_block,
};
Ok(aff_window)
}
/// Computes the election window for the current session.
///
/// The election window is a sub-range of the affidavit window:
/// ```text
/// start = affidavit_start + (election_begins_at * (affidavit_end - affidavit_start))
/// end = affidavit_end
/// ```
///
/// Note:
/// - `election_begins_at` is a **percentage** of the affidavit window range.
/// - The election always **ends when the affidavit window ends**.
///
/// ## Diagram
/// ```text
/// |--------- Affidavit Window ---------|
/// |------|-----------------------------|
/// ^ ^
/// election_start election_end (= affidavit_end)
/// ```
///
/// ## Returns
/// - `Ok(ElectionWindow)` containing start and end blocks
/// - `DispatchError` otherwise
pub fn compute_election_window() -> Result<ElectionWindow<T>, DispatchError> {
let afdt_window = Self::compute_affidavit_window()?;
let start_affidavit = afdt_window.start;
let end_affidavit = afdt_window.end;
let election_begin_at = ElectionBeginsAt::<T>::get();
let affidavit_range = end_affidavit.saturating_sub(start_affidavit);
let start_portion = election_begin_at.mul_floor(affidavit_range);
let start_election = start_affidavit.saturating_add(start_portion);
let elect_window = ElectionWindow::<T> {
start: start_election,
end: end_affidavit,
};
Ok(elect_window)
}
}
// ===============================================================================
// `````````````````````````````` VALIDATE UNSIGNED ``````````````````````````````
// ===============================================================================
impl<T: Config> ValidateUnsigned for Pallet<T> {
type Call = Call<T>;
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
let Ok(aff_window) = Self::compute_affidavit_window() else {
return InvalidTransaction::BadProof.into();
};
match call {
Call::declare { payload, signature } => {
if !SignedPayload::<T>::verify::<T::AffidavitCrypto>(payload, signature.clone())
{
return InvalidTransaction::BadProof.into();
}
let end_block = aff_window.end;
// Current block number (fork-relative).
// Safe to use for freshness/expiry checks since validity is evaluated per fork head.
let current_block = frame_system::Pallet::<T>::block_number();
// Reject if the affidavit window has expired.
// This is fork-safe because it is a monotonic freshness check.
if current_block > end_block {
return InvalidTransaction::Stale.into();
}
let public = SignedPayload::<T>::public(payload);
let affidavit_pub: AffidavitId<T> = public.clone().into_account().into();
let for_session = CurrentSession::<T>::get().saturating_add(One::one());
// Ensure the signer is registered as a valid affidavit key for that session.
if !AffidavitKeys::<T>::contains_key((for_session, &affidavit_pub)) {
return InvalidTransaction::BadSigner.into();
}
// Longevity: how long (in blocks) this transaction should remain valid in the pool.
// Derived from remaining time until the affidavit window closes.
let longetivity = end_block.saturating_sub(current_block).into();
return ValidTransaction::with_tag_prefix("declare")
.priority(AffidavitTxPriority::<T>::get())
.longevity(longetivity.low_u64())
// Provide a uniqueness tag to prevent duplicate unsigned submissions
// per (session, validator). The tuple is SCALE-encoded and used as the pool key.
.and_provides((for_session, affidavit_pub))
// Allow propagation to other nodes (normal gossip).
.propagate(true)
.build();
}
Call::validate { payload, signature } => {
if !SignedPayload::<T>::verify::<T::AffidavitCrypto>(payload, signature.clone())
{
return InvalidTransaction::BadProof.into();
}
let avg_session_len = <<T as crate::Config>::NextSessionRotation as EstimateNextSessionRotation<BlockNumberFor<T>>>::average_session_length();
let session_start = SessionStartAt::<T>::get();
let current_block = frame_system::Pallet::<T>::block_number();
// Longevity: remaining blocks until end of session.
// This keeps the tx in the pool only while session is still active.
let longetivity = session_start
.saturating_add(avg_session_len)
.saturating_sub(current_block)
.into();
return ValidTransaction::with_tag_prefix("validate")
.priority(ValidateTxPriority::<T>::get())
.longevity(longetivity.low_u64())
// Provide a uniqueness tag based on the SCALE-encoded payload.
// This prevents duplicate submissions of the exact same validation payload
// from coexisting in the transaction pool (replay/spam protection).
.and_provides(payload)
.propagate(true)
.build();
}
Call::elect { payload, signature } => {
if !SignedPayload::<T>::verify::<T::AffidavitCrypto>(payload, signature.clone())
{
return InvalidTransaction::BadProof.into();
}
let end_affidavit = aff_window.end;
let current_block = frame_system::Pallet::<T>::block_number();
// Reject if election period has expired.
// Fork-safe freshness check.
if current_block > end_affidavit {
return InvalidTransaction::Stale.into();
}
// Elections target the session after next (current + 2), since
// affidavit declaration would have resulted in newly rotated key.
let for_session = CurrentSession::<T>::get().saturating_add(2u32.into());
let public = SignedPayload::<T>::public(payload);
let affidavit_pub: AffidavitId<T> = public.clone().into_account().into();
// Ensure signer is eligible for that future session.
if !AffidavitKeys::<T>::contains_key((for_session, &affidavit_pub.clone())) {
return InvalidTransaction::BadSigner.into();
}
// Longevity tied to remaining election window.
let longetivity = end_affidavit.saturating_sub(current_block).into();
return ValidTransaction::with_tag_prefix("elect")
.priority(ElectionTxPriority::<T>::get())
.longevity(longetivity.low_u64())
// Provide uniqueness per (future session, validator)
// to avoid duplicate elections.
.and_provides((for_session, affidavit_pub))
// Do not propagate: only the block author (local node)
// should include this tx, As its checked in the runtime via
// pallet-authorship.
.propagate(false)
.build();
}
_ => InvalidTransaction::Call.into(),
}
}
}
}
// ===============================================================================
// `````````````````````````````````` API TESTS ``````````````````````````````````
// ===============================================================================
#[cfg(test)]
mod ext_tests {
// ===============================================================================
// ``````````````````````````````````` IMPORTS ```````````````````````````````````
// ===============================================================================
// --- Local crate imports ---
use crate::{mock::*, types::ForceGenesisConfig};
// --- Scale-codec crates ---
use codec::{Decode, Encode};
// --- FRAME Suite ---
use frame_suite::{blockchain::*, roles::*};
// --- FRAME Support ---
use frame_support::{
assert_err, assert_noop, assert_ok,
pallet_prelude::{TransactionSource, ValidateUnsigned},
traits::{Hooks, tokens::{Fortitude, Precision}},
};
// --- Substrate primitives ---
use sp_runtime::{
traits::{Convert, Zero},
transaction_validity::InvalidTransaction,
DispatchError, WeakBoundedVec,
};
// ===============================================================================
// ```````````````````````````````````` HOOKS ````````````````````````````````````
// ===============================================================================
#[test]
fn on_initialize_success() {
chain_manager_test_ext().execute_with(|| {
CurrentSession::put(1);
SessionStartsAt::put(10);
set_user_balance_and_hold(ALICE, 100, 100).unwrap();
RoleAdapter::enroll(&ALICE, 100, Fortitude::Force).unwrap();
set_block_author(ALICE);
assert!(PointsAdapter::points_of(&ALICE).is_err());
System::set_block_number(11);
Pallet::on_initialize(11);
// Check that ALICE received a point for this session
let points = PointsAdapter::points_of(&ALICE).unwrap();
assert_eq!(points, 1);
});
}
#[test]
fn ocw_initializes_active_affidavit_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
ocw_step();
assert!(affidavit_key_count().is_zero());
assert!(get_afdt_key().is_none());
ocw_step();
assert!(get_afdt_key().is_some());
let afdt_key_1 = get_afdt_key().unwrap();
assert!(get_public_key(afdt_key_1.clone()).is_some());
ocw_step();
// Since, key is already initialized, no new key is initialized.
assert!(get_afdt_key().is_some());
let afdt_key_2 = get_afdt_key().unwrap();
assert!(get_public_key(afdt_key_2.clone()).is_some());
assert_eq!(afdt_key_1, afdt_key_2);
});
}
#[test]
fn ocw_declares_affidavit() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::set(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE]).unwrap();
direct_fund_author(ALAN, ALICE, STANDARD_FUND).unwrap();
assert!(affidavit_key_count().is_zero());
assert!(get_finalized_afdt_key().is_none());
while System::block_number() < AFDT_SUBMISSION_START {
ocw_step();
}
assert!(get_afdt_key().is_some());
let afdt_key_1 = get_afdt_key().unwrap();
assert!(get_public_key(afdt_key_1.clone()).is_some());
assert!(get_next_afdt_key().is_some());
let afdt_key = get_afdt_key().unwrap();
let for_session = CurrentSession::get() + 1;
AffidavitKeys::insert((for_session, afdt_key.clone()), ALICE);
env.pool_state.write().transactions.clear();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 0);
ocw_step();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 1);
let submited_ext = env.pool_state.read().transactions.last().unwrap().clone();
let ext_decode = UncheckedExtrinsic::decode(&mut &submited_ext[..]).unwrap();
assert!(matches!(
ext_decode.function,
RuntimeCall::ChainManager(crate::Call::declare { .. })
));
ocw_step();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 2);
let submited_ext = env.pool_state.read().transactions.last().unwrap().clone();
let ext_decode = UncheckedExtrinsic::decode(&mut &submited_ext[..]).unwrap();
assert!(matches!(
ext_decode.function,
RuntimeCall::ChainManager(crate::Call::declare { .. })
));
})
}
#[test]
fn ocw_submits_election_tx_when_eligible() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE]).unwrap();
direct_fund_author(ALAN, ALICE, STANDARD_FUND).unwrap();
// prepare active key first.
while System::block_number() < AFDT_SUBMISSION_START {
ocw_step();
}
let afdt_key = get_afdt_key().unwrap();
let for_session = CurrentSession::get() + 1;
AffidavitKeys::insert((for_session, afdt_key.clone()), ALICE);
ocw_step();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 1);
let submited_ext = env.pool_state.read().transactions.last().unwrap().clone();
let ext_decode = UncheckedExtrinsic::decode(&mut &submited_ext[..]).unwrap();
assert!(matches!(
ext_decode.function,
RuntimeCall::ChainManager(crate::Call::declare { .. })
));
// declare executed
let next_afdt_key = get_next_afdt_key().unwrap();
AffidavitKeys::insert((for_session + 1, next_afdt_key), ALICE);
// move into just before election-eligible block
while System::block_number() < ELECTION_START {
ocw_step();
}
env.pool_state.write().transactions.clear();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 0);
ocw_step();
let tx = env.pool_state.read().transactions.clone();
assert_eq!(tx.len(), 1);
let submited_ext = env.pool_state.read().transactions.last().unwrap().clone();
let ext_decode = UncheckedExtrinsic::decode(&mut &submited_ext[..]).unwrap();
assert!(matches!(
ext_decode.function,
RuntimeCall::ChainManager(crate::Call::elect { .. })
));
});
}
// ===============================================================================
// `````````````````````````````` VALIDATE UNSIGNED ``````````````````````````````
// ===============================================================================
#[test]
fn validate_unsigned_validate_accepts_valid_payload() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(1);
let public = generate_affidavit_keypair();
let payload = ValidatePayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::validate { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
let valid = validity.unwrap();
assert_eq!(valid.priority, ValidateTxPriority::get());
assert_eq!(valid.longevity, 600);
assert!(valid.propagate);
});
}
#[test]
fn validate_unsigned_validate_rejects_bad_signature() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(1);
let public = generate_affidavit_keypair();
let wrong_public = generate_affidavit_keypair();
let payload = ValidatePayloadOf {
public: public.clone(),
};
let bad_signature = sign_payload(&payload.encode(), wrong_public);
let call = Call::validate {
payload,
signature: bad_signature,
};
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
assert_err!(validity, InvalidTransaction::BadProof);
});
}
#[test]
fn validate_unsigned_declare_affidavit_accepts_registered_key_within_window() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(AFDT_SUBMISSION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let next_afdt_id = generate_affidavit_id();
let for_session = CurrentSession::get() + 1;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_afdt_id,
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::declare { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
let valid = validity.unwrap();
assert_eq!(valid.priority, AffidavitTxPriority::get());
assert_eq!(valid.longevity, AFDT_SUBMISSION_END - AFDT_SUBMISSION_START);
assert!(valid.propagate);
});
}
#[test]
fn validate_unsigned_declare_affidavit_rejects_bad_signature() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(AFDT_SUBMISSION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let wrong_public = generate_affidavit_keypair();
let next_afdt_id = generate_affidavit_id();
let for_session = CurrentSession::get() + 1;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_afdt_id,
};
let bad_signature = sign_payload(&payload.encode(), wrong_public);
let call = Call::declare {
payload,
signature: bad_signature,
};
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
assert_err!(validity, InvalidTransaction::BadProof);
});
}
#[test]
fn validate_unsigned_declare_affidavit_rejects_unregistered_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(AFDT_SUBMISSION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id).unwrap();
let next_afdt_id = generate_affidavit_id();
let payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_afdt_id,
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::declare { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
assert_err!(validity, InvalidTransaction::BadSigner);
});
}
#[test]
fn validate_unsigned_declare_affidavit_rejects_stale_call() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(AFDT_SUBMISSION_END + 1);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let next_afdt_id = generate_affidavit_id();
let for_session = CurrentSession::get() + 1;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_afdt_id,
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::declare { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::External, &call);
assert_err!(validity, InvalidTransaction::Stale);
});
}
#[test]
fn validate_unsigned_elect_authors_accepts_registered_rotated_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(ELECTION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let for_session = CurrentSession::get() + 2;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::elect { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::Local, &call);
let valid = validity.unwrap();
assert_eq!(valid.priority, ElectionTxPriority::get());
assert_eq!(valid.longevity, AFDT_SUBMISSION_END - ELECTION_START);
assert!(!valid.propagate);
});
}
#[test]
fn validate_unsigned_elect_authors_rejects_bad_signature() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(ELECTION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let wrong_public = generate_affidavit_keypair();
let for_session = CurrentSession::get() + 2;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = ElectionPayloadOf {
public: public.clone(),
};
let bad_signature = sign_payload(&payload.encode(), wrong_public);
let call = Call::elect {
payload,
signature: bad_signature,
};
let validity = Pallet::validate_unsigned(TransactionSource::Local, &call);
assert_err!(validity, InvalidTransaction::BadProof);
});
}
#[test]
fn validate_unsigned_elect_authors_rejects_unregistered_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(ELECTION_START);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id).unwrap();
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::elect { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::Local, &call);
assert_err!(validity, InvalidTransaction::BadSigner);
});
}
#[test]
fn validate_unsigned_elect_authors_rejects_stale_call() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session(1);
set_session_config();
System::set_block_number(AFDT_SUBMISSION_END + 1);
let afdt_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let for_session = CurrentSession::get() + 2;
register_affidavit_key(for_session, afdt_id, ALICE);
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
let call = Call::elect { payload, signature };
let validity = Pallet::validate_unsigned(TransactionSource::Local, &call);
assert_err!(validity, InvalidTransaction::Stale);
});
}
// ===============================================================================
// ````````````````````````````````` EXTRINSICS ``````````````````````````````````
// ===============================================================================
#[test]
fn validate_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
let afdt_id = generate_affidavit_id();
insert_active_afdt_key(afdt_id.clone()).unwrap();
run_to_block(120);
assert!(!AffidavitKeys::contains_key((2, afdt_id.clone())));
let (payload, signature) = Pallet::sign_validate_payload().unwrap();
assert_ok!(Pallet::validate(
RuntimeOrigin::signed(ALICE),
payload,
signature,
));
assert!(AffidavitKeys::contains_key((2, afdt_id)));
})
}
#[test]
fn validate_err_bad_origin() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
let afdt_id = generate_affidavit_id();
insert_active_afdt_key(afdt_id.clone()).unwrap();
run_to_block(120);
let (payload, signature) = Pallet::sign_validate_payload().unwrap();
assert_noop!(
Pallet::validate(RuntimeOrigin::root(), payload, signature,),
DispatchError::BadOrigin
);
})
}
#[test]
fn chill_err_session_id_query_failed() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
assert_noop!(
Pallet::chill(RuntimeOrigin::signed(BOB), afdt_id),
Error::SessionIdQueryFailed
);
})
}
#[test]
fn chill_err_validator_cannot_chill() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
let alice_session_id = Pallet::convert(ALICE.clone()).unwrap();
Validators::put(vec![alice_session_id]);
assert_err!(
Pallet::chill(RuntimeOrigin::signed(ALICE), afdt_id),
Error::ValidatorCannotChill
)
})
}
#[test]
fn chill_err_author_not_affidavit_owner() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
RoleAdapter::enroll(&BOB, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, afdt_id.clone()).unwrap();
let nxt_afdt_id = generate_affidavit_id();
let payload = TestAfdtPayload {
active_afdt_pub: afdt_id.clone(),
next_afdt_pub: nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, payload).unwrap();
assert_err!(
Pallet::chill(RuntimeOrigin::signed(BOB), nxt_afdt_id),
Error::AuthorNotAffidavitOwner
)
})
}
#[test]
#[should_panic]
fn chill_err_declared_before_affidavit_period() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, afdt_id.clone()).unwrap();
let nxt_afdt_id = generate_affidavit_id();
let payload = TestAfdtPayload {
active_afdt_pub: afdt_id.clone(),
next_afdt_pub: nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, payload).unwrap();
System::set_block_number(AFDT_SUBMISSION_START - 1);
Pallet::chill(RuntimeOrigin::signed(ALICE), nxt_afdt_id).unwrap();
})
}
#[test]
fn chill_err_candidate_cannot_chill() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, afdt_id.clone()).unwrap();
let nxt_afdt_id = generate_affidavit_id();
let payload = TestAfdtPayload {
active_afdt_pub: afdt_id.clone(),
next_afdt_pub: nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, payload).unwrap();
assert_noop!(
Pallet::chill(RuntimeOrigin::signed(ALICE), nxt_afdt_id),
Error::CandidateCannotChill
);
})
}
#[test]
fn chill_err_elected_cannot_chill() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
set_default_user_balance_and_hold(CHARLIE).unwrap();
set_default_user_balance_and_hold(AMY).unwrap();
set_default_user_balance_and_hold(NIX).unwrap();
enroll_authors_with_default_collateral(vec![ALICE, BOB, ALAN]).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id: AccountId = generate_affidavit_id();
let bob_nxt_afdt_id: AccountId = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
System::set_block_number(ELECTION_START);
let elected = ext_elect_authors(ALICE, alice_nxt_afdt_id.clone()).unwrap();
assert!(elected.iter().any(|id| *id == ALICE));
System::set_block_number(AFDT_SUBMISSION_END + 1);
assert_noop!(
Pallet::chill(RuntimeOrigin::signed(ALICE), alice_nxt_afdt_id),
Error::ElectedCannotChill
);
})
}
#[test]
fn chill_err_author_not_affidavit_owner_of_the_registered_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
RoleAdapter::enroll(&BOB, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, afdt_id.clone()).unwrap();
assert_noop!(
Pallet::chill(RuntimeOrigin::signed(BOB), afdt_id),
Error::AuthorNotAffidavitOwner
);
})
}
#[test]
fn chill_err_invalid_rotated_affidavit_key() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, STANDARD_COLLATERAL, Fortitude::Force).unwrap();
let afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, afdt_id.clone()).unwrap();
let gen_afdt = Pallet::gen_affidavit(&afdt_id).unwrap();
Pallet::submit_affidavit(&afdt_id, &gen_afdt).unwrap();
assert_noop!(
Pallet::chill(RuntimeOrigin::signed(ALICE), afdt_id),
Error::InvalidRotatedAffidavitKey
);
})
}
#[test]
fn chill_success_chilling_unelected_author_after_election() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
set_default_user_balance_and_hold(CHARLIE).unwrap();
set_default_user_balance_and_hold(AMY).unwrap();
set_default_user_balance_and_hold(NIX).unwrap();
set_default_user_balance_and_hold(MIKE).unwrap();
set_default_user_balance_and_hold(LAYA).unwrap();
set_default_user_balance_and_hold(DAVE).unwrap();
set_default_user_balance_and_hold(JIM).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
System::set_block_number(ELECTION_START);
let elected = ext_elect_authors(ALICE, alice_nxt_afdt_id.clone()).unwrap();
let mut not_elected = ALICE;
for author in authors {
if !elected.contains(&author) {
not_elected = author
}
}
// dbg!(not_elected.clone());
assert!(not_elected == JIM);
System::set_block_number(AFDT_SUBMISSION_END + 1);
assert_ok!(Pallet::chill(
RuntimeOrigin::signed(JIM),
jim_nxt_afdt_id.clone()
),);
let nxt_afdt_session = CurrentSession::get() + 2;
assert!(!AffidavitKeys::contains_key((
nxt_afdt_session,
jim_nxt_afdt_id
)))
})
}
#[test]
fn chill_success_before_start_affidavit() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
let afdt_pub = generate_affidavit_id();
System::set_block_number(AFDT_SUBMISSION_START - 25);
ext_validate(ALICE, afdt_pub.clone()).unwrap();
assert_ok!(Pallet::chill(
RuntimeOrigin::signed(ALICE),
afdt_pub.clone()
));
let for_session = CurrentSession::get() + 1;
assert!(!AffidavitKeys::contains_key((
for_session,
afdt_pub.clone()
)));
})
}
#[test]
fn chill_success_during_affidavit_period_but_before_declaring() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
let afdt_pub = generate_affidavit_id();
System::set_block_number(AFDT_SUBMISSION_START - 25);
ext_validate(ALICE, afdt_pub.clone()).unwrap();
System::set_block_number(AFDT_SUBMISSION_START + 50);
assert_ok!(Pallet::chill(
RuntimeOrigin::signed(ALICE),
afdt_pub.clone()
));
let for_session = CurrentSession::get() + 1;
assert!(!AffidavitKeys::contains_key((
for_session,
afdt_pub.clone()
)));
})
}
#[test]
fn chill_success_after_end_affidavit_without_declaring() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
let afdt_pub = generate_affidavit_id();
System::set_block_number(AFDT_SUBMISSION_START - 25);
ext_validate(ALICE, afdt_pub.clone()).unwrap();
System::set_block_number(AFDT_SUBMISSION_END + 1);
assert_ok!(Pallet::chill(
RuntimeOrigin::signed(ALICE),
afdt_pub.clone()
));
let for_session = CurrentSession::get() + 1;
assert!(!AffidavitKeys::contains_key((
for_session,
afdt_pub.clone()
)));
})
}
#[test]
fn chill_err_bad_origin() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
let afdt_pub = generate_affidavit_id();
let for_session = CurrentSession::get() + 1;
ext_validate(ALICE, afdt_pub.clone()).unwrap();
System::set_block_number(AFDT_SUBMISSION_START - 25);
assert_noop!(
Pallet::chill(RuntimeOrigin::root(), afdt_pub.clone()),
sp_runtime::DispatchError::BadOrigin
);
assert!(AffidavitKeys::contains_key((for_session, afdt_pub.clone())));
})
}
#[test]
fn declare_affidavit_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::put(1);
set_default_users_balance_and_hold(vec![ALICE, BOB]).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(BOB, ALICE, 300).unwrap();
let afdt_id: sp_runtime::AccountId32 = generate_affidavit_id();
insert_active_afdt_key(afdt_id.clone()).unwrap();
ext_validate(ALICE, afdt_id.clone()).unwrap();
let for_session = CurrentSession::get() + 1;
assert!(AffidavitKeys::contains_key((for_session, afdt_id.clone())));
let next_adft_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let affidavit_payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_adft_id.clone(),
};
let signature = sign_payload(&affidavit_payload.encode(), public);
assert!(!AuthorOfAffidavits::contains_key((for_session, ALICE)));
System::set_block_number(AFDT_SUBMISSION_START);
assert_ok!(Pallet::declare(
RuntimeOrigin::none(),
affidavit_payload,
signature
));
assert!(AuthorOfAffidavits::contains_key((for_session, ALICE)));
let actual_afdt = AuthorOfAffidavits::get((for_session, ALICE)).unwrap();
let afdt: WeakBoundedVec<(Funder, u64), _> =
WeakBoundedVec::try_from(vec![(Funder::Direct(BOB), 300)]).unwrap();
let expected_afdt = (AFDT_SUBMISSION_START, afdt);
assert_eq!(actual_afdt, expected_afdt);
let for_session_2 = CurrentSession::get() + 2;
assert!(AffidavitKeys::contains_key((for_session_2, next_adft_id)));
#[cfg(not(feature = "dev"))]
{
System::assert_last_event(Event::AffidavitSubmitted {
afdt_id: afdt_id,
session: for_session
}
.into()
);
}
#[cfg(feature = "dev")]
{
let exp_afdt = Pallet::get_affidavit(&afdt_id).unwrap();
System::assert_last_event(Event::AffidavitSubmitted {
afdt_id: afdt_id,
session: for_session,
author: ALICE,
affidavit: exp_afdt
}
.into()
);
}
})
}
#[test]
fn declare_affidavit_err_bad_origin() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::put(1);
set_default_users_balance_and_hold(vec![ALICE, BOB]).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(BOB, ALICE, 300).unwrap();
let afdt_id = generate_affidavit_id();
insert_active_afdt_key(afdt_id.clone()).unwrap();
ext_validate(ALICE, afdt_id.clone()).unwrap();
let for_session = CurrentSession::get() + 1;
assert!(AffidavitKeys::contains_key((for_session, afdt_id.clone())));
let next_adft_id = generate_affidavit_id();
let public = get_public_key(afdt_id.clone()).unwrap();
let affidavit_payload = AffidavitPayloadOf {
public: public.clone(),
rotate: next_adft_id.clone(),
};
let signature = sign_payload(&affidavit_payload.encode(), public);
assert!(!AuthorOfAffidavits::contains_key((for_session, ALICE)));
System::set_block_number(AFDT_SUBMISSION_START);
System::set_block_number(136);
assert_noop!(
Pallet::declare(
RuntimeOrigin::signed(ALICE),
affidavit_payload.clone(),
signature.clone()
),
sp_runtime::DispatchError::BadOrigin
);
assert_noop!(
Pallet::declare(RuntimeOrigin::root(), affidavit_payload, signature),
sp_runtime::DispatchError::BadOrigin
);
})
}
#[test]
fn declare_affidavit_err_affidavit_author_not_found() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
init_fork_graph();
set_session_config();
CurrentSession::put(1);
set_default_users_balance_and_hold(vec![ALICE, BOB]).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(BOB, ALICE, 300).unwrap();
let afdt_id = generate_affidavit_id();
insert_active_afdt_key(afdt_id.clone()).unwrap();
ext_validate(ALICE, afdt_id.clone()).unwrap();
let for_session = CurrentSession::get() + 1;
assert!(AffidavitKeys::contains_key((for_session, afdt_id.clone())));
let next_adft_id = generate_affidavit_id();
let _public = get_public_key(afdt_id.clone()).unwrap();
let dummy_public = generate_affidavit_keypair();
let affidavit_payload = AffidavitPayloadOf {
public: dummy_public.clone(),
rotate: next_adft_id.clone(),
};
let signature = sign_payload(&affidavit_payload.encode(), dummy_public);
assert!(!AuthorOfAffidavits::contains_key((for_session, ALICE)));
System::set_block_number(AFDT_SUBMISSION_START);
assert_noop!(
Pallet::declare(RuntimeOrigin::none(), affidavit_payload, signature),
Error::AffidavitAuthorNotFound
);
})
}
#[test]
fn elect_authors_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, CHARLIE, AMY, NIX, MIKE, LAYA, DAVE, JIM];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
let public = get_public_key(alice_nxt_afdt_id).unwrap();
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
set_block_author(ALICE);
System::set_block_number(ELECTION_START);
assert_ok!(Pallet::elect(RuntimeOrigin::none(), payload, signature));
let actual_elected = Internals::reveal().unwrap();
let expected_elected = vec![BOB, MIKE, LAYA, DAVE, ALICE, ALAN];
assert_eq!(actual_elected, expected_elected);
let for_session = CurrentSession::get() + 1;
#[cfg(feature = "dev")]
System::assert_last_event(Event::ElectedInstance {
session: for_session,
runner: ALICE,
elects: actual_elected
}
.into()
);
#[cfg(not(feature = "dev"))]
System::assert_last_event(Event::ElectedInstance {
session: for_session,
runner: ALICE,
}
.into()
);
})
}
#[test]
fn elect_authors_err_bad_origin() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, CHARLIE, AMY, NIX, MIKE, LAYA, DAVE, JIM];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
let public = get_public_key(alice_nxt_afdt_id).unwrap();
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
set_block_author(ALICE);
System::set_block_number(ELECTION_START);
assert_err!(
Pallet::elect(
RuntimeOrigin::signed(ALICE),
payload.clone(),
signature.clone()
),
DispatchError::BadOrigin
);
assert_err!(
Pallet::elect(RuntimeOrigin::root(), payload.clone(), signature.clone()),
DispatchError::BadOrigin
);
})
}
#[test]
fn elect_authors_err_affidavit_author_not_found() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, CHARLIE, AMY, NIX, MIKE, LAYA, DAVE, JIM];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
let _public = get_public_key(alice_nxt_afdt_id).unwrap();
let dummy_public = generate_affidavit_keypair();
let payload = ElectionPayloadOf {
public: dummy_public.clone(),
};
let signature = sign_payload(&payload.encode(), dummy_public);
set_block_author(ALICE);
System::set_block_number(ELECTION_START);
assert_err!(
Pallet::elect(RuntimeOrigin::none(), payload, signature),
Error::AffidavitAuthorNotFound
);
})
}
#[test]
fn elect_authors_err_tried_electing_by_non_block_author() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, CHARLIE, AMY, NIX, MIKE, LAYA, DAVE, JIM];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
let public = get_public_key(alice_nxt_afdt_id).unwrap();
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
set_block_author(BOB);
System::set_block_number(ELECTION_START);
assert_err!(
Pallet::elect(RuntimeOrigin::none(), payload, signature),
Error::TriedElectingByNonBlockAuthor
);
})
}
#[cfg(feature = "dev")]
#[test]
fn inspect_elects_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, CHARLIE, AMY, NIX, MIKE, LAYA, DAVE, JIM];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB, ALAN, MIKE, LAYA, DAVE, JIM];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALAN, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
let mike_afdt_id = generate_affidavit_id();
let laya_afdt_id = generate_affidavit_id();
let dev_afdt_id = generate_affidavit_id();
let jim_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
ext_validate(ALAN, alan_afdt_id.clone()).unwrap();
ext_validate(MIKE, mike_afdt_id.clone()).unwrap();
ext_validate(LAYA, laya_afdt_id.clone()).unwrap();
ext_validate(DAVE, dev_afdt_id.clone()).unwrap();
ext_validate(JIM, jim_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alan_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let jim_nxt_afdt_id = generate_affidavit_id();
let mike_nxt_afdt_id = generate_affidavit_id();
let dev_nxt_afdt_id = generate_affidavit_id();
let laya_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let alan_payload = TestAfdtPayload {
active_afdt_pub: alan_afdt_id.clone(),
next_afdt_pub: alan_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
let mike_payload = TestAfdtPayload {
active_afdt_pub: mike_afdt_id.clone(),
next_afdt_pub: mike_nxt_afdt_id.clone(),
};
let laya_payload = TestAfdtPayload {
active_afdt_pub: laya_afdt_id.clone(),
next_afdt_pub: laya_nxt_afdt_id.clone(),
};
let jim_payload = TestAfdtPayload {
active_afdt_pub: jim_afdt_id.clone(),
next_afdt_pub: jim_nxt_afdt_id.clone(),
};
let dev_payload = TestAfdtPayload {
active_afdt_pub: dev_afdt_id.clone(),
next_afdt_pub: dev_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(ALAN, alan_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
ext_declare_affidavit(MIKE, mike_payload).unwrap();
ext_declare_affidavit(LAYA, laya_payload).unwrap();
ext_declare_affidavit(JIM, jim_payload).unwrap();
ext_declare_affidavit(DAVE, dev_payload).unwrap();
let public = get_public_key(alice_nxt_afdt_id).unwrap();
let payload = ElectionPayloadOf {
public: public.clone(),
};
let signature = sign_payload(&payload.encode(), public);
set_block_author(ALICE);
System::set_block_number(ELECTION_START);
assert_ok!(Pallet::elect(RuntimeOrigin::none(), payload, signature));
assert_ok!(Pallet::inspect_elects(RuntimeOrigin::signed(AMY)));
let expected_elects = vec![BOB, MIKE, LAYA, DAVE, ALICE, ALAN];
System::assert_last_event(
Event::InspectElects {
elects: expected_elects
}
.into()
);
})
}
#[cfg(feature = "dev")]
#[test]
fn prepare_validation_payload_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
System::set_block_number(10);
Pallet::offchain_worker(10);
assert_err!(
Pallet::prepare_validation_payload(RuntimeOrigin::signed(ALICE)),
Error::ActiveAfdtKeyNotYetFinalized
);
while System::block_number() < 30 {
ocw_step();
}
assert_ok!(Pallet::prepare_validation_payload(RuntimeOrigin::signed(ALICE)));
})
}
#[cfg(feature = "dev")]
#[test]
fn inspect_affidavit_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, BOB, ALAN, AMY, JIM, NIX, LAYA];
set_default_users_balance_and_hold(users).unwrap();
let authors = vec![ALICE, BOB];
enroll_authors_with_default_collateral(authors.clone()).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, BOB, SMALL_FUND).unwrap();
direct_fund_author(ALAN, BOB, LARGE_FUND).unwrap();
direct_fund_author(JIM, ALICE, SMALL_FUND).unwrap();
direct_fund_author(LAYA, ALICE, STANDARD_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
let bob_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
ext_validate(BOB, bob_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let bob_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
let bob_payload = TestAfdtPayload {
active_afdt_pub: bob_afdt_id.clone(),
next_afdt_pub: bob_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
ext_declare_affidavit(BOB, bob_payload).unwrap();
assert_ok!(Pallet::inspect_affidavit(RuntimeOrigin::signed(ALICE), alice_afdt_id.clone()));
let expected_affidavit = vec![(Funder::Direct(LAYA), STANDARD_FUND), (Funder::Direct(NIX), STANDARD_FUND), (Funder::Direct(JIM), SMALL_FUND)];
System::assert_last_event(
Event::InspectAffidavit {
author: ALICE,
afdt_id: alice_afdt_id,
session: 2,
affidavit: expected_affidavit
}
.into()
);
})
}
#[test]
fn force_genesis_config_err_bad_origin() {
chain_manager_test_ext().execute_with(|| {
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::signed(ALICE),
ForceGenesisConfig::AllowAffidavits(true)
),
sp_runtime::DispatchError::BadOrigin
);
});
}
#[test]
fn force_allow_affidavits_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(AllowAffidavits::get(), false);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AllowAffidavits(true)
));
assert_eq!(AllowAffidavits::get(), true);
});
}
#[test]
fn force_affidavit_begins_at_err_invalid_affidavit_period() {
chain_manager_test_ext().execute_with(|| {
AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitBeginsAt(Duration::from_rational(8u32, 10u32))
),
Error::InvalidAffidavitPeriod
);
});
}
#[test]
fn force_affidavit_ends_at_err_invalid_affidavit_period() {
chain_manager_test_ext().execute_with(|| {
AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitEndsAt(Duration::from_rational(2u32, 10u32))
),
Error::InvalidAffidavitPeriod
);
});
}
#[test]
fn force_affidavit_period_updates_correctly() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(
AffidavitBeginsAt::get(),
Duration::from_rational(2u32, 10u32)
);
assert_eq!(AffidavitEndsAt::get(), Duration::from_rational(8u32, 10u32));
assert_eq!(
ElectionBeginsAt::get(),
Duration::from_rational(5u32, 10u32)
);
let begin = Duration::from_rational(3u32, 10u32);
let end = Duration::from_rational(7u32, 10u32);
let election = Duration::from_rational(4u32, 10u32);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitBeginsAt(begin)
));
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitEndsAt(end)
));
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ElectionBeginsAt(election)
));
assert_eq!(AffidavitBeginsAt::get(), begin);
assert_eq!(AffidavitEndsAt::get(), end);
assert_eq!(ElectionBeginsAt::get(), election);
});
}
#[test]
fn force_election_runner_points_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(ElectionRunnerPointsUpgrade::get(), None);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ElectionRunnerPointsUpgrade(Some(10))
));
assert_eq!(ElectionRunnerPointsUpgrade::get(), Some(10));
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ElectionRunnerPointsUpgrade(None)
));
assert_eq!(ElectionRunnerPointsUpgrade::get(), None);
})
}
#[test]
fn force_validate_tx_priority_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(ValidateTxPriority::get(), 1_000_000);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ValidateTxPriority(1)
));
assert_eq!(ValidateTxPriority::get(), 1);
})
}
#[test]
fn force_validate_tx_priority_err_value_cannot_be_zero() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(ValidateTxPriority::get(), 1_000_000);
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ValidateTxPriority(0)
),
Error::ValueCannotBeZero
);
})
}
#[test]
fn force_affidavit_tx_priority_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(AffidavitTxPriority::get(), 850_000);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitTxPriority(2)
));
assert_eq!(AffidavitTxPriority::get(), 2);
})
}
#[test]
fn force_affidavit_tx_priority_err_value_cannot_be_zero() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(AffidavitTxPriority::get(), 850_000);
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::AffidavitTxPriority(0)
),
Error::ValueCannotBeZero
);
})
}
#[test]
fn force_election_tx_priority_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(ElectionTxPriority::get(), 700_000);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ElectionTxPriority(3)
));
assert_eq!(ElectionTxPriority::get(), 3);
})
}
#[test]
fn force_election_tx_priority_err_value_cannot_be_zero() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(ElectionTxPriority::get(), 700_000);
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::ElectionTxPriority(0)
),
Error::ValueCannotBeZero
);
})
}
#[test]
fn force_finality_after_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(FinalityAfter::get(), 60_000);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::FinalityAfter(90_000)
));
assert_eq!(FinalityAfter::get(), 90_000);
})
}
#[test]
fn force_finality_after_err_value_cannot_be_zero() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(FinalityAfter::get(), 60_000);
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::FinalityAfter(0)
),
Error::ValueCannotBeZero
);
})
}
#[test]
fn force_finality_ticks_success() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(FinalityTicks::get(), 5);
assert_ok!(ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::FinalityTicks(3)
));
assert_eq!(FinalityTicks::get(), 3);
})
}
#[test]
fn force_finality_ticks_err_value_cannot_be_zero() {
chain_manager_test_ext().execute_with(|| {
assert_eq!(FinalityTicks::get(), 5);
assert_noop!(
ChainManager::force_genesis_config(
RuntimeOrigin::root(),
ForceGenesisConfig::FinalityTicks(0)
),
Error::ValueCannotBeZero
);
})
}
// ===============================================================================
// ````````````````````````````````` PUBLIC APIS `````````````````````````````````
// ===============================================================================
#[test]
fn is_validating_success() {
chain_manager_test_ext().execute_with(|| {
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE, BOB, ALAN]).unwrap();
let alice_id = Pallet::convert(ALICE).unwrap();
let bob_id = Pallet::convert(BOB).unwrap();
Validators::put(vec![bob_id, alice_id]);
assert!(Pallet::is_validating(ALICE));
assert!(Pallet::is_validating(BOB));
assert!(!Pallet::is_validating(ALAN));
})
}
#[test]
fn get_runtime_afdt_key_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE, BOB, ALAN]).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
CurrentSession::put(1);
let next_session = CurrentSession::get() + 1;
let next_afdt_session = next_session + 1;
AffidavitKeys::insert((next_session, alice_afdt_id.clone()), ALICE);
AffidavitKeys::insert((next_afdt_session, alan_afdt_id.clone()), ALAN);
let alice_active_afdt_key = Pallet::get_runtime_afdt_key(ALICE);
let bob_active_afdt_key = Pallet::get_runtime_afdt_key(BOB);
let alan_active_afdt_key = Pallet::get_runtime_afdt_key(ALAN);
assert_ok!(alan_active_afdt_key.clone());
assert_ok!(alice_active_afdt_key. clone());
assert_err!(bob_active_afdt_key, Error::AffidavitKeyPairNotFound);
assert_eq!(
alan_active_afdt_key.unwrap(),
(next_afdt_session, alan_afdt_id)
);
assert_eq!(
alice_active_afdt_key.unwrap(),
(next_session, alice_afdt_id)
);
})
}
#[test]
fn is_chilling_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE, BOB, ALAN]).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
CurrentSession::put(1);
let next_session = CurrentSession::get() + 1;
let next_afdt_session = next_session + 1;
AffidavitKeys::insert((next_session, alice_afdt_id), ALICE);
AffidavitKeys::insert((next_afdt_session, alan_afdt_id), ALAN);
assert!(!Pallet::is_chilling(ALICE));
assert!(!Pallet::is_chilling(ALAN));
assert!(Pallet::is_chilling(BOB));
})
}
#[test]
fn get_finalized_afdt_key_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
System::set_block_number(10);
Pallet::offchain_worker(10);
let active_afdt = Pallet::get_finalized_afdt_key();
assert_err!(active_afdt, Error::ActiveAfdtKeyNotYetFinalized);
while System::block_number() < 30 {
ocw_step();
}
let active_afdt = Pallet::get_finalized_afdt_key();
assert_ok!(active_afdt);
})
}
#[test]
fn sign_validate_payload_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
System::set_block_number(10);
Pallet::offchain_worker(10);
let sign_payload = Pallet::sign_validate_payload();
assert_err!(sign_payload, Error::ActiveAfdtKeyNotYetFinalized);
while System::block_number() < 30 {
ocw_step();
}
let sign_payload = Pallet::sign_validate_payload();
assert_ok!(sign_payload);
})
}
#[test]
fn get_public_key_sucess() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
System::set_block_number(10);
Pallet::offchain_worker(10);
while System::block_number() < 30 {
ocw_step();
}
let afdt_key = Pallet::get_finalized_afdt_key().unwrap();
let pub_key = Pallet::get_public_key(afdt_key);
assert_ok!(pub_key);
})
}
#[test]
fn get_elects_success() {
chain_manager_test_ext().execute_with(|| {
let users = vec![ALICE, CHARLIE, ALAN, MIKE, BOB, NIX];
set_default_users_balance_and_hold(users).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
RoleAdapter::enroll(&BOB, 200, Fortitude::Force).unwrap();
RoleAdapter::enroll(&MIKE, 200, Fortitude::Force).unwrap();
RoleAdapter::fund(
&ALICE,
&Funder::Direct(CHARLIE),
100,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
RoleAdapter::fund(
&BOB,
&Funder::Direct(ALAN),
150,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
RoleAdapter::fund(
&MIKE,
&Funder::Direct(NIX),
125,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
System::set_block_number(10);
SessionStartsAt::put(15);
AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
ElectionBeginsAt::put(Duration::from_rational(5u32, 10u32));
System::set_block_number(15);
System::set_block_number(135);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_B), BOB);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_C), MIKE);
let affidavit_alice_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit_alice_id).unwrap();
let affidavit_bob_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_B).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_B, &affidavit_bob_id).unwrap();
let affidavit_mike_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_C).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_C, &affidavit_mike_id).unwrap();
System::set_block_number(315);
assert_ok!(Internals::prepare_election(&Some(ALICE)));
let actual_elects = Pallet::get_elects().unwrap();
let expected_reveal = vec![BOB, MIKE, ALICE];
assert_eq!(actual_elects, expected_reveal);
})
}
#[test]
fn get_elects_returns_err_unable_to_reveal_elected() {
chain_manager_test_ext().execute_with(|| {
let users = vec![ALICE, CHARLIE, ALAN, MIKE, BOB, NIX];
set_default_users_balance_and_hold(users).unwrap();
RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
RoleAdapter::enroll(&BOB, 200, Fortitude::Force).unwrap();
RoleAdapter::enroll(&MIKE, 200, Fortitude::Force).unwrap();
RoleAdapter::fund(
&ALICE,
&Funder::Direct(CHARLIE),
100,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
RoleAdapter::fund(
&BOB,
&Funder::Direct(ALAN),
150,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
RoleAdapter::fund(
&MIKE,
&Funder::Direct(NIX),
125,
Precision::Exact,
Fortitude::Force,
)
.unwrap();
System::set_block_number(10);
SessionStartsAt::put(15);
AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
ElectionBeginsAt::put(Duration::from_rational(5u32, 10u32));
System::set_block_number(15);
System::set_block_number(135);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_B), BOB);
AffidavitKeys::insert((1, AFFIDAVIT_KEY_C), MIKE);
let affidavit_alice_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit_alice_id).unwrap();
let affidavit_bob_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_B).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_B, &affidavit_bob_id).unwrap();
let affidavit_mike_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_C).unwrap();
Pallet::submit_affidavit(&AFFIDAVIT_KEY_C, &affidavit_mike_id).unwrap();
let elects = Pallet::get_elects();
assert_err!(elects, Error::UnableToRevealElected);
})
}
#[test]
fn fetch_affidavit_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, NIX, AMY, CHARLIE];
set_default_users_balance_and_hold(users).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, ALICE, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALICE, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
let actual_affidavit = Pallet::fetch_affidavit(alice_afdt_id.clone()).unwrap();
let expected_affidavit = vec![(Funder::Direct(NIX), STANDARD_FUND), (Funder::Direct(CHARLIE), LARGE_FUND), (Funder::Direct(AMY), SMALL_FUND)];
assert_eq!(actual_affidavit, expected_affidavit);
assert!(Pallet::fetch_affidavit(alice_nxt_afdt_id).is_err());
})
}
#[test]
fn fetch_affidavit_for_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, NIX, AMY, CHARLIE];
set_default_users_balance_and_hold(users).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
direct_fund_author(AMY, ALICE, SMALL_FUND).unwrap();
direct_fund_author(CHARLIE, ALICE, LARGE_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
let for_session = CurrentSession::get() + 1;
let actual_affidavit = Pallet::fetch_affidavit_for(alice_afdt_id.clone(), for_session).unwrap();
let expected_affidavit = vec![(Funder::Direct(NIX), STANDARD_FUND), (Funder::Direct(CHARLIE), LARGE_FUND), (Funder::Direct(AMY), SMALL_FUND)];
assert_eq!(actual_affidavit, expected_affidavit);
let for_session = CurrentSession::get() + 2;
assert_err!(Pallet::fetch_affidavit_for(alice_afdt_id, for_session), Error::AffidavitKeyPairNotFound);
})
}
#[test]
fn is_contesting_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
let users = vec![ALICE, NIX];
set_default_users_balance_and_hold(users).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
direct_fund_author(NIX, ALICE, STANDARD_FUND).unwrap();
let alice_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
let alice_nxt_afdt_id = generate_affidavit_id();
let alice_payload = TestAfdtPayload {
active_afdt_pub: alice_afdt_id.clone(),
next_afdt_pub: alice_nxt_afdt_id.clone(),
};
System::set_block_number(AFDT_SUBMISSION_START);
ext_declare_affidavit(ALICE, alice_payload).unwrap();
assert!(Pallet::is_contesting(ALICE));
assert!(!Pallet::is_contesting(NIX));
})
}
#[test]
fn is_pursuing_success() {
let mut env = new_ocw_env();
env.ext.execute_with(|| {
set_default_user_balance_and_hold(ALICE).unwrap();
set_default_user_balance_and_hold(BOB).unwrap();
set_default_user_balance_and_hold(ALAN).unwrap();
enroll_authors_with_default_collateral(vec![ALICE, BOB, ALAN]).unwrap();
let alice_afdt_id = generate_affidavit_id();
let alan_afdt_id = generate_affidavit_id();
CurrentSession::put(1);
let next_session = CurrentSession::get() + 1;
let next_afdt_session = next_session + 1;
AffidavitKeys::insert((next_session, alice_afdt_id), ALICE);
AffidavitKeys::insert((next_afdt_session, alan_afdt_id), ALAN);
assert!(Pallet::is_pursuing(ALICE));
assert!(Pallet::is_pursuing(ALAN));
assert!(!Pallet::is_pursuing(BOB));
})
}
#[test]
fn can_declare_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
let alice_afdt_id = generate_affidavit_id();
System::set_block_number(150);
ext_validate(ALICE, alice_afdt_id.clone()).unwrap();
assert_ok!(Pallet::can_declare(alice_afdt_id));
})
}
#[test]
fn can_declare_err_affidavit_author_not_found() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
let alice_afdt_id = generate_affidavit_id();
assert_err!(Pallet::can_declare(alice_afdt_id), Error::AffidavitAuthorNotFound);
})
}
#[test]
fn can_elect_success() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
System::set_block_number(450);
set_block_author(ALICE);
assert_ok!(Pallet::can_elect(ALICE));
})
}
#[test]
fn can_elect_err_not_a_block_author() {
let mut env = new_ocw_env();
env.ext.execute_with(||{
set_session_config();
CurrentSession::put(1);
set_default_user_balance_and_hold(BOB).unwrap();
enroll_author_with_default_collateral(BOB).unwrap();
set_default_user_balance_and_hold(ALICE).unwrap();
enroll_author_with_default_collateral(ALICE).unwrap();
System::set_block_number(450);
set_block_author(ALICE);
assert_err!(Pallet::can_elect(BOB), Error::NotABlockAuthor);
})
}
}