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
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Runtime component for handling disputes of parachain candidates.

use crate::{
	configuration::{self, HostConfiguration},
	initializer::SessionChangeNotification,
	session_info,
};
use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0};
use frame_support::{ensure, storage::TransactionOutcome, traits::Get, weights::Weight};
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{
	byzantine_threshold, supermajority_threshold, ApprovalVote, CandidateHash, CompactStatement,
	ConsensusLog, DisputeState, DisputeStatement, DisputeStatementSet, ExplicitDisputeStatement,
	InvalidDisputeStatementKind, MultiDisputeStatementSet, SessionIndex, SigningContext,
	ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature,
};
use scale_info::TypeInfo;
use sp_runtime::{
	traits::{AppVerify, One, Saturating, Zero},
	DispatchError, RuntimeDebug, SaturatedConversion,
};
use sp_std::{collections::btree_set::BTreeSet, prelude::*};

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub use crate::Origin as ParachainOrigin;

/// Whether the dispute is local or remote.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum DisputeLocation {
	Local,
	Remote,
}

/// The result of a dispute, whether the candidate is deemed valid (for) or invalid (against).
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum DisputeResult {
	Valid,
	Invalid,
}

/// Reward hooks for disputes.
pub trait RewardValidators {
	// Give each validator a reward, likely small, for participating in the dispute.
	fn reward_dispute_statement(
		session: SessionIndex,
		validators: impl IntoIterator<Item = ValidatorIndex>,
	);
}

impl RewardValidators for () {
	fn reward_dispute_statement(_: SessionIndex, _: impl IntoIterator<Item = ValidatorIndex>) {}
}

/// Punishment hooks for disputes.
pub trait PunishValidators {
	/// Punish a series of validators who were for an invalid parablock. This is expected to be a major
	/// punishment.
	fn punish_for_invalid(
		session: SessionIndex,
		validators: impl IntoIterator<Item = ValidatorIndex>,
	);

	/// Punish a series of validators who were against a valid parablock. This is expected to be a minor
	/// punishment.
	fn punish_against_valid(
		session: SessionIndex,
		validators: impl IntoIterator<Item = ValidatorIndex>,
	);

	/// Punish a series of validators who were part of a dispute which never concluded. This is expected
	/// to be a minor punishment.
	fn punish_inconclusive(
		session: SessionIndex,
		validators: impl IntoIterator<Item = ValidatorIndex>,
	);
}

impl PunishValidators for () {
	fn punish_for_invalid(_: SessionIndex, _: impl IntoIterator<Item = ValidatorIndex>) {}

	fn punish_against_valid(_: SessionIndex, _: impl IntoIterator<Item = ValidatorIndex>) {}

	fn punish_inconclusive(_: SessionIndex, _: impl IntoIterator<Item = ValidatorIndex>) {}
}

/// Hook into disputes handling.
///
/// Allows decoupling parachains handling from disputes so that it can
/// potentially be disabled when instantiating a specific runtime.
pub trait DisputesHandler<BlockNumber> {
	/// Whether the chain is frozen, if the chain is frozen it will not accept
	/// any new parachain blocks for backing or inclusion.
	fn is_frozen() -> bool;

	/// Handler for filtering any dispute statements before including them as part
	/// of inherent data. This can be useful to filter out ancient and duplicate
	/// dispute statements.
	fn filter_multi_dispute_data(statement_sets: &mut MultiDisputeStatementSet);

	/// Handle sets of dispute statements corresponding to 0 or more candidates.
	/// Returns a vector of freshly created disputes.
	fn provide_multi_dispute_data(
		statement_sets: MultiDisputeStatementSet,
	) -> Result<Vec<(SessionIndex, CandidateHash)>, DispatchError>;

	/// Note that the given candidate has been included.
	fn note_included(
		session: SessionIndex,
		candidate_hash: CandidateHash,
		included_in: BlockNumber,
	);

	/// Retrieve the included state of a given candidate in a particular session. If it
	/// returns `Some`, then we have a local dispute for the given `candidate_hash`.
	fn included_state(session: SessionIndex, candidate_hash: CandidateHash) -> Option<BlockNumber>;

	/// Whether the given candidate concluded invalid in a dispute with supermajority.
	fn concluded_invalid(session: SessionIndex, candidate_hash: CandidateHash) -> bool;

	/// Called by the initializer to initialize the configuration module.
	fn initializer_initialize(now: BlockNumber) -> Weight;

	/// Called by the initializer to finalize the configuration module.
	fn initializer_finalize();

	/// Called by the initializer to note that a new session has started.
	fn initializer_on_new_session(notification: &SessionChangeNotification<BlockNumber>);
}

impl<BlockNumber> DisputesHandler<BlockNumber> for () {
	fn is_frozen() -> bool {
		false
	}

	fn filter_multi_dispute_data(statement_sets: &mut MultiDisputeStatementSet) {
		statement_sets.clear()
	}

	fn provide_multi_dispute_data(
		_statement_sets: MultiDisputeStatementSet,
	) -> Result<Vec<(SessionIndex, CandidateHash)>, DispatchError> {
		Ok(Vec::new())
	}

	fn note_included(
		_session: SessionIndex,
		_candidate_hash: CandidateHash,
		_included_in: BlockNumber,
	) {
	}

	fn included_state(
		_session: SessionIndex,
		_candidate_hash: CandidateHash,
	) -> Option<BlockNumber> {
		None
	}

	fn concluded_invalid(_session: SessionIndex, _candidate_hash: CandidateHash) -> bool {
		false
	}

	fn initializer_initialize(_now: BlockNumber) -> Weight {
		0
	}

	fn initializer_finalize() {}

	fn initializer_on_new_session(_notification: &SessionChangeNotification<BlockNumber>) {}
}

impl<T: Config> DisputesHandler<T::BlockNumber> for pallet::Pallet<T> {
	fn is_frozen() -> bool {
		pallet::Pallet::<T>::is_frozen()
	}

	fn filter_multi_dispute_data(statement_sets: &mut MultiDisputeStatementSet) {
		pallet::Pallet::<T>::filter_multi_dispute_data(statement_sets)
	}

	fn provide_multi_dispute_data(
		statement_sets: MultiDisputeStatementSet,
	) -> Result<Vec<(SessionIndex, CandidateHash)>, DispatchError> {
		pallet::Pallet::<T>::provide_multi_dispute_data(statement_sets)
	}

	fn note_included(
		session: SessionIndex,
		candidate_hash: CandidateHash,
		included_in: T::BlockNumber,
	) {
		pallet::Pallet::<T>::note_included(session, candidate_hash, included_in)
	}

	fn included_state(
		session: SessionIndex,
		candidate_hash: CandidateHash,
	) -> Option<T::BlockNumber> {
		pallet::Pallet::<T>::included_state(session, candidate_hash)
	}

	fn concluded_invalid(session: SessionIndex, candidate_hash: CandidateHash) -> bool {
		pallet::Pallet::<T>::concluded_invalid(session, candidate_hash)
	}

	fn initializer_initialize(now: T::BlockNumber) -> Weight {
		pallet::Pallet::<T>::initializer_initialize(now)
	}

	fn initializer_finalize() {
		pallet::Pallet::<T>::initializer_finalize()
	}

	fn initializer_on_new_session(notification: &SessionChangeNotification<T::BlockNumber>) {
		pallet::Pallet::<T>::initializer_on_new_session(notification)
	}
}

pub trait WeightInfo {
	fn force_unfreeze() -> Weight;
}

pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
	fn force_unfreeze() -> Weight {
		0
	}
}

pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::pallet_prelude::*;

	#[pallet::config]
	pub trait Config: frame_system::Config + configuration::Config + session_info::Config {
		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
		type RewardValidators: RewardValidators;
		type PunishValidators: PunishValidators;

		/// Weight information for extrinsics in this pallet.
		type WeightInfo: WeightInfo;
	}

	#[pallet::pallet]
	pub struct Pallet<T>(_);

	/// The last pruned session, if any. All data stored by this module
	/// references sessions.
	#[pallet::storage]
	pub(super) type LastPrunedSession<T> = StorageValue<_, SessionIndex>;

	/// All ongoing or concluded disputes for the last several sessions.
	#[pallet::storage]
	pub(super) type Disputes<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		SessionIndex,
		Blake2_128Concat,
		CandidateHash,
		DisputeState<T::BlockNumber>,
	>;

	/// All included blocks on the chain, as well as the block number in this chain that
	/// should be reverted back to if the candidate is disputed and determined to be invalid.
	#[pallet::storage]
	pub(super) type Included<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		SessionIndex,
		Blake2_128Concat,
		CandidateHash,
		T::BlockNumber,
	>;

	/// Maps session indices to a vector indicating the number of potentially-spam disputes
	/// each validator is participating in. Potentially-spam disputes are remote disputes which have
	/// fewer than `byzantine_threshold + 1` validators.
	///
	/// The i'th entry of the vector corresponds to the i'th validator in the session.
	#[pallet::storage]
	pub(super) type SpamSlots<T> = StorageMap<_, Twox64Concat, SessionIndex, Vec<u32>>;

	/// Whether the chain is frozen. Starts as `None`. When this is `Some`,
	/// the chain will not accept any new parachain blocks for backing or inclusion,
	/// and its value indicates the last valid block number in the chain.
	/// It can only be set back to `None` by governance intervention.
	#[pallet::storage]
	#[pallet::getter(fn last_valid_block)]
	pub(super) type Frozen<T: Config> = StorageValue<_, Option<T::BlockNumber>, ValueQuery>;

	#[pallet::event]
	#[pallet::generate_deposit(pub fn deposit_event)]
	pub enum Event<T: Config> {
		/// A dispute has been initiated. \[candidate hash, dispute location\]
		DisputeInitiated(CandidateHash, DisputeLocation),
		/// A dispute has concluded for or against a candidate.
		/// `\[para id, candidate hash, dispute result\]`
		DisputeConcluded(CandidateHash, DisputeResult),
		/// A dispute has timed out due to insufficient participation.
		/// `\[para id, candidate hash\]`
		DisputeTimedOut(CandidateHash),
		/// A dispute has concluded with supermajority against a candidate.
		/// Block authors should no longer build on top of this head and should
		/// instead revert the block at the given height. This should be the
		/// number of the child of the last known valid block in the chain.
		Revert(T::BlockNumber),
	}

	#[pallet::error]
	pub enum Error<T> {
		/// Duplicate dispute statement sets provided.
		DuplicateDisputeStatementSets,
		/// Ancient dispute statement provided.
		AncientDisputeStatement,
		/// Validator index on statement is out of bounds for session.
		ValidatorIndexOutOfBounds,
		/// Invalid signature on statement.
		InvalidSignature,
		/// Validator vote submitted more than once to dispute.
		DuplicateStatement,
		/// Too many spam slots used by some specific validator.
		PotentialSpam,
		/// A dispute where there are only votes on one side.
		SingleSidedDispute,
	}

	#[pallet::origin]
	pub type Origin = ParachainOrigin;

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		#[pallet::weight(<T as Config>::WeightInfo::force_unfreeze())]
		pub fn force_unfreeze(origin: OriginFor<T>) -> DispatchResult {
			ensure_root(origin)?;
			Frozen::<T>::set(None);
			Ok(())
		}
	}
}

bitflags::bitflags! {
	#[derive(Default)]
	struct DisputeStateFlags: u8 {
		const CONFIRMED = 0b0001;
		const FOR_SUPERMAJORITY = 0b0010;
		const AGAINST_SUPERMAJORITY = 0b0100;
	}
}

impl DisputeStateFlags {
	fn from_state<BlockNumber>(state: &DisputeState<BlockNumber>) -> Self {
		let n = state.validators_for.len();

		let byzantine_threshold = byzantine_threshold(n);
		let supermajority_threshold = supermajority_threshold(n);

		let mut flags = DisputeStateFlags::default();
		let all_participants = {
			let mut a = state.validators_for.clone();
			*a |= state.validators_against.iter().by_val();
			a
		};
		if all_participants.count_ones() > byzantine_threshold {
			flags |= DisputeStateFlags::CONFIRMED;
		}

		if state.validators_for.count_ones() >= supermajority_threshold {
			flags |= DisputeStateFlags::FOR_SUPERMAJORITY;
		}

		if state.validators_against.count_ones() >= supermajority_threshold {
			flags |= DisputeStateFlags::AGAINST_SUPERMAJORITY;
		}

		flags
	}
}

#[derive(PartialEq, RuntimeDebug)]
enum SpamSlotChange {
	Inc,
	Dec,
}

struct ImportSummary<BlockNumber> {
	// The new state, with all votes imported.
	state: DisputeState<BlockNumber>,
	// Changes to spam slots. Validator index paired with directional change.
	spam_slot_changes: Vec<(ValidatorIndex, SpamSlotChange)>,
	// Validators to slash for being (wrongly) on the AGAINST side.
	slash_against: Vec<ValidatorIndex>,
	// Validators to slash for being (wrongly) on the FOR side.
	slash_for: Vec<ValidatorIndex>,
	// New participants in the dispute.
	new_participants: bitvec::vec::BitVec<BitOrderLsb0, u8>,
	// Difference in state flags from previous.
	new_flags: DisputeStateFlags,
}

#[derive(RuntimeDebug, PartialEq, Eq)]
enum VoteImportError {
	ValidatorIndexOutOfBounds,
	DuplicateStatement,
}

impl<T: Config> From<VoteImportError> for Error<T> {
	fn from(e: VoteImportError) -> Self {
		match e {
			VoteImportError::ValidatorIndexOutOfBounds => Error::<T>::ValidatorIndexOutOfBounds,
			VoteImportError::DuplicateStatement => Error::<T>::DuplicateStatement,
		}
	}
}

#[derive(RuntimeDebug, PartialEq, Eq)]
struct ImportUndo {
	validator_index: ValidatorIndex,
	valid: bool,
	new_participant: bool,
}

struct DisputeStateImporter<BlockNumber> {
	state: DisputeState<BlockNumber>,
	now: BlockNumber,
	new_participants: bitvec::vec::BitVec<BitOrderLsb0, u8>,
	pre_flags: DisputeStateFlags,
}

impl<BlockNumber: Clone> DisputeStateImporter<BlockNumber> {
	fn new(state: DisputeState<BlockNumber>, now: BlockNumber) -> Self {
		let pre_flags = DisputeStateFlags::from_state(&state);
		let new_participants = bitvec::bitvec![BitOrderLsb0, u8; 0; state.validators_for.len()];

		DisputeStateImporter { state, now, new_participants, pre_flags }
	}

	fn import(
		&mut self,
		validator: ValidatorIndex,
		valid: bool,
	) -> Result<ImportUndo, VoteImportError> {
		let (bits, other_bits) = if valid {
			(&mut self.state.validators_for, &mut self.state.validators_against)
		} else {
			(&mut self.state.validators_against, &mut self.state.validators_for)
		};

		// out of bounds or already participated
		match bits.get(validator.0 as usize).map(|b| *b) {
			None => return Err(VoteImportError::ValidatorIndexOutOfBounds),
			Some(true) => return Err(VoteImportError::DuplicateStatement),
			Some(false) => {},
		}

		// inefficient, and just for extra sanity.
		if validator.0 as usize >= self.new_participants.len() {
			return Err(VoteImportError::ValidatorIndexOutOfBounds)
		}

		let mut undo = ImportUndo { validator_index: validator, valid, new_participant: false };

		bits.set(validator.0 as usize, true);

		// New participants tracks those which didn't appear on either
		// side of the dispute until now. So we check the other side
		// and checked the first side before.
		if other_bits.get(validator.0 as usize).map_or(false, |b| !*b) {
			undo.new_participant = true;
			self.new_participants.set(validator.0 as usize, true);
		}

		Ok(undo)
	}

	fn undo(&mut self, undo: ImportUndo) {
		if undo.valid {
			self.state.validators_for.set(undo.validator_index.0 as usize, false);
		} else {
			self.state.validators_against.set(undo.validator_index.0 as usize, false);
		}

		if undo.new_participant {
			self.new_participants.set(undo.validator_index.0 as usize, false);
		}
	}

	fn finish(mut self) -> ImportSummary<BlockNumber> {
		let pre_flags = self.pre_flags;
		let post_flags = DisputeStateFlags::from_state(&self.state);

		let pre_post_contains = |flags| (pre_flags.contains(flags), post_flags.contains(flags));

		// 1. Act on confirmed flag state to inform spam slots changes.
		let spam_slot_changes: Vec<_> = match pre_post_contains(DisputeStateFlags::CONFIRMED) {
			(false, false) => {
				// increment spam slots for all new participants.
				self.new_participants
					.iter_ones()
					.map(|i| (ValidatorIndex(i as _), SpamSlotChange::Inc))
					.collect()
			},
			(false, true) => {
				let prev_participants = {
					// all participants
					let mut a = self.state.validators_for.clone();
					*a |= self.state.validators_against.iter().by_val();

					// which are not new participants
					*a &= self.new_participants.iter().by_val().map(|b| !b);

					a
				};

				prev_participants
					.iter_ones()
					.map(|i| (ValidatorIndex(i as _), SpamSlotChange::Dec))
					.collect()
			},
			(true, true) | (true, false) => {
				// nothing to do. (true, false) is also impossible.
				Vec::new()
			},
		};

		// 2. Check for fresh FOR supermajority. Only if not already concluded.
		let slash_against =
			if let (false, true) = pre_post_contains(DisputeStateFlags::FOR_SUPERMAJORITY) {
				if self.state.concluded_at.is_none() {
					self.state.concluded_at = Some(self.now.clone());
				}

				// provide AGAINST voters to slash.
				self.state
					.validators_against
					.iter_ones()
					.map(|i| ValidatorIndex(i as _))
					.collect()
			} else {
				Vec::new()
			};

		// 3. Check for fresh AGAINST supermajority.
		let slash_for =
			if let (false, true) = pre_post_contains(DisputeStateFlags::AGAINST_SUPERMAJORITY) {
				if self.state.concluded_at.is_none() {
					self.state.concluded_at = Some(self.now.clone());
				}

				// provide FOR voters to slash.
				self.state.validators_for.iter_ones().map(|i| ValidatorIndex(i as _)).collect()
			} else {
				Vec::new()
			};

		ImportSummary {
			state: self.state,
			spam_slot_changes,
			slash_against,
			slash_for,
			new_participants: self.new_participants,
			new_flags: post_flags - pre_flags,
		}
	}
}

// A filter on a dispute statement set.
#[derive(PartialEq)]
#[cfg_attr(test, derive(Debug))]
enum StatementSetFilter {
	// Remove the entire dispute statement set.
	RemoveAll,
	// Remove the votes with given index from the statement set.
	RemoveIndices(Vec<usize>),
}

impl StatementSetFilter {
	fn filter_statement_set(
		self,
		mut statement_set: DisputeStatementSet,
	) -> Option<DisputeStatementSet> {
		match self {
			StatementSetFilter::RemoveAll => None,
			StatementSetFilter::RemoveIndices(mut indices) => {
				indices.sort();
				indices.dedup();

				// reverse order ensures correctness
				for index in indices.into_iter().rev() {
					// swap_remove guarantees linear complexity.
					statement_set.statements.swap_remove(index);
				}

				if statement_set.statements.is_empty() {
					None
				} else {
					Some(statement_set)
				}
			},
		}
	}

	fn remove_index(&mut self, i: usize) {
		if let StatementSetFilter::RemoveIndices(ref mut indices) = *self {
			indices.push(i)
		}
	}
}

impl<T: Config> Pallet<T> {
	/// Called by the initializer to initialize the disputes module.
	pub(crate) fn initializer_initialize(now: T::BlockNumber) -> Weight {
		let config = <configuration::Pallet<T>>::config();

		let mut weight = 0;
		for (session_index, candidate_hash, mut dispute) in <Disputes<T>>::iter() {
			weight += T::DbWeight::get().reads_writes(1, 0);

			if dispute.concluded_at.is_none() &&
				dispute.start + config.dispute_conclusion_by_time_out_period < now
			{
				Self::deposit_event(Event::DisputeTimedOut(candidate_hash));

				dispute.concluded_at = Some(now);
				<Disputes<T>>::insert(session_index, candidate_hash, &dispute);

				if <Included<T>>::contains_key(&session_index, &candidate_hash) {
					// Local disputes don't count towards spam.

					weight += T::DbWeight::get().reads_writes(1, 1);
					continue
				}

				// mildly punish all validators involved. they've failed to make
				// data available to others, so this is most likely spam.
				SpamSlots::<T>::mutate(session_index, |spam_slots| {
					let spam_slots = match spam_slots {
						Some(ref mut s) => s,
						None => return,
					};

					// also reduce spam slots for all validators involved, if the dispute was unconfirmed.
					// this does open us up to more spam, but only for validators who are willing
					// to be punished more.
					//
					// it would be unexpected for any change here to occur when the dispute has not concluded
					// in time, as a dispute guaranteed to have at least one honest participant should
					// conclude quickly.
					let participating = decrement_spam(spam_slots, &dispute);

					// Slight punishment as these validators have failed to make data available to
					// others in a timely manner.
					T::PunishValidators::punish_inconclusive(
						session_index,
						participating.iter_ones().map(|i| ValidatorIndex(i as _)),
					);
				});

				weight += T::DbWeight::get().reads_writes(2, 2);
			}
		}

		weight
	}

	/// Called by the initializer to finalize the disputes module.
	pub(crate) fn initializer_finalize() {}

	/// Called by the initializer to note a new session in the disputes module.
	pub(crate) fn initializer_on_new_session(
		notification: &SessionChangeNotification<T::BlockNumber>,
	) {
		let config = <configuration::Pallet<T>>::config();

		if notification.session_index <= config.dispute_period + 1 {
			return
		}

		let pruning_target = notification.session_index - config.dispute_period - 1;

		LastPrunedSession::<T>::mutate(|last_pruned| {
			let to_prune = if let Some(last_pruned) = last_pruned {
				*last_pruned + 1..=pruning_target
			} else {
				pruning_target..=pruning_target
			};

			for to_prune in to_prune {
				// This should be small, as disputes are rare, so `None` is fine.
				<Disputes<T>>::remove_prefix(to_prune, None);

				// This is larger, and will be extracted to the `shared` module for more proper pruning.
				// TODO: https://github.com/paritytech/polkadot/issues/3469
				<Included<T>>::remove_prefix(to_prune, None);
				SpamSlots::<T>::remove(to_prune);
			}

			*last_pruned = Some(pruning_target);
		});
	}

	/// Handle sets of dispute statements corresponding to 0 or more candidates.
	/// Returns a vector of freshly created disputes.
	///
	/// # Warning
	///
	/// This functions modifies the state when failing. It is expected to be called in inherent,
	/// and to fail the extrinsic on error. As invalid inherents are not allowed, the dirty state
	/// is not committed.
	pub(crate) fn provide_multi_dispute_data(
		statement_sets: MultiDisputeStatementSet,
	) -> Result<Vec<(SessionIndex, CandidateHash)>, DispatchError> {
		let config = <configuration::Pallet<T>>::config();

		// Deduplicate.
		{
			let mut targets: Vec<_> =
				statement_sets.iter().map(|set| (set.candidate_hash.0, set.session)).collect();

			targets.sort();

			let submitted = targets.len();
			targets.dedup();

			ensure!(submitted == targets.len(), Error::<T>::DuplicateDisputeStatementSets);
		}

		let mut fresh = Vec::with_capacity(statement_sets.len());
		for statement_set in statement_sets {
			let dispute_target = (statement_set.session, statement_set.candidate_hash);
			if Self::provide_dispute_data(&config, statement_set)? {
				fresh.push(dispute_target);
			}
		}

		Ok(fresh)
	}

	/// Removes all duplicate disputes.
	fn filter_multi_dispute_data(statement_sets: &mut MultiDisputeStatementSet) {
		frame_support::storage::with_transaction(|| {
			let config = <configuration::Pallet<T>>::config();

			let old_statement_sets = sp_std::mem::take(statement_sets);

			// Deduplicate.
			let dedup_iter = {
				let mut targets = BTreeSet::new();
				old_statement_sets.into_iter().filter(move |set| {
					let target = (set.candidate_hash, set.session);
					targets.insert(target)
				})
			};

			*statement_sets = dedup_iter
				.filter_map(|set| {
					let filter = Self::filter_dispute_data(&config, &set);

					filter.filter_statement_set(set)
				})
				.collect();
			TransactionOutcome::Rollback(())
		})
	}

	// Given a statement set, this produces a filter to be applied to the statement set.
	// It either removes the entire dispute statement set or some specific votes from it.
	//
	// Votes which are duplicate or already known by the chain are filtered out.
	// The entire set is removed if the dispute is ancient or concluded.
	fn filter_dispute_data(
		config: &HostConfiguration<T::BlockNumber>,
		set: &DisputeStatementSet,
	) -> StatementSetFilter {
		let mut filter = StatementSetFilter::RemoveIndices(Vec::new());

		// Dispute statement sets on any dispute which concluded
		// before this point are to be rejected.
		let now = <frame_system::Pallet<T>>::block_number();
		let oldest_accepted = now.saturating_sub(config.dispute_post_conclusion_acceptance_period);

		// Load session info to access validators
		let session_info = match <session_info::Pallet<T>>::session_info(set.session) {
			Some(s) => s,
			None => return StatementSetFilter::RemoveAll,
		};

		let n_validators = session_info.validators.len();

		// Check for ancient.
		let dispute_state = {
			if let Some(dispute_state) = <Disputes<T>>::get(&set.session, &set.candidate_hash) {
				if dispute_state.concluded_at.as_ref().map_or(false, |c| c < &oldest_accepted) {
					return StatementSetFilter::RemoveAll
				}

				dispute_state
			} else {
				DisputeState {
					validators_for: bitvec![BitOrderLsb0, u8; 0; n_validators],
					validators_against: bitvec![BitOrderLsb0, u8; 0; n_validators],
					start: now,
					concluded_at: None,
				}
			}
		};

		// Check and import all votes.
		let summary = {
			let mut importer = DisputeStateImporter::new(dispute_state, now);
			for (i, (statement, validator_index, signature)) in set.statements.iter().enumerate() {
				let validator_public = match session_info.validators.get(validator_index.0 as usize)
				{
					None => {
						filter.remove_index(i);
						continue
					},
					Some(v) => v,
				};

				let valid = statement.indicates_validity();

				let undo = match importer.import(*validator_index, valid) {
					Ok(u) => u,
					Err(_) => {
						filter.remove_index(i);
						continue
					},
				};

				// Check signature after attempting import.
				//
				// Since we expect that this filter will be applied to
				// disputes long after they're concluded, 99% of the time,
				// the duplicate filter above will catch them before needing
				// to do a heavy signature check.
				//
				// This is only really important until the post-conclusion acceptance threshold
				// is reached, and then no part of this loop will be hit.
				if let Err(()) = check_signature(
					&validator_public,
					set.candidate_hash,
					set.session,
					statement,
					signature,
				) {
					importer.undo(undo);
					filter.remove_index(i);
					continue
				}
			}

			importer.finish()
		};

		// Reject disputes which don't have at least one vote on each side.
		if summary.state.validators_for.count_ones() == 0 ||
			summary.state.validators_against.count_ones() == 0
		{
			return StatementSetFilter::RemoveAll
		}

		// Apply spam slot changes. Bail early if too many occupied.
		let is_local = <Included<T>>::contains_key(&set.session, &set.candidate_hash);
		if !is_local {
			let mut spam_slots: Vec<u32> =
				SpamSlots::<T>::get(&set.session).unwrap_or_else(|| vec![0; n_validators]);

			for (validator_index, spam_slot_change) in summary.spam_slot_changes {
				let spam_slot = spam_slots
					.get_mut(validator_index.0 as usize)
					.expect("index is in-bounds, as checked above; qed");

				if let SpamSlotChange::Inc = spam_slot_change {
					if *spam_slot >= config.dispute_max_spam_slots {
						// Find the vote by this validator and filter it out.
						let first_index_in_set = set
							.statements
							.iter()
							.position(|(_, v_i, _)| &validator_index == v_i)
							.expect(
								"spam slots are only incremented when a new statement \
									from a validator is included; qed",
							);

						// Note that there may be many votes by the validator in the statement
						// set. There are not supposed to be, but the purpose of this function
						// is to filter out invalid submissions, after all.
						//
						// This is fine - we only need to handle the first one, because all
						// subsequent votes' indices have been added to the filter already
						// by the duplicate checks above. It's only the first one which
						// may not already have been filtered out.
						filter.remove_index(first_index_in_set);
					}

					// It's also worth noting that the `DisputeStateImporter`
					// which produces these spam slot updates only produces
					// one spam slot update per validator because it rejects
					// duplicate votes.
					//
					// So we don't need to worry about spam slots being
					// updated incorrectly after receiving duplicates.
					*spam_slot += 1;
				} else {
					*spam_slot = spam_slot.saturating_sub(1);
				}
			}

			// We write the spam slots here because sequential calls to
			// `filter_dispute_data` have a dependency on each other.
			//
			// For example, if a validator V occupies 1 spam slot and
			// max is 2, then 2 sequential calls incrementing spam slot
			// cannot be allowed.
			//
			// However, 3 sequential calls, where the first increments,
			// the second decrements, and the third increments would be allowed.
			SpamSlots::<T>::insert(&set.session, spam_slots);
		}

		filter
	}

	/// Handle a set of dispute statements corresponding to a single candidate.
	///
	/// Fails if the dispute data is invalid. Returns a boolean indicating whether the
	/// dispute is fresh.
	fn provide_dispute_data(
		config: &HostConfiguration<T::BlockNumber>,
		set: DisputeStatementSet,
	) -> Result<bool, DispatchError> {
		// Dispute statement sets on any dispute which concluded
		// before this point are to be rejected.
		let now = <frame_system::Pallet<T>>::block_number();
		let oldest_accepted = now.saturating_sub(config.dispute_post_conclusion_acceptance_period);

		// Load session info to access validators
		let session_info = match <session_info::Pallet<T>>::session_info(set.session) {
			Some(s) => s,
			None => return Err(Error::<T>::AncientDisputeStatement.into()),
		};

		let n_validators = session_info.validators.len();

		// Check for ancient.
		let (fresh, dispute_state) = {
			if let Some(dispute_state) = <Disputes<T>>::get(&set.session, &set.candidate_hash) {
				ensure!(
					dispute_state.concluded_at.as_ref().map_or(true, |c| c >= &oldest_accepted),
					Error::<T>::AncientDisputeStatement,
				);

				(false, dispute_state)
			} else {
				(
					true,
					DisputeState {
						validators_for: bitvec![BitOrderLsb0, u8; 0; n_validators],
						validators_against: bitvec![BitOrderLsb0, u8; 0; n_validators],
						start: now,
						concluded_at: None,
					},
				)
			}
		};

		// Check and import all votes.
		let summary = {
			let mut importer = DisputeStateImporter::new(dispute_state, now);
			for (statement, validator_index, signature) in &set.statements {
				let validator_public = session_info
					.validators
					.get(validator_index.0 as usize)
					.ok_or(Error::<T>::ValidatorIndexOutOfBounds)?;

				// Check signature before importing.
				check_signature(
					&validator_public,
					set.candidate_hash,
					set.session,
					statement,
					signature,
				)
				.map_err(|()| Error::<T>::InvalidSignature)?;

				let valid = statement.indicates_validity();

				importer.import(*validator_index, valid).map_err(Error::<T>::from)?;
			}

			importer.finish()
		};

		// Reject disputes which don't have at least one vote on each side.
		ensure!(
			summary.state.validators_for.count_ones() > 0 &&
				summary.state.validators_against.count_ones() > 0,
			Error::<T>::SingleSidedDispute,
		);

		// Apply spam slot changes. Bail early if too many occupied.
		let is_local = <Included<T>>::contains_key(&set.session, &set.candidate_hash);
		if !is_local {
			let mut spam_slots: Vec<u32> =
				SpamSlots::<T>::get(&set.session).unwrap_or_else(|| vec![0; n_validators]);

			for (validator_index, spam_slot_change) in summary.spam_slot_changes {
				let spam_slot = spam_slots
					.get_mut(validator_index.0 as usize)
					.expect("index is in-bounds, as checked above; qed");

				match spam_slot_change {
					SpamSlotChange::Inc => {
						ensure!(
							*spam_slot < config.dispute_max_spam_slots,
							Error::<T>::PotentialSpam,
						);

						*spam_slot += 1;
					},
					SpamSlotChange::Dec => {
						*spam_slot = spam_slot.saturating_sub(1);
					},
				}
			}

			SpamSlots::<T>::insert(&set.session, spam_slots);
		}

		if fresh {
			Self::deposit_event(Event::DisputeInitiated(
				set.candidate_hash,
				if is_local { DisputeLocation::Local } else { DisputeLocation::Remote },
			));
		}

		{
			if summary.new_flags.contains(DisputeStateFlags::FOR_SUPERMAJORITY) {
				Self::deposit_event(Event::DisputeConcluded(
					set.candidate_hash,
					DisputeResult::Valid,
				));
			}

			// It is possible, although unexpected, for a dispute to conclude twice.
			// This would require f+1 validators to vote in both directions.
			// A dispute cannot conclude more than once in each direction.

			if summary.new_flags.contains(DisputeStateFlags::AGAINST_SUPERMAJORITY) {
				Self::deposit_event(Event::DisputeConcluded(
					set.candidate_hash,
					DisputeResult::Invalid,
				));
			}
		}

		// Reward statements.
		T::RewardValidators::reward_dispute_statement(
			set.session,
			summary.new_participants.iter_ones().map(|i| ValidatorIndex(i as _)),
		);

		// Slash participants on a losing side.
		{
			// a valid candidate, according to 2/3. Punish those on the 'against' side.
			T::PunishValidators::punish_against_valid(set.session, summary.slash_against);

			// an invalid candidate, according to 2/3. Punish those on the 'for' side.
			T::PunishValidators::punish_for_invalid(set.session, summary.slash_for);
		}

		<Disputes<T>>::insert(&set.session, &set.candidate_hash, &summary.state);

		// Freeze if just concluded against some local candidate
		if summary.new_flags.contains(DisputeStateFlags::AGAINST_SUPERMAJORITY) {
			if let Some(revert_to) = <Included<T>>::get(&set.session, &set.candidate_hash) {
				Self::revert_and_freeze(revert_to);
			}
		}

		Ok(fresh)
	}

	#[allow(unused)]
	pub(crate) fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<T::BlockNumber>)> {
		<Disputes<T>>::iter().collect()
	}

	pub(crate) fn note_included(
		session: SessionIndex,
		candidate_hash: CandidateHash,
		included_in: T::BlockNumber,
	) {
		if included_in.is_zero() {
			return
		}

		let revert_to = included_in - One::one();

		<Included<T>>::insert(&session, &candidate_hash, revert_to);

		// If we just included a block locally which has a live dispute, decrement spam slots
		// for any involved validators, if the dispute is not already confirmed by f + 1.
		if let Some(state) = <Disputes<T>>::get(&session, candidate_hash) {
			SpamSlots::<T>::mutate(&session, |spam_slots| {
				if let Some(ref mut spam_slots) = *spam_slots {
					decrement_spam(spam_slots, &state);
				}
			});

			if has_supermajority_against(&state) {
				Self::revert_and_freeze(revert_to);
			}
		}
	}

	pub(crate) fn included_state(
		session: SessionIndex,
		candidate_hash: CandidateHash,
	) -> Option<T::BlockNumber> {
		<Included<T>>::get(session, candidate_hash)
	}

	pub(crate) fn concluded_invalid(session: SessionIndex, candidate_hash: CandidateHash) -> bool {
		<Disputes<T>>::get(&session, &candidate_hash).map_or(false, |dispute| {
			// A dispute that has concluded with supermajority-against.
			has_supermajority_against(&dispute)
		})
	}

	pub(crate) fn is_frozen() -> bool {
		Self::last_valid_block().is_some()
	}

	pub(crate) fn revert_and_freeze(revert_to: T::BlockNumber) {
		if Self::last_valid_block().map_or(true, |last| last > revert_to) {
			Frozen::<T>::set(Some(revert_to));

			// The `Revert` log is about reverting a block, not reverting to a block.
			// If we want to revert to block X in the current chain, we need to revert
			// block X+1.
			let revert = revert_to + One::one();
			Self::deposit_event(Event::Revert(revert));
			frame_system::Pallet::<T>::deposit_log(
				ConsensusLog::Revert(revert.saturated_into()).into(),
			);
		}
	}
}

fn has_supermajority_against<BlockNumber>(dispute: &DisputeState<BlockNumber>) -> bool {
	let supermajority_threshold = supermajority_threshold(dispute.validators_against.len());
	dispute.validators_against.count_ones() >= supermajority_threshold
}

// If the dispute had not enough validators to confirm, decrement spam slots for all the participating
// validators.
//
// Returns the set of participating validators as a bitvec.
fn decrement_spam<BlockNumber>(
	spam_slots: &mut [u32],
	dispute: &DisputeState<BlockNumber>,
) -> bitvec::vec::BitVec<BitOrderLsb0, u8> {
	let byzantine_threshold = byzantine_threshold(spam_slots.len());

	let participating = dispute.validators_for.clone() | dispute.validators_against.iter().by_val();
	let decrement_spam = participating.count_ones() <= byzantine_threshold;
	for validator_index in participating.iter_ones() {
		if decrement_spam {
			if let Some(occupied) = spam_slots.get_mut(validator_index as usize) {
				*occupied = occupied.saturating_sub(1);
			}
		}
	}

	participating
}

fn check_signature(
	validator_public: &ValidatorId,
	candidate_hash: CandidateHash,
	session: SessionIndex,
	statement: &DisputeStatement,
	validator_signature: &ValidatorSignature,
) -> Result<(), ()> {
	let payload = match *statement {
		DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) =>
			ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(),
		DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(inclusion_parent)) =>
			CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext {
				session_index: session,
				parent_hash: inclusion_parent,
			}),
		DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) =>
			CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext {
				session_index: session,
				parent_hash: inclusion_parent,
			}),
		DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) =>
			ApprovalVote(candidate_hash).signing_payload(session),
		DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) =>
			ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(),
	};

	if validator_signature.verify(&payload[..], &validator_public) {
		Ok(())
	} else {
		Err(())
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::mock::{
		new_test_ext, AccountId, AllPallets, Initializer, MockGenesisConfig, System, Test,
		PUNISH_VALIDATORS_AGAINST, PUNISH_VALIDATORS_FOR, PUNISH_VALIDATORS_INCONCLUSIVE,
		REWARD_VALIDATORS,
	};
	use frame_support::{
		assert_err, assert_noop, assert_ok, assert_storage_noop,
		traits::{OnFinalize, OnInitialize},
	};
	use frame_system::InitKind;
	use primitives::v1::BlockNumber;
	use sp_core::{crypto::CryptoType, Pair};

	// All arguments for `initializer::on_new_session`
	type NewSession<'a> = (
		bool,
		SessionIndex,
		Vec<(&'a AccountId, ValidatorId)>,
		Option<Vec<(&'a AccountId, ValidatorId)>>,
	);

	// Run to specific block, while calling disputes pallet hooks manually, because disputes is not
	// integrated in initializer yet.
	fn run_to_block<'a>(
		to: BlockNumber,
		new_session: impl Fn(BlockNumber) -> Option<NewSession<'a>>,
	) {
		while System::block_number() < to {
			let b = System::block_number();
			if b != 0 {
				// circumvent requirement to have bitfields and headers in block for testing purposes
				crate::paras_inherent::Included::<Test>::set(Some(()));

				AllPallets::on_finalize(b);
				System::finalize();
			}

			System::initialize(&(b + 1), &Default::default(), &Default::default(), InitKind::Full);
			AllPallets::on_initialize(b + 1);

			if let Some(new_session) = new_session(b + 1) {
				Initializer::test_trigger_on_new_session(
					new_session.0,
					new_session.1,
					new_session.2.into_iter(),
					new_session.3.map(|q| q.into_iter()),
				);
			}
		}
	}

	#[test]
	fn test_dispute_state_flag_from_state() {
		assert_eq!(
			DisputeStateFlags::from_state(&DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			}),
			DisputeStateFlags::default(),
		);

		assert_eq!(
			DisputeStateFlags::from_state(&DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 1, 1, 1, 1, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			}),
			DisputeStateFlags::FOR_SUPERMAJORITY | DisputeStateFlags::CONFIRMED,
		);

		assert_eq!(
			DisputeStateFlags::from_state(&DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 1, 1, 1, 1, 1, 0, 0],
				start: 0,
				concluded_at: None,
			}),
			DisputeStateFlags::AGAINST_SUPERMAJORITY | DisputeStateFlags::CONFIRMED,
		);
	}

	#[test]
	fn test_import_new_participant_spam_inc() {
		let mut importer = DisputeStateImporter::new(
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
			0,
		);

		assert_err!(
			importer.import(ValidatorIndex(9), true),
			VoteImportError::ValidatorIndexOutOfBounds,
		);

		assert_err!(importer.import(ValidatorIndex(0), true), VoteImportError::DuplicateStatement);
		assert_ok!(importer.import(ValidatorIndex(0), false));

		assert_ok!(importer.import(ValidatorIndex(2), true));
		assert_err!(importer.import(ValidatorIndex(2), true), VoteImportError::DuplicateStatement);

		assert_ok!(importer.import(ValidatorIndex(2), false));
		assert_err!(importer.import(ValidatorIndex(2), false), VoteImportError::DuplicateStatement);

		let summary = importer.finish();
		assert_eq!(summary.new_flags, DisputeStateFlags::default());
		assert_eq!(
			summary.state,
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
		);
		assert_eq!(summary.spam_slot_changes, vec![(ValidatorIndex(2), SpamSlotChange::Inc)]);
		assert!(summary.slash_for.is_empty());
		assert!(summary.slash_against.is_empty());
		assert_eq!(summary.new_participants, bitvec![BitOrderLsb0, u8; 0, 0, 1, 0, 0, 0, 0, 0]);
	}

	#[test]
	fn test_import_prev_participant_spam_dec_confirmed() {
		let mut importer = DisputeStateImporter::new(
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
			0,
		);

		assert_ok!(importer.import(ValidatorIndex(2), true));

		let summary = importer.finish();
		assert_eq!(
			summary.state,
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
		);
		assert_eq!(
			summary.spam_slot_changes,
			vec![
				(ValidatorIndex(0), SpamSlotChange::Dec),
				(ValidatorIndex(1), SpamSlotChange::Dec),
			],
		);
		assert!(summary.slash_for.is_empty());
		assert!(summary.slash_against.is_empty());
		assert_eq!(summary.new_participants, bitvec![BitOrderLsb0, u8; 0, 0, 1, 0, 0, 0, 0, 0]);
		assert_eq!(summary.new_flags, DisputeStateFlags::CONFIRMED);
	}

	#[test]
	fn test_import_prev_participant_spam_dec_confirmed_slash_for() {
		let mut importer = DisputeStateImporter::new(
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
			0,
		);

		assert_ok!(importer.import(ValidatorIndex(2), true));
		assert_ok!(importer.import(ValidatorIndex(2), false));
		assert_ok!(importer.import(ValidatorIndex(3), false));
		assert_ok!(importer.import(ValidatorIndex(4), false));
		assert_ok!(importer.import(ValidatorIndex(5), false));
		assert_ok!(importer.import(ValidatorIndex(6), false));

		let summary = importer.finish();
		assert_eq!(
			summary.state,
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 1, 1, 1, 1, 1, 0],
				start: 0,
				concluded_at: Some(0),
			},
		);
		assert_eq!(
			summary.spam_slot_changes,
			vec![
				(ValidatorIndex(0), SpamSlotChange::Dec),
				(ValidatorIndex(1), SpamSlotChange::Dec),
			],
		);
		assert_eq!(summary.slash_for, vec![ValidatorIndex(0), ValidatorIndex(2)]);
		assert!(summary.slash_against.is_empty());
		assert_eq!(summary.new_participants, bitvec![BitOrderLsb0, u8; 0, 0, 1, 1, 1, 1, 1, 0]);
		assert_eq!(
			summary.new_flags,
			DisputeStateFlags::CONFIRMED | DisputeStateFlags::AGAINST_SUPERMAJORITY,
		);
	}

	#[test]
	fn test_import_slash_against() {
		let mut importer = DisputeStateImporter::new(
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 0, 0, 0, 0, 0, 0],
				start: 0,
				concluded_at: None,
			},
			0,
		);

		assert_ok!(importer.import(ValidatorIndex(3), true));
		assert_ok!(importer.import(ValidatorIndex(4), true));
		assert_ok!(importer.import(ValidatorIndex(5), false));
		assert_ok!(importer.import(ValidatorIndex(6), true));
		assert_ok!(importer.import(ValidatorIndex(7), true));

		let summary = importer.finish();
		assert_eq!(
			summary.state,
			DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 1, 1, 1, 0, 1, 1],
				validators_against: bitvec![BitOrderLsb0, u8; 0, 1, 0, 0, 0, 1, 0, 0],
				start: 0,
				concluded_at: Some(0),
			},
		);
		assert!(summary.spam_slot_changes.is_empty());
		assert!(summary.slash_for.is_empty());
		assert_eq!(summary.slash_against, vec![ValidatorIndex(1), ValidatorIndex(5)]);
		assert_eq!(summary.new_participants, bitvec![BitOrderLsb0, u8; 0, 0, 0, 1, 1, 1, 1, 1]);
		assert_eq!(summary.new_flags, DisputeStateFlags::FOR_SUPERMAJORITY);
	}

	// Test that punish_inconclusive is correctly called.
	#[test]
	fn test_initializer_initialize() {
		let dispute_conclusion_by_time_out_period = 3;
		let start = 10;

		let mock_genesis_config = MockGenesisConfig {
			configuration: crate::configuration::GenesisConfig {
				config: HostConfiguration {
					dispute_conclusion_by_time_out_period,
					..Default::default()
				},
				..Default::default()
			},
			..Default::default()
		};

		new_test_ext(mock_genesis_config).execute_with(|| {
			// We need 6 validators for the byzantine threshold to be 2
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v2 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v3 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v4 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v5 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v6 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(start, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					],
					Some(vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					]),
				))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			// v0 votes for 3, v6 against.
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: start - 1,
				statements: vec![
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						v0.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: start - 1,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(6),
						v2.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: start - 1,
							}
							.signing_payload(),
						),
					),
				],
			}];

			assert_ok!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				vec![(9, candidate_hash.clone())],
			);
			assert_eq!(SpamSlots::<Test>::get(start - 1), Some(vec![1, 0, 0, 0, 0, 0, 1]));

			// Run to timeout period
			run_to_block(start + dispute_conclusion_by_time_out_period, |_| None);
			assert_eq!(SpamSlots::<Test>::get(start - 1), Some(vec![1, 0, 0, 0, 0, 0, 1]));

			// Run to timeout + 1 in order to executive on_finalize(timeout)
			run_to_block(start + dispute_conclusion_by_time_out_period + 1, |_| None);
			assert_eq!(SpamSlots::<Test>::get(start - 1), Some(vec![0, 0, 0, 0, 0, 0, 0]));
			assert_eq!(
				PUNISH_VALIDATORS_INCONCLUSIVE.with(|r| r.borrow()[0].clone()),
				(9, vec![ValidatorIndex(0), ValidatorIndex(6)]),
			);
		});
	}

	// Test prunning works
	#[test]
	fn test_initializer_on_new_session() {
		let dispute_period = 3;

		let mock_genesis_config = MockGenesisConfig {
			configuration: crate::configuration::GenesisConfig {
				config: HostConfiguration { dispute_period, ..Default::default() },
				..Default::default()
			},
			..Default::default()
		};

		new_test_ext(mock_genesis_config).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));
			Pallet::<Test>::note_included(0, candidate_hash.clone(), 0);
			Pallet::<Test>::note_included(1, candidate_hash.clone(), 1);
			Pallet::<Test>::note_included(2, candidate_hash.clone(), 2);
			Pallet::<Test>::note_included(3, candidate_hash.clone(), 3);
			Pallet::<Test>::note_included(4, candidate_hash.clone(), 4);
			Pallet::<Test>::note_included(5, candidate_hash.clone(), 5);
			Pallet::<Test>::note_included(6, candidate_hash.clone(), 5);

			run_to_block(7, |b| {
				// a new session at each block
				Some((true, b, vec![(&0, v0.public())], Some(vec![(&0, v0.public())])))
			});

			// current session is 7,
			// we keep for dispute_period + 1 session and we remove in on_finalize
			// thus we keep info for session 3, 4, 5, 6, 7.
			assert_eq!(Included::<Test>::iter_prefix(0).count(), 0);
			assert_eq!(Included::<Test>::iter_prefix(1).count(), 0);
			assert_eq!(Included::<Test>::iter_prefix(2).count(), 0);
			assert_eq!(Included::<Test>::iter_prefix(3).count(), 1);
			assert_eq!(Included::<Test>::iter_prefix(4).count(), 1);
			assert_eq!(Included::<Test>::iter_prefix(5).count(), 1);
			assert_eq!(Included::<Test>::iter_prefix(6).count(), 1);
		});
	}

	#[test]
	fn test_provide_multi_dispute_data_duplicate_error() {
		new_test_ext(Default::default()).execute_with(|| {
			let candidate_hash_1 = CandidateHash(sp_core::H256::repeat_byte(1));
			let candidate_hash_2 = CandidateHash(sp_core::H256::repeat_byte(2));

			let stmts = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash_2,
					session: 2,
					statements: vec![],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash_1,
					session: 1,
					statements: vec![],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash_2,
					session: 2,
					statements: vec![],
				},
			];

			assert_err!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				DispatchError::from(Error::<Test>::DuplicateDisputeStatementSets),
			);
		})
	}

	// Test:
	// * wrong signature fails
	// * signature is checked for correct validator
	#[test]
	fn test_provide_multi_dispute_is_checking_signature_correctly() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				if b == 1 {
					Some((
						true,
						b,
						vec![(&0, v0.public()), (&1, v1.public())],
						Some(vec![(&0, v0.public()), (&1, v1.public())]),
					))
				} else {
					Some((true, b, vec![(&1, v1.public())], Some(vec![(&1, v1.public())])))
				}
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 1,
				statements: vec![
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						v0.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 1,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 1,
							}
							.signing_payload(),
						),
					),
				],
			}];

			assert_ok!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				vec![(1, candidate_hash.clone())],
			);

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 2,
				statements: vec![(
					DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
					ValidatorIndex(0),
					v0.sign(
						&ExplicitDisputeStatement {
							valid: true,
							candidate_hash: candidate_hash.clone(),
							session: 2,
						}
						.signing_payload(),
					),
				)],
			}];

			assert_noop!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				DispatchError::from(Error::<Test>::InvalidSignature),
			);
		})
	}

	#[test]
	fn test_freeze_on_note_included() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(6, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![(&0, v0.public()), (&1, v1.public())],
					Some(vec![(&0, v0.public()), (&1, v1.public())]),
				))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			// v0 votes for 3
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 3,
				statements: vec![
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						v0.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
				],
			}];
			assert!(Pallet::<Test>::provide_multi_dispute_data(stmts).is_ok());

			Pallet::<Test>::note_included(3, candidate_hash.clone(), 3);
			assert_eq!(Frozen::<Test>::get(), Some(2));
		});
	}

	#[test]
	fn test_freeze_provided_against_supermajority_for_included() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(6, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![(&0, v0.public()), (&1, v1.public())],
					Some(vec![(&0, v0.public()), (&1, v1.public())]),
				))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			// v0 votes for 3
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 3,
				statements: vec![
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						v0.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
				],
			}];

			Pallet::<Test>::note_included(3, candidate_hash.clone(), 3);
			assert!(Pallet::<Test>::provide_multi_dispute_data(stmts).is_ok());
			assert_eq!(Frozen::<Test>::get(), Some(2));
		});
	}

	// tests for:
	// * provide_multi_dispute: with success scenario
	// * disputes: correctness of datas
	// * could_be_invalid: correctness of datas
	// * note_included: decrement spam correctly
	// * spam slots: correctly incremented and decremented
	// * ensure rewards and punishment are correctly called.
	#[test]
	fn test_provide_multi_dispute_success_and_other() {
		new_test_ext(Default::default()).execute_with(|| {
			// 7 validators needed for byzantine threshold of 2.
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v2 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v3 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v4 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v5 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v6 = <ValidatorId as CryptoType>::Pair::generate().0;

			// v0 -> 0
			// v1 -> 3
			// v2 -> 6
			// v3 -> 5
			// v4 -> 1
			// v5 -> 4
			// v6 -> 2

			run_to_block(6, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					],
					Some(vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					]),
				))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			// v0 votes for 3, v6 votes against
			let stmts = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 3,
				statements: vec![
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						v0.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(2),
						v6.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					),
				],
			}];

			assert_ok!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				vec![(3, candidate_hash.clone())],
			);
			assert_eq!(SpamSlots::<Test>::get(3), Some(vec![1, 0, 1, 0, 0, 0, 0]));

			// v1 votes for 4 and for 3, v6 votes against 4.
			let stmts = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 4,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(3),
							v1.sign(
								&ExplicitDisputeStatement {
									valid: true,
									candidate_hash: candidate_hash.clone(),
									session: 4,
								}
								.signing_payload(),
							),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(2),
							v6.sign(
								&ExplicitDisputeStatement {
									valid: false,
									candidate_hash: candidate_hash.clone(),
									session: 4,
								}
								.signing_payload(),
							),
						),
					],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 3,
					statements: vec![(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(3),
						v1.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					)],
				},
			];

			assert_ok!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				vec![(4, candidate_hash.clone())],
			);
			assert_eq!(SpamSlots::<Test>::get(3), Some(vec![0, 0, 0, 0, 0, 0, 0])); // Confirmed as no longer spam
			assert_eq!(SpamSlots::<Test>::get(4), Some(vec![0, 0, 1, 1, 0, 0, 0]));

			// v3 votes against 3 and for 5, v6 votes against 5.
			let stmts = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 3,
					statements: vec![(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(5),
						v3.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					)],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 5,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(5),
							v3.sign(
								&ExplicitDisputeStatement {
									valid: true,
									candidate_hash: candidate_hash.clone(),
									session: 5,
								}
								.signing_payload(),
							),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(2),
							v6.sign(
								&ExplicitDisputeStatement {
									valid: false,
									candidate_hash: candidate_hash.clone(),
									session: 5,
								}
								.signing_payload(),
							),
						),
					],
				},
			];
			assert_ok!(
				Pallet::<Test>::provide_multi_dispute_data(stmts),
				vec![(5, candidate_hash.clone())],
			);
			assert_eq!(SpamSlots::<Test>::get(3), Some(vec![0, 0, 0, 0, 0, 0, 0]));
			assert_eq!(SpamSlots::<Test>::get(4), Some(vec![0, 0, 1, 1, 0, 0, 0]));
			assert_eq!(SpamSlots::<Test>::get(5), Some(vec![0, 0, 1, 0, 0, 1, 0]));

			// v2 votes for 3 and against 5
			let stmts = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 3,
					statements: vec![(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(6),
						v2.sign(
							&ExplicitDisputeStatement {
								valid: true,
								candidate_hash: candidate_hash.clone(),
								session: 3,
							}
							.signing_payload(),
						),
					)],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 5,
					statements: vec![(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(6),
						v2.sign(
							&ExplicitDisputeStatement {
								valid: false,
								candidate_hash: candidate_hash.clone(),
								session: 5,
							}
							.signing_payload(),
						),
					)],
				},
			];
			assert_ok!(Pallet::<Test>::provide_multi_dispute_data(stmts), vec![]);
			assert_eq!(SpamSlots::<Test>::get(3), Some(vec![0, 0, 0, 0, 0, 0, 0]));
			assert_eq!(SpamSlots::<Test>::get(4), Some(vec![0, 0, 1, 1, 0, 0, 0]));
			assert_eq!(SpamSlots::<Test>::get(5), Some(vec![0, 0, 0, 0, 0, 0, 0]));

			let stmts = vec![
				// 0, 4, and 5 vote against 5
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 5,
					statements: vec![
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							v0.sign(
								&ExplicitDisputeStatement {
									valid: false,
									candidate_hash: candidate_hash.clone(),
									session: 5,
								}
								.signing_payload(),
							),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							v4.sign(
								&ExplicitDisputeStatement {
									valid: false,
									candidate_hash: candidate_hash.clone(),
									session: 5,
								}
								.signing_payload(),
							),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(4),
							v5.sign(
								&ExplicitDisputeStatement {
									valid: false,
									candidate_hash: candidate_hash.clone(),
									session: 5,
								}
								.signing_payload(),
							),
						),
					],
				},
				// 4 and 5 vote for 3
				DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 3,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							v4.sign(
								&ExplicitDisputeStatement {
									valid: true,
									candidate_hash: candidate_hash.clone(),
									session: 3,
								}
								.signing_payload(),
							),
						),
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(4),
							v5.sign(
								&ExplicitDisputeStatement {
									valid: true,
									candidate_hash: candidate_hash.clone(),
									session: 3,
								}
								.signing_payload(),
							),
						),
					],
				},
			];
			assert_ok!(Pallet::<Test>::provide_multi_dispute_data(stmts), vec![]);

			assert_eq!(
				Pallet::<Test>::disputes(),
				vec![
					(
						5,
						candidate_hash.clone(),
						DisputeState {
							validators_for: bitvec![BitOrderLsb0, u8; 0, 0, 0, 0, 0, 1, 0],
							validators_against: bitvec![BitOrderLsb0, u8; 1, 1, 1, 0, 1, 0, 1],
							start: 6,
							concluded_at: Some(6), // 5 vote against
						}
					),
					(
						3,
						candidate_hash.clone(),
						DisputeState {
							validators_for: bitvec![BitOrderLsb0, u8; 1, 1, 0, 1, 1, 0, 1],
							validators_against: bitvec![BitOrderLsb0, u8; 0, 0, 1, 0, 0, 1, 0],
							start: 6,
							concluded_at: Some(6), // 5 vote for
						}
					),
					(
						4,
						candidate_hash.clone(),
						DisputeState {
							validators_for: bitvec![BitOrderLsb0, u8; 0, 0, 0, 1, 0, 0, 0],
							validators_against: bitvec![BitOrderLsb0, u8; 0, 0, 1, 0, 0, 0, 0],
							start: 6,
							concluded_at: None,
						}
					),
				]
			);

			assert!(!Pallet::<Test>::concluded_invalid(3, candidate_hash.clone()));
			assert!(!Pallet::<Test>::concluded_invalid(4, candidate_hash.clone()));
			assert!(Pallet::<Test>::concluded_invalid(5, candidate_hash.clone()));

			// Ensure inclusion removes spam slots
			assert_eq!(SpamSlots::<Test>::get(4), Some(vec![0, 0, 1, 1, 0, 0, 0]));
			Pallet::<Test>::note_included(4, candidate_hash.clone(), 4);
			assert_eq!(SpamSlots::<Test>::get(4), Some(vec![0, 0, 0, 0, 0, 0, 0]));

			// Ensure the reward_validator function was correctly called
			assert_eq!(
				REWARD_VALIDATORS.with(|r| r.borrow().clone()),
				vec![
					(3, vec![ValidatorIndex(0), ValidatorIndex(2)]),
					(4, vec![ValidatorIndex(2), ValidatorIndex(3)]),
					(3, vec![ValidatorIndex(3)]),
					(3, vec![ValidatorIndex(5)]),
					(5, vec![ValidatorIndex(2), ValidatorIndex(5)]),
					(3, vec![ValidatorIndex(6)]),
					(5, vec![ValidatorIndex(6)]),
					(5, vec![ValidatorIndex(0), ValidatorIndex(1), ValidatorIndex(4)]),
					(3, vec![ValidatorIndex(1), ValidatorIndex(4)]),
				],
			);

			// Ensure punishment against is called
			assert_eq!(
				PUNISH_VALIDATORS_AGAINST.with(|r| r.borrow().clone()),
				vec![
					(3, vec![]),
					(4, vec![]),
					(3, vec![]),
					(3, vec![]),
					(5, vec![]),
					(3, vec![]),
					(5, vec![]),
					(5, vec![]),
					(3, vec![ValidatorIndex(2), ValidatorIndex(5)]),
				],
			);

			// Ensure punishment for is called
			assert_eq!(
				PUNISH_VALIDATORS_FOR.with(|r| r.borrow().clone()),
				vec![
					(3, vec![]),
					(4, vec![]),
					(3, vec![]),
					(3, vec![]),
					(5, vec![]),
					(3, vec![]),
					(5, vec![]),
					(5, vec![ValidatorIndex(5)]),
					(3, vec![]),
				],
			);
		})
	}

	#[test]
	fn test_revert_and_freeze() {
		new_test_ext(Default::default()).execute_with(|| {
			// events are ignored for genesis block
			System::set_block_number(1);

			Frozen::<Test>::put(Some(0));
			assert_noop!(
				{
					Pallet::<Test>::revert_and_freeze(0);
					Result::<(), ()>::Err(()) // Just a small trick in order to use assert_noop.
				},
				(),
			);

			Frozen::<Test>::kill();
			Pallet::<Test>::revert_and_freeze(0);

			assert_eq!(Frozen::<Test>::get(), Some(0));
			assert_eq!(System::digest().logs[0], ConsensusLog::Revert(1).into());
			System::assert_has_event(Event::Revert(1).into());
		})
	}

	#[test]
	fn test_revert_and_freeze_merges() {
		new_test_ext(Default::default()).execute_with(|| {
			Frozen::<Test>::put(Some(10));
			assert_noop!(
				{
					Pallet::<Test>::revert_and_freeze(10);
					Result::<(), ()>::Err(()) // Just a small trick in order to use assert_noop.
				},
				(),
			);

			Pallet::<Test>::revert_and_freeze(8);
			assert_eq!(Frozen::<Test>::get(), Some(8));
		})
	}

	#[test]
	fn test_has_supermajority_against() {
		assert_eq!(
			has_supermajority_against(&DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 1, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 1, 1, 1, 1, 1, 0, 0, 0],
				start: 0,
				concluded_at: None,
			}),
			false,
		);

		assert_eq!(
			has_supermajority_against(&DisputeState {
				validators_for: bitvec![BitOrderLsb0, u8; 1, 1, 0, 0, 0, 0, 0, 0],
				validators_against: bitvec![BitOrderLsb0, u8; 1, 1, 1, 1, 1, 1, 0, 0],
				start: 0,
				concluded_at: None,
			}),
			true,
		);
	}

	#[test]
	fn test_decrement_spam() {
		let original_spam_slots = vec![0, 1, 2, 3, 4, 5, 6, 7];

		// Test confirm is no-op
		let mut spam_slots = original_spam_slots.clone();
		let dispute_state_confirm = DisputeState {
			validators_for: bitvec![BitOrderLsb0, u8; 1, 1, 0, 0, 0, 0, 0, 0],
			validators_against: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
			start: 0,
			concluded_at: None,
		};
		assert_eq!(
			DisputeStateFlags::from_state(&dispute_state_confirm),
			DisputeStateFlags::CONFIRMED
		);
		assert_eq!(
			decrement_spam(spam_slots.as_mut(), &dispute_state_confirm),
			bitvec![BitOrderLsb0, u8; 1, 1, 1, 0, 0, 0, 0, 0],
		);
		assert_eq!(spam_slots, original_spam_slots);

		// Test not confirm is decreasing spam
		let mut spam_slots = original_spam_slots.clone();
		let dispute_state_no_confirm = DisputeState {
			validators_for: bitvec![BitOrderLsb0, u8; 1, 0, 0, 0, 0, 0, 0, 0],
			validators_against: bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
			start: 0,
			concluded_at: None,
		};
		assert_eq!(
			DisputeStateFlags::from_state(&dispute_state_no_confirm),
			DisputeStateFlags::default()
		);
		assert_eq!(
			decrement_spam(spam_slots.as_mut(), &dispute_state_no_confirm),
			bitvec![BitOrderLsb0, u8; 1, 0, 1, 0, 0, 0, 0, 0],
		);
		assert_eq!(spam_slots, vec![0, 1, 1, 3, 4, 5, 6, 7]);
	}

	#[test]
	fn test_check_signature() {
		let validator_id = <ValidatorId as CryptoType>::Pair::generate().0;
		let wrong_validator_id = <ValidatorId as CryptoType>::Pair::generate().0;

		let session = 0;
		let wrong_session = 1;
		let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));
		let wrong_candidate_hash = CandidateHash(sp_core::H256::repeat_byte(2));
		let inclusion_parent = sp_core::H256::repeat_byte(3);
		let wrong_inclusion_parent = sp_core::H256::repeat_byte(4);

		let statement_1 = DisputeStatement::Valid(ValidDisputeStatementKind::Explicit);
		let statement_2 = DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(
			inclusion_parent.clone(),
		));
		let wrong_statement_2 = DisputeStatement::Valid(
			ValidDisputeStatementKind::BackingSeconded(wrong_inclusion_parent.clone()),
		);
		let statement_3 = DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(
			inclusion_parent.clone(),
		));
		let wrong_statement_3 = DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(
			wrong_inclusion_parent.clone(),
		));
		let statement_4 = DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking);
		let statement_5 = DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit);

		let signed_1 = validator_id.sign(
			&ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash.clone(),
				session,
			}
			.signing_payload(),
		);
		let signed_2 =
			validator_id.sign(&CompactStatement::Seconded(candidate_hash.clone()).signing_payload(
				&SigningContext { session_index: session, parent_hash: inclusion_parent.clone() },
			));
		let signed_3 =
			validator_id.sign(&CompactStatement::Valid(candidate_hash.clone()).signing_payload(
				&SigningContext { session_index: session, parent_hash: inclusion_parent.clone() },
			));
		let signed_4 =
			validator_id.sign(&ApprovalVote(candidate_hash.clone()).signing_payload(session));
		let signed_5 = validator_id.sign(
			&ExplicitDisputeStatement {
				valid: false,
				candidate_hash: candidate_hash.clone(),
				session,
			}
			.signing_payload(),
		);

		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_1
		)
		.is_ok());
		assert!(check_signature(
			&wrong_validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			wrong_candidate_hash,
			session,
			&statement_1,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			wrong_session,
			&statement_1,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_1
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_1
		)
		.is_err());

		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_2
		)
		.is_ok());
		assert!(check_signature(
			&wrong_validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			wrong_candidate_hash,
			session,
			&statement_2,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			wrong_session,
			&statement_2,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&wrong_statement_2,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_2
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_2
		)
		.is_err());

		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_3
		)
		.is_ok());
		assert!(check_signature(
			&wrong_validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			wrong_candidate_hash,
			session,
			&statement_3,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			wrong_session,
			&statement_3,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&wrong_statement_3,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_3
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_3
		)
		.is_err());

		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_4
		)
		.is_ok());
		assert!(check_signature(
			&wrong_validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			wrong_candidate_hash,
			session,
			&statement_4,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			wrong_session,
			&statement_4,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_4
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_4
		)
		.is_err());

		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_5
		)
		.is_ok());
		assert!(check_signature(
			&wrong_validator_id.public(),
			candidate_hash,
			session,
			&statement_5,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			wrong_candidate_hash,
			session,
			&statement_5,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			wrong_session,
			&statement_5,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_1,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_2,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_3,
			&signed_5
		)
		.is_err());
		assert!(check_signature(
			&validator_id.public(),
			candidate_hash,
			session,
			&statement_4,
			&signed_5
		)
		.is_err());
	}

	#[test]
	fn filter_removes_duplicates_within_set() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![(&0, v0.public()), (&1, v1.public())],
					Some(vec![(&0, v0.public()), (&1, v1.public())]),
				))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash.clone(),
				session: 1,
			}
			.signing_payload();

			let payload_against = ExplicitDisputeStatement {
				valid: false,
				candidate_hash: candidate_hash.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload);
			let sig_b = v0.sign(&payload);
			let sig_c = v0.sign(&payload);
			let sig_d = v1.sign(&payload_against);

			let mut statements = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 1,
				statements: vec![
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_a.clone(),
					),
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_b,
					),
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_c,
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(1),
						sig_d.clone(),
					),
				],
			}];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert_eq!(
				statements,
				vec![DisputeStatementSet {
					candidate_hash: candidate_hash.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_a,
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							sig_d,
						),
					]
				}]
			)
		})
	}

	#[test]
	fn filter_bad_signatures_correctly_detects_single_sided() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v2 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v3 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
					],
					Some(vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
					]),
				))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = |c_hash: &CandidateHash, valid| {
				ExplicitDisputeStatement { valid, candidate_hash: c_hash.clone(), session: 1 }
					.signing_payload()
			};

			let payload_a = payload(&candidate_hash_a, true);
			let payload_a_bad = payload(&candidate_hash_a, false);

			let sig_0 = v0.sign(&payload_a);
			let sig_1 = v1.sign(&payload_a_bad);

			let mut statements = vec![DisputeStatementSet {
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
				statements: vec![
					(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_0.clone(),
					),
					(
						DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
						ValidatorIndex(2),
						sig_1.clone(),
					),
				],
			}];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert!(statements.is_empty());
		})
	}

	#[test]
	fn filter_correctly_accounts_spam_slots() {
		let dispute_max_spam_slots = 2;

		let mock_genesis_config = MockGenesisConfig {
			configuration: crate::configuration::GenesisConfig {
				config: HostConfiguration { dispute_max_spam_slots, ..Default::default() },
				..Default::default()
			},
			..Default::default()
		};

		new_test_ext(mock_genesis_config).execute_with(|| {
			// We need 7 validators for the byzantine threshold to be 2
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v2 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v3 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v4 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v5 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v6 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					],
					Some(vec![
						(&0, v0.public()),
						(&1, v1.public()),
						(&2, v2.public()),
						(&3, v3.public()),
						(&4, v4.public()),
						(&5, v5.public()),
						(&6, v6.public()),
					]),
				))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));
			let candidate_hash_b = CandidateHash(sp_core::H256::repeat_byte(2));
			let candidate_hash_c = CandidateHash(sp_core::H256::repeat_byte(3));

			let payload = |c_hash: &CandidateHash, valid| {
				ExplicitDisputeStatement { valid, candidate_hash: c_hash.clone(), session: 1 }
					.signing_payload()
			};

			let payload_a = payload(&candidate_hash_a, true);
			let payload_b = payload(&candidate_hash_b, true);
			let payload_c = payload(&candidate_hash_c, true);

			let payload_a_bad = payload(&candidate_hash_a, false);
			let payload_b_bad = payload(&candidate_hash_b, false);
			let payload_c_bad = payload(&candidate_hash_c, false);

			let sig_0a = v0.sign(&payload_a);
			let sig_0b = v0.sign(&payload_b);
			let sig_0c = v0.sign(&payload_c);

			let sig_1b = v1.sign(&payload_b);

			let sig_2a = v2.sign(&payload_a_bad);
			let sig_2b = v2.sign(&payload_b_bad);
			let sig_2c = v2.sign(&payload_c_bad);

			let mut statements = vec![
				// validators 0 and 2 get 1 spam slot from this.
				DisputeStatementSet {
					candidate_hash: candidate_hash_a.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_0a.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(6),
							sig_2a.clone(),
						),
					],
				},
				// Validators 0, 2, and 3 get no spam slots for this
				DisputeStatementSet {
					candidate_hash: candidate_hash_b.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_0b.clone(),
						),
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(3),
							sig_1b.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(6),
							sig_2b.clone(),
						),
					],
				},
				// Validators 0 and 2 get an extra spam slot for this.
				DisputeStatementSet {
					candidate_hash: candidate_hash_c.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_0c.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(6),
							sig_2c.clone(),
						),
					],
				},
			];

			let old_statements = statements.clone();
			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert_eq!(statements, old_statements);
		})
	}

	#[test]
	fn filter_removes_session_out_of_bounds() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((true, b, vec![(&0, v0.public())], Some(vec![(&0, v0.public())])))
			});

			let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload);

			let mut statements = vec![DisputeStatementSet {
				candidate_hash: candidate_hash.clone(),
				session: 100,
				statements: vec![(
					DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
					ValidatorIndex(0),
					sig_a,
				)],
			}];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert!(statements.is_empty());
		})
	}

	#[test]
	fn filter_removes_concluded_ancient() {
		let dispute_post_conclusion_acceptance_period = 2;

		let mock_genesis_config = MockGenesisConfig {
			configuration: crate::configuration::GenesisConfig {
				config: HostConfiguration {
					dispute_post_conclusion_acceptance_period,
					..Default::default()
				},
				..Default::default()
			},
			..Default::default()
		};

		new_test_ext(mock_genesis_config).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((true, b, vec![(&0, v0.public())], Some(vec![(&0, v0.public())])))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));
			let candidate_hash_b = CandidateHash(sp_core::H256::repeat_byte(2));

			<Disputes<Test>>::insert(
				&1,
				&candidate_hash_a,
				DisputeState {
					validators_for: bitvec![BitOrderLsb0, u8; 0; 4],
					validators_against: bitvec![BitOrderLsb0, u8; 1; 4],
					start: 0,
					concluded_at: Some(0),
				},
			);

			<Disputes<Test>>::insert(
				&1,
				&candidate_hash_b,
				DisputeState {
					validators_for: bitvec![BitOrderLsb0, u8; 0; 4],
					validators_against: bitvec![BitOrderLsb0, u8; 1; 4],
					start: 0,
					concluded_at: Some(1),
				},
			);

			let payload_a = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
			}
			.signing_payload();

			let payload_b = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash_b.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload_a);
			let sig_b = v0.sign(&payload_b);

			let mut statements = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash_a.clone(),
					session: 1,
					statements: vec![(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_a,
					)],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash_b.clone(),
					session: 1,
					statements: vec![(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_b.clone(),
					)],
				},
			];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert_eq!(
				statements,
				vec![DisputeStatementSet {
					candidate_hash: candidate_hash_b.clone(),
					session: 1,
					statements: vec![(
						DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
						ValidatorIndex(0),
						sig_b,
					),]
				}]
			);
		})
	}

	#[test]
	fn filter_removes_duplicate_statements_sets() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;
			let v1 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((
					true,
					b,
					vec![(&0, v0.public()), (&1, v1.public())],
					Some(vec![(&0, v0.public()), (&1, v1.public())]),
				))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
			}
			.signing_payload();

			let payload_against = ExplicitDisputeStatement {
				valid: false,
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload);
			let sig_a_against = v1.sign(&payload_against);

			let sig_b = v0.sign(&payload);
			let sig_b_against = v1.sign(&payload_against);

			let mut statements = vec![
				DisputeStatementSet {
					candidate_hash: candidate_hash_a.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_a.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							sig_a_against.clone(),
						),
					],
				},
				DisputeStatementSet {
					candidate_hash: candidate_hash_a.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_b.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							sig_b_against.clone(),
						),
					],
				},
			];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert_eq!(
				statements,
				vec![DisputeStatementSet {
					candidate_hash: candidate_hash_a.clone(),
					session: 1,
					statements: vec![
						(
							DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
							ValidatorIndex(0),
							sig_a.clone(),
						),
						(
							DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit),
							ValidatorIndex(1),
							sig_a_against.clone(),
						),
					],
				}]
			);
		})
	}

	#[test]
	fn filter_ignores_single_sided() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((true, b, vec![(&0, v0.public())], Some(vec![(&0, v0.public())])))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload);

			let mut statements = vec![DisputeStatementSet {
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
				statements: vec![(
					DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
					ValidatorIndex(0),
					sig_a.clone(),
				)],
			}];

			assert_storage_noop!(Pallet::<Test>::filter_multi_dispute_data(&mut statements));

			assert!(statements.is_empty());
		})
	}

	#[test]
	fn import_ignores_single_sided() {
		new_test_ext(Default::default()).execute_with(|| {
			let v0 = <ValidatorId as CryptoType>::Pair::generate().0;

			run_to_block(3, |b| {
				// a new session at each block
				Some((true, b, vec![(&0, v0.public())], Some(vec![(&0, v0.public())])))
			});

			let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));

			let payload = ExplicitDisputeStatement {
				valid: true,
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
			}
			.signing_payload();

			let sig_a = v0.sign(&payload);

			let statements = vec![DisputeStatementSet {
				candidate_hash: candidate_hash_a.clone(),
				session: 1,
				statements: vec![(
					DisputeStatement::Valid(ValidDisputeStatementKind::Explicit),
					ValidatorIndex(0),
					sig_a.clone(),
				)],
			}];

			assert_err!(
				Pallet::<Test>::provide_multi_dispute_data(statements),
				DispatchError::from(Error::<Test>::SingleSidedDispute),
			);
		})
	}
}