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

package agreement

import (
	"bytes"
	"context"
	"crypto/sha256"
	"fmt"
	"math/rand"
	"os"
	"reflect"
	"runtime"
	"strconv"
	"testing"
	"time"

	"github.com/algorand/go-deadlock"
	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/account"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/bookkeeping"
	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
	"github.com/algorand/go-algorand/util/db"
	"github.com/algorand/go-algorand/util/timers"
)

type testingTimeout struct {
	delta time.Duration
	ch    chan time.Time
}

type testingClock struct {
	mu deadlock.Mutex

	zeroes uint

	TA map[TimeoutType]testingTimeout // TimeoutAt

	monitor *coserviceMonitor
}

func makeTestingClock(m *coserviceMonitor) *testingClock {
	c := new(testingClock)
	c.TA = make(map[TimeoutType]testingTimeout)
	c.monitor = m
	return c
}

func (c *testingClock) Zero() timers.Clock[TimeoutType] {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.zeroes++
	c.TA = make(map[TimeoutType]testingTimeout)
	c.monitor.clearClock()
	return c
}

func (c *testingClock) Since() time.Duration {
	return 1
}

func (c *testingClock) TimeoutAt(d time.Duration, timeoutType TimeoutType) <-chan time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()

	ta, ok := c.TA[timeoutType]
	if !ok || ta.delta != d {
		c.TA[timeoutType] = testingTimeout{delta: d, ch: make(chan time.Time)}
		ta = c.TA[timeoutType]
	}

	return ta.ch
}

func (c *testingClock) when(timeoutType TimeoutType) (time.Duration, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	ta, ok := c.TA[timeoutType]
	if !ok {
		return time.Duration(0), fmt.Errorf("no timeout of type, %v", timeoutType)
	}
	return ta.delta, nil
}

func (c *testingClock) Encode() []byte {
	return nil
}

func (c *testingClock) Decode([]byte) (timers.Clock[TimeoutType], error) {
	return makeTestingClock(nil), nil // TODO
}

func (c *testingClock) prepareToFire() {
	c.monitor.inc(clockCoserviceType)
}

func (c *testingClock) fire(timeoutType TimeoutType) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if _, ok := c.TA[timeoutType]; !ok {
		panic(fmt.Errorf("no timeout of type %v", timeoutType))
	}
	close(c.TA[timeoutType].ch)
}

type testingNetwork struct {
	validator BlockValidator

	voteMessages    []chan Message
	payloadMessages []chan Message
	bundleMessages  []chan Message

	mu deadlock.Mutex // guards connected, nextHandle, source, and monitors

	connected  [][]bool // symmetric
	nextHandle int
	source     map[MessageHandle]nodeID
	monitors   map[nodeID]*coserviceMonitor

	// used for extra tests
	dropSoftVotes     bool
	dropSlowNextVotes bool
	dropVotes         bool
	certVotePocket    chan<- multicastParams
	softVotePocket    chan<- multicastParams
	compoundPocket    chan<- multicastParams
	partitionedNodes  map[nodeID]bool
	crownedNodes      map[nodeID]bool
	relayNodes        map[nodeID]bool
	interceptFn       multicastInterceptFn
}

type testingNetworkEndpoint struct {
	parent *testingNetwork
	id     nodeID

	voteMessages    chan Message
	payloadMessages chan Message
	bundleMessages  chan Message

	monitor *coserviceMonitor
}

type nodeID int

// bufferCapacity is per channel
func makeTestingNetwork(nodes int, bufferCapacity int, validator BlockValidator) *testingNetwork {
	n := new(testingNetwork)

	n.validator = validator

	n.voteMessages = make([]chan Message, nodes)
	n.payloadMessages = make([]chan Message, nodes)
	n.bundleMessages = make([]chan Message, nodes)
	n.source = make(map[MessageHandle]nodeID)
	n.monitors = make(map[nodeID]*coserviceMonitor)

	for i := 0; i < nodes; i++ {
		n.voteMessages[i] = make(chan Message, bufferCapacity)
		n.payloadMessages[i] = make(chan Message, bufferCapacity)
		n.bundleMessages[i] = make(chan Message, bufferCapacity)

		m := new(coserviceMonitor)
		m.id = i
		n.monitors[nodeID(i)] = m
	}

	n.connected = make([][]bool, nodes)
	for i := 0; i < nodes; i++ {
		n.connected[i] = make([]bool, nodes)
		for j := 0; j < nodes; j++ {
			n.connected[i][j] = true
		}
	}

	return n
}

type multicastInterceptFn func(params multicastParams) multicastParams
type multicastParams struct {
	tag     protocol.Tag
	data    []byte
	source  nodeID
	exclude nodeID
}

// UnknownMsgTag ensures the testingNetwork implementation below will drop a message.
const UnknownMsgTag protocol.Tag = "??"

func (n *testingNetwork) multicast(tag protocol.Tag, data []byte, source nodeID, exclude nodeID) {
	// fmt.Println("mc", source, "x", exclude)
	n.mu.Lock()
	defer n.mu.Unlock()

	if n.interceptFn != nil {
		out := n.interceptFn(multicastParams{tag, data, source, exclude})
		tag, data, source, exclude = out.tag, out.data, out.source, out.exclude
	}

	if n.dropSoftVotes || n.dropSlowNextVotes || n.dropVotes || n.certVotePocket != nil || n.softVotePocket != nil || n.compoundPocket != nil {
		if tag == protocol.ProposalPayloadTag {
			r := bytes.NewBuffer(data)

			var tp transmittedPayload
			err := protocol.DecodeStream(r, &tp)
			if err != nil {
				panic(err)
			}

			if n.compoundPocket != nil {
				n.compoundPocket <- multicastParams{tag, data, source, exclude}
				return
			}
		}

		if tag == protocol.AgreementVoteTag {
			r := bytes.NewBuffer(data)

			var uv unauthenticatedVote
			err := protocol.DecodeStream(r, &uv)
			if err != nil {
				panic(err)
			}

			if n.certVotePocket != nil && uv.R.Step == cert {
				n.certVotePocket <- multicastParams{tag, data, source, exclude}
				return
			}

			if n.softVotePocket != nil && uv.R.Step == soft {
				n.softVotePocket <- multicastParams{tag, data, source, exclude}
				return
			}

			if n.dropVotes {
				return
			}

			if n.dropSoftVotes && uv.R.Step == soft {
				return
			}

			if n.dropSlowNextVotes && uv.R.Step >= next && uv.R.Step != late && uv.R.Step != redo && uv.R.Step != down {
				return
			}
		}
	}

	n.nextHandle++
	handle := new(int)
	*handle = n.nextHandle
	n.source[handle] = source

	var msgChans []chan Message
	switch tag {
	case protocol.AgreementVoteTag:
		msgChans = n.voteMessages
	case protocol.VoteBundleTag:
		msgChans = n.bundleMessages
	case protocol.ProposalPayloadTag:
		msgChans = n.payloadMessages
	case UnknownMsgTag:
		// We use this intentionally - just drop it
		return
	default:
		panic("bad broadcast call")
	}

	for i, connected := range n.connected[source] {
		peerid := nodeID(i)
		if peerid == source {
			continue
		}
		if peerid == exclude {
			continue
		}
		if !connected {
			continue
		}
		if n.partitionedNodes != nil {
			if n.partitionedNodes[source] != n.partitionedNodes[peerid] {
				continue
			}
		}
		if n.crownedNodes != nil {
			if !n.crownedNodes[peerid] {
				continue
			}
		}
		if n.relayNodes != nil {
			if !n.relayNodes[source] && !n.relayNodes[peerid] {
				continue
			}
		}

		// we should have incremented tokenizerCoserviceType
		n.monitors[peerid].inc(tokenizerCoserviceType)
		select {
		case msgChans[peerid] <- Message{MessageHandle: handle, Data: data}:
			// fmt.Println("transmit-success", source, "->", peerid)
		default:
			logging.Base().Warn("message dropped during test")
			n.monitors[peerid].dec(tokenizerCoserviceType)
			// fmt.Println("transmit-failure", source, "->", peerid)
		}
	}
}

func (n *testingNetwork) dropAllSoftVotes() {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.dropSoftVotes = true
}

func (n *testingNetwork) dropAllSlowNextVotes() {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.dropSlowNextVotes = true
}

func (n *testingNetwork) dropAllVotes() {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.dropVotes = true
}

func (n *testingNetwork) pocketAllCertVotes(ch chan<- multicastParams) (closeFn func()) {
	n.certVotePocket = ch
	return func() {
		close(ch)
	}
}

func (n *testingNetwork) pocketAllSoftVotes(ch chan<- multicastParams) (closeFn func()) {
	n.softVotePocket = ch
	return func() {
		close(ch)
	}
}

func (n *testingNetwork) pocketAllCompound(ch chan<- multicastParams) (closeFn func()) {
	n.compoundPocket = ch
	return func() {
		close(ch)
	}
}

func (n *testingNetwork) repairAll() {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.dropSoftVotes = false
	n.dropSlowNextVotes = false
	n.dropVotes = false
	n.certVotePocket = nil
	n.softVotePocket = nil
	n.compoundPocket = nil
	n.partitionedNodes = nil
	n.crownedNodes = nil
	n.relayNodes = nil
	n.interceptFn = nil
}

func (n *testingNetwork) disconnect(a nodeID, b nodeID) {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.connected[a][b] = false
	n.connected[b][a] = false
}

// Set the given list of nodes as a partition; heal whatever previous
// partition existed.
func (n *testingNetwork) partition(part ...nodeID) {
	n.mu.Lock()
	defer n.mu.Unlock()
	// different mechanism than n.connected map
	n.partitionedNodes = make(map[nodeID]bool)
	for i := 0; i < len(part); i++ {
		n.partitionedNodes[part[i]] = true
	}
}

// Only deliver messages to the given set of nodes
func (n *testingNetwork) crown(prophets ...nodeID) {
	n.mu.Lock()
	defer n.mu.Unlock()
	n.crownedNodes = make(map[nodeID]bool)
	for i := 0; i < len(prophets); i++ {
		n.crownedNodes[prophets[i]] = true
	}
}

// Star topology with the given nodes at the center; to revert, call repairAll
func (n *testingNetwork) makeRelays(relays ...nodeID) {
	n.mu.Lock()
	defer n.mu.Unlock()
	n.relayNodes = make(map[nodeID]bool)
	for i := 0; i < len(relays); i++ {
		n.relayNodes[relays[i]] = true
	}
}

// intercept messages from the given sources, replacing them with our own.
// if, in the returned params, the message is tagged UnknownMsgTag, the testing
// network drops the message.
func (n *testingNetwork) intercept(f multicastInterceptFn) {
	n.mu.Lock()
	defer n.mu.Unlock()
	n.interceptFn = f
}

func (n *testingNetwork) sourceOf(h MessageHandle) nodeID {
	n.mu.Lock()
	defer n.mu.Unlock()
	if _, noint := h.(*int); !noint {
		panic(fmt.Errorf("h isn't a *int; %v", reflect.TypeOf(h)))
	}
	return n.source[h]
}

func (n *testingNetwork) testingNetworkEndpoint(id nodeID) *testingNetworkEndpoint {
	e := new(testingNetworkEndpoint)
	e.id = id
	e.parent = n
	e.voteMessages = n.voteMessages[id]
	e.payloadMessages = n.payloadMessages[id]
	e.bundleMessages = n.bundleMessages[id]
	e.monitor = n.monitors[id]
	return e
}

// this allows us to put the activity into a busy state until the message on the queue is actually processed
func (n *testingNetwork) prepareAllMulticast() {
	n.mu.Lock()
	defer n.mu.Unlock()
	for _, monitor := range n.monitors {
		monitor.inc(networkCoserviceType)
	}
}

func (n *testingNetwork) finishAllMulticast() {
	n.mu.Lock()
	defer n.mu.Unlock()
	for _, monitor := range n.monitors {
		monitor.dec(networkCoserviceType)
	}
}

func (e *testingNetworkEndpoint) Messages(tag protocol.Tag) <-chan Message {
	switch tag {
	case protocol.AgreementVoteTag:
		return e.voteMessages
	case protocol.VoteBundleTag:
		return e.bundleMessages
	case protocol.ProposalPayloadTag:
		return e.payloadMessages
	default:
		panic("bad messages call")
	}
}

func (e *testingNetworkEndpoint) Broadcast(tag protocol.Tag, data []byte) error {
	e.parent.multicast(tag, data, e.id, e.id)
	return nil
}

func (e *testingNetworkEndpoint) Relay(h MessageHandle, t protocol.Tag, data []byte) error {
	sourceID := e.id
	if _, isMsg := h.(*int); isMsg {
		sourceID = e.parent.sourceOf(h)
	}

	e.parent.multicast(t, data, e.id, sourceID)
	return nil
}

func (e *testingNetworkEndpoint) Disconnect(h MessageHandle) {
	if _, isMsg := h.(*int); !isMsg {
		return
	}

	sourceID := e.parent.sourceOf(h)
	e.parent.disconnect(e.id, sourceID)
}

func (e *testingNetworkEndpoint) Start() {}

type activityMonitor struct {
	deadlock.Mutex

	busy bool

	sums      map[nodeID]uint
	listeners map[nodeID]coserviceListener

	activity chan struct{}
	quiet    chan struct{}

	cb func(nodeID, map[coserviceType]uint)
}

func makeActivityMonitor() (m *activityMonitor) {
	m = new(activityMonitor)
	m.sums = make(map[nodeID]uint)
	m.listeners = make(map[nodeID]coserviceListener)
	m.activity = make(chan struct{}, 1000)
	m.quiet = make(chan struct{}, 1000)
	return
}

func (m *activityMonitor) coserviceListener(id nodeID) coserviceListener {
	m.Lock()
	defer m.Unlock()

	if m.listeners[id] == nil {
		m.listeners[id] = amCoserviceListener{id: id, activityMonitor: m}
	}
	return m.listeners[id]
}

func (m *activityMonitor) sum() (s uint) {
	for _, a := range m.sums {
		s += a
	}
	return
}

func (m *activityMonitor) dump() {
	m.Lock()
	defer m.Unlock()

	for n, s := range m.sums {
		fmt.Printf("%v: %v\n", n, s)
	}
}

func (m *activityMonitor) waitForActivity() {
	<-m.activity
}

func (m *activityMonitor) waitForQuiet() {
	select {
	case <-m.quiet:
	case <-time.After(10 * time.Second):
		m.dump()

		var buf [1000000]byte
		n := runtime.Stack(buf[:], true)
		fmt.Println("Printing goroutine dump of size", n)
		fmt.Println(string(buf[:n]))

		panic("timed out waiting for quiet...")
	}
}

func (m *activityMonitor) setCallback(cb func(nodeID, map[coserviceType]uint)) {
	m.Lock()
	defer m.Unlock()
	m.cb = cb
}

type amCoserviceListener struct {
	id nodeID

	*activityMonitor
}

func (l amCoserviceListener) inc(sum uint, v map[coserviceType]uint) {
	l.Lock()
	defer l.Unlock()

	l.activityMonitor.sums[l.id] = sum

	if !l.busy {
		l.activity <- struct{}{}
		l.busy = true
	}

	if l.cb != nil {
		l.cb(l.id, v)
	}
}

func (l amCoserviceListener) dec(sum uint, v map[coserviceType]uint) {
	l.Lock()
	defer l.Unlock()

	l.activityMonitor.sums[l.id] = sum

	if l.busy && l.sum() == 0 {
		l.quiet <- struct{}{}
		l.busy = false
	}

	if l.cb != nil {
		l.cb(l.id, v)
	}
}

// copied from fuzzer/ledger_test.go. We can merge once a refactor seems necessary.
func generatePseudoRandomVRF(keynum int) *crypto.VRFSecrets {
	seed := [32]byte{}
	seed[0] = byte(keynum % 255)
	seed[1] = byte(keynum / 255)
	pk, sk := crypto.VrfKeygenFromSeed(seed)
	return &crypto.VRFSecrets{
		PK: pk,
		SK: sk,
	}
}

func createTestAccountsAndBalances(t *testing.T, numNodes int, rootSeed []byte) (accounts []account.Participation, balances map[basics.Address]basics.AccountData) {
	off := int(rand.Uint32() >> 2) // prevent name collision from running tests more than once

	// system state setup: keygen, stake initialization
	accounts = make([]account.Participation, numNodes)
	balances = make(map[basics.Address]basics.AccountData, numNodes)
	var seed crypto.Seed
	copy(seed[:], rootSeed)

	for i := 0; i < numNodes; i++ {
		var rootAddress basics.Address
		// add new account rootAddress to db
		{
			rootAccess, err := db.MakeAccessor(t.Name()+"root"+strconv.Itoa(i+off), false, true)
			if err != nil {
				panic(err)
			}
			seed = sha256.Sum256(seed[:]) // rehash every node to get different root addresses
			root, err := account.ImportRoot(rootAccess, seed)
			if err != nil {
				panic(err)
			}
			rootAddress = root.Address()
		}

		var v *crypto.OneTimeSignatureSecrets
		firstValid := basics.Round(0)
		lastValid := basics.Round(1000)
		// generate new participation keys
		{
			// Compute how many distinct participation keys we should generate
			keyDilution := config.Consensus[protocol.ConsensusCurrentVersion].DefaultKeyDilution
			firstID := basics.OneTimeIDForRound(firstValid, keyDilution)
			lastID := basics.OneTimeIDForRound(lastValid, keyDilution)
			numBatches := lastID.Batch - firstID.Batch + 1

			// Generate them
			v = crypto.GenerateOneTimeSignatureSecrets(firstID.Batch, numBatches)
		}

		// save partkeys to db
		{
			accounts[i] = account.Participation{
				Parent:     rootAddress,
				VRF:        generatePseudoRandomVRF(i),
				Voting:     v,
				FirstValid: firstValid,
				LastValid:  lastValid,
			}
		}

		// expose balances for future ledger creation
		acctData := basics.AccountData{
			Status:      basics.Online,
			MicroAlgos:  basics.MicroAlgos{Raw: 1000000},
			VoteID:      accounts[i].VotingSecrets().OneTimeSignatureVerifier,
			SelectionID: accounts[i].VRFSecrets().PK,
		}
		balances[rootAddress] = acctData
	}
	return
}

const (
	firstFPR  = 436854775807
	secondFPR = 736854775807
)

// testingRand always returns max uint64 / 2.
type testingRand struct{}

func (testingRand) Uint64() uint64 {
	var zero uint64
	maxuint64 := zero - 1
	return maxuint64 / 2
}

func setupAgreement(t *testing.T, numNodes int, traceLevel traceLevel, ledgerFactory func(map[basics.Address]basics.AccountData) Ledger) (*testingNetwork, Ledger, func(), []*Service, []timers.Clock[TimeoutType], []Ledger, *activityMonitor) {
	var validator testBlockValidator
	return setupAgreementWithValidator(t, numNodes, traceLevel, validator, ledgerFactory)
}

func setupAgreementWithValidator(t *testing.T, numNodes int, traceLevel traceLevel, validator BlockValidator, ledgerFactory func(map[basics.Address]basics.AccountData) Ledger) (*testingNetwork, Ledger, func(), []*Service, []timers.Clock[TimeoutType], []Ledger, *activityMonitor) {
	bufCap := 1000 // max number of buffered messages

	// system state setup: keygen, stake initialization
	accounts, balances := createTestAccountsAndBalances(t, numNodes, (&[32]byte{})[:])
	baseLedger := ledgerFactory(balances)

	// logging
	log := logging.Base()
	f, _ := os.Create(t.Name() + ".log")
	log.SetJSONFormatter()
	log.SetOutput(f)
	log.SetLevel(logging.Debug)

	// node setup
	clocks := make([]timers.Clock[TimeoutType], numNodes)
	ledgers := make([]Ledger, numNodes)
	dbAccessors := make([]db.Accessor, numNodes)
	services := make([]*Service, numNodes)
	baseNetwork := makeTestingNetwork(numNodes, bufCap, validator)
	am := makeActivityMonitor()

	for i := 0; i < numNodes; i++ {
		accessor, err := db.MakeAccessor(t.Name()+"_"+strconv.Itoa(i)+"_crash.db", false, true)
		if err != nil {
			panic(err)
		}
		dbAccessors[i] = accessor

		m := baseNetwork.monitors[nodeID(i)]
		m.coserviceListener = am.coserviceListener(nodeID(i))
		clocks[i] = makeTestingClock(m)
		ledgers[i] = ledgerFactory(balances)
		keys := makeRecordingKeyManager(accounts[i : i+1])
		endpoint := baseNetwork.testingNetworkEndpoint(nodeID(i))
		ilog := log.WithFields(logging.Fields{"Source": "service-" + strconv.Itoa(i)})

		params := Parameters{
			Logger:         ilog,
			Ledger:         ledgers[i],
			Network:        endpoint,
			KeyManager:     keys,
			BlockValidator: validator,
			BlockFactory:   testBlockFactory{Owner: i},
			Clock:          clocks[i],
			Accessor:       accessor,
			Local:          config.Local{CadaverSizeTarget: 10000000},
			RandomSource:   &testingRand{},
		}

		cadaverFilename := fmt.Sprintf("%v-%v", t.Name(), i)
		os.Remove(cadaverFilename + ".cdv")
		os.Remove(cadaverFilename + ".cdv.archive")

		services[i], err = MakeService(params)
		require.NoError(t, err)
		services[i].tracer.cadaver.baseFilename = cadaverFilename
		services[i].tracer.level = traceLevel
		services[i].tracer.tag = strconv.Itoa(i)

		services[i].monitor = m
		m.inc(demuxCoserviceType)
	}

	cleanupFn := func() {
		for idx := 0; idx < len(dbAccessors); idx++ {
			dbAccessors[idx].Close()
		}

		if r := recover(); r != nil {
			for n, c := range clocks {
				fmt.Printf("node-%v:\n", n)
				c.(*testingClock).monitor.dump()
			}
			panic(r)
		}
	}
	return baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, am
}

func (m *coserviceMonitor) dump() {
	m.Mutex.Lock()
	defer m.Mutex.Unlock()

	for t, n := range m.c {
		fmt.Printf(" %v: %v\n", t, n)
	}
	return
}

func (m *coserviceMonitor) clearClock() {
	if m == nil {
		return
	}

	m.Mutex.Lock()
	defer m.Mutex.Unlock()

	if m.c == nil {
		m.c = make(map[coserviceType]uint)
	}
	m.c[clockCoserviceType] = 0

	if m.coserviceListener != nil {
		m.coserviceListener.dec(m.sum(), m.c)
	}
}

func expectNewPeriod(clocks []timers.Clock[TimeoutType], zeroes uint) (newzeroes uint) {
	zeroes++
	for i := range clocks {
		if clocks[i].(*testingClock).zeroes != zeroes {
			errstr := fmt.Sprintf("unexpected number of zeroes: %v != %v", clocks[i].(*testingClock).zeroes, zeroes)
			panic(errstr)
		}
	}
	return zeroes
}

func expectNoNewPeriod(clocks []timers.Clock[TimeoutType], zeroes uint) (newzeroes uint) {
	for i := range clocks {
		if clocks[i].(*testingClock).zeroes != zeroes {
			errstr := fmt.Sprintf("unexpected number of zeroes: %v != %v", clocks[i].(*testingClock).zeroes, zeroes)
			panic(errstr)
		}
	}
	return zeroes
}

func triggerGlobalTimeout(d time.Duration, timeoutType TimeoutType, clocks []timers.Clock[TimeoutType], activityMonitor *activityMonitor) {
	for i := range clocks {
		clocks[i].(*testingClock).prepareToFire()
	}
	for i := range clocks {
		clocks[i].(*testingClock).fire(timeoutType)
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
}

func triggerGlobalTimeoutType(timeoutType TimeoutType, clocks []timers.Clock[TimeoutType], activityMonitor *activityMonitor) {
	for i := range clocks {
		clocks[i].(*testingClock).prepareToFire()
	}
	for i := range clocks {
		clocks[i].(*testingClock).fire(timeoutType)
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
}

func runRound(clocks []timers.Clock[TimeoutType], activityMonitor *activityMonitor, zeroes uint, filterTimeout time.Duration) (newzeroes uint) {
	triggerGlobalTimeout(filterTimeout, TimeoutFilter, clocks, activityMonitor)
	return expectNewPeriod(clocks, zeroes)
}
func runRoundTriggerFilter(clocks []timers.Clock[TimeoutType], activityMonitor *activityMonitor, zeroes uint) (newzeroes uint) {
	triggerGlobalTimeoutType(TimeoutFilter, clocks, activityMonitor)
	return expectNewPeriod(clocks, zeroes)
}

func sanityCheck(startRound round, numRounds round, ledgers []Ledger) {
	for i := range ledgers {
		if ledgers[i].NextRound() != startRound+numRounds {
			panic("did not progress numRounds rounds")
		}
	}

	for j := round(0); j < numRounds; j++ {
		reference := ledgers[0].(*testLedger).entries[startRound+j].Digest()
		for i := range ledgers {
			if ledgers[i].(*testLedger).entries[startRound+j].Digest() != reference {
				panic("wrong block confirmed")
			}
		}
	}
}

func simulateAgreement(t *testing.T, numNodes int, numRounds int, traceLevel traceLevel) (filterTimeouts []time.Duration) {
	return simulateAgreementWithLedgerFactory(t, numNodes, numRounds, traceLevel, makeTestLedger)
}

func simulateAgreementWithConsensusVersion(t *testing.T, numNodes int, numRounds int, traceLevel traceLevel, consensusVersion func(basics.Round) (protocol.ConsensusVersion, error)) (filterTimeouts []time.Duration) {
	ledgerFactory := func(data map[basics.Address]basics.AccountData) Ledger {
		return makeTestLedgerWithConsensusVersion(data, consensusVersion)
	}
	return simulateAgreementWithLedgerFactory(t, numNodes, numRounds, traceLevel, ledgerFactory)
}

func simulateAgreementWithLedgerFactory(t *testing.T, numNodes int, numRounds int, traceLevel traceLevel, ledgerFactory func(map[basics.Address]basics.AccountData) Ledger) []time.Duration {
	_, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, traceLevel, ledgerFactory)
	startRound := baseLedger.NextRound()
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	filterTimeouts := make([][]time.Duration, numNodes, numNodes)

	// run round with round-specific consensus version first (since fix in #1896)
	zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	for j := 1; j < numRounds; j++ {
		for srvIdx, clock := range clocks {
			delta, err := clock.(*testingClock).when(TimeoutFilter)
			require.NoError(t, err)
			filterTimeouts[srvIdx] = append(filterTimeouts[srvIdx], delta)
		}
		zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	firstHistoricalClocksRound := startRound
	if basics.Round(numRounds) > credentialRoundLag {
		firstHistoricalClocksRound = startRound + basics.Round(numRounds) - credentialRoundLag
	}

	// check that historical clocks map didn't get too large
	for i := 0; i < numNodes; i++ {
		require.LessOrEqual(t, len(services[i].historicalClocks), int(credentialRoundLag)+1, "too many historical clocks kept")
		for round := firstHistoricalClocksRound + 1; round <= startRound+basics.Round(numRounds); round++ {
			_, has := services[i].historicalClocks[round]
			require.True(t, has)
		}
	}
	if numRounds >= int(credentialRoundLag) {
		for i := 0; i < numNodes; i++ {
			require.Equal(t, len(services[i].historicalClocks), int(credentialRoundLag)+1, "not enough historical clocks kept")
		}
	}

	sanityCheck(startRound, round(numRounds), ledgers)

	if len(clocks) == 0 {
		return nil
	}

	for rnd := 0; rnd < numRounds-1; rnd++ {
		delta := filterTimeouts[0][rnd]
		for srvIdx := range clocks {
			require.Equal(t, delta, filterTimeouts[srvIdx][rnd])
		}
	}

	return filterTimeouts[0]
}

func TestAgreementSynchronous1(t *testing.T) {
	partitiontest.PartitionTest(t)

	// if testing.Short() {
	// 	t.Skip("Skipping agreement integration test")
	// }

	simulateAgreement(t, 1, 5, disabled)
}

func TestAgreementSynchronous2(t *testing.T) {
	partitiontest.PartitionTest(t)

	// if testing.Short() {
	// 	t.Skip("Skipping agreement integration test")
	// }

	simulateAgreement(t, 2, 5, disabled)
}

func TestAgreementSynchronous3(t *testing.T) {
	partitiontest.PartitionTest(t)

	// if testing.Short() {
	// 	t.Skip("Skipping agreement integration test")
	// }

	simulateAgreement(t, 3, 5, disabled)
}

func TestAgreementSynchronous4(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	simulateAgreement(t, 4, 5, disabled)
}

func TestAgreementSynchronous5(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	simulateAgreement(t, 5, 5, disabled)
}

func TestAgreementSynchronous10(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Skip("Skipping flaky agreement integration test")
	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	simulateAgreement(t, 10, 5, disabled)
}

func TestAgreementSynchronous5_50(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	simulateAgreement(t, 5, 50, disabled)
}

func TestAgreementHistoricalClocksCleanup(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	simulateAgreement(t, 5, int(credentialRoundLag)+10, disabled)
}

func overrideConfigWithDynamicFilterParam(dynamicFilterTimeoutEnabled bool) (version protocol.ConsensusVersion, consensusVersion func(r basics.Round) (protocol.ConsensusVersion, error), configCleanup func()) {
	version = protocol.ConsensusVersion("test-protocol-filtertimeout")
	protoParams := config.Consensus[protocol.ConsensusCurrentVersion]
	protoParams.DynamicFilterTimeout = dynamicFilterTimeoutEnabled
	config.Consensus[version] = protoParams

	consensusVersion = func(r basics.Round) (protocol.ConsensusVersion, error) {
		return version, nil
	}

	configCleanup = func() {
		delete(config.Consensus, version)
	}

	return
}

func TestAgreementSynchronousFuture5_DynamicFilterRounds(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	_, consensusVersion, configCleanup := overrideConfigWithDynamicFilterParam(true)
	defer configCleanup()

	if dynamicFilterCredentialArrivalHistory <= 0 {
		return
	}

	baseHistoryRounds := dynamicFilterCredentialArrivalHistory + int(credentialRoundLag)
	rounds := baseHistoryRounds + 20

	filterTimeouts := simulateAgreementWithConsensusVersion(t, 5, rounds, disabled, consensusVersion)
	require.Len(t, filterTimeouts, rounds-1)
	for i := 1; i < baseHistoryRounds-1; i++ {
		require.Equal(t, filterTimeouts[i-1], filterTimeouts[i])
	}

	// dynamic filter timeout kicks in when history window is full
	require.Less(t, filterTimeouts[baseHistoryRounds-1], filterTimeouts[baseHistoryRounds-2])

	for i := baseHistoryRounds; i < len(filterTimeouts); i++ {
		require.Equal(t, filterTimeouts[i-1], filterTimeouts[i])
	}
}

func TestDynamicFilterTimeoutResets(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	version, consensusVersion, configCleanup := overrideConfigWithDynamicFilterParam(true)
	defer configCleanup()

	if dynamicFilterCredentialArrivalHistory <= 0 {
		return
	}

	numNodes := 5

	ledgerFactory := func(data map[basics.Address]basics.AccountData) Ledger {
		return makeTestLedgerWithConsensusVersion(data, consensusVersion)
	}

	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, ledgerFactory)
	startRound := baseLedger.NextRound()
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	filterTimeouts := make([][]time.Duration, numNodes, numNodes)

	baseHistoryRounds := dynamicFilterCredentialArrivalHistory + int(credentialRoundLag)

	// run round with round-specific consensus version first (since fix in #1896)
	zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	for j := 1; j < baseHistoryRounds+2; j++ {
		for srvIdx, clock := range clocks {
			delta, err := clock.(*testingClock).when(TimeoutFilter)
			require.NoError(t, err)
			filterTimeouts[srvIdx] = append(filterTimeouts[srvIdx], delta)
		}
		zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	}

	for i := range clocks {
		require.Len(t, filterTimeouts[i], baseHistoryRounds+1)
		for j := 1; j < baseHistoryRounds-2; j++ {
			require.Equal(t, filterTimeouts[i][j-1], filterTimeouts[i][j])
		}
		require.Less(t, filterTimeouts[i][baseHistoryRounds-1], filterTimeouts[i][baseHistoryRounds-2])
	}

	// force fast partition recovery into bottom
	{
		baseNetwork.dropAllSoftVotes()
		baseNetwork.dropAllSlowNextVotes()

		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeoutType(TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(firstFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 1
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	filterTimeoutsPostRecovery := make([][]time.Duration, numNodes, numNodes)

	// run round with round-specific consensus version first (since fix in #1896)
	zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	for j := 1; j < baseHistoryRounds+1; j++ {
		for srvIdx, clock := range clocks {
			delta, err := clock.(*testingClock).when(TimeoutFilter)
			require.NoError(t, err)
			filterTimeoutsPostRecovery[srvIdx] = append(filterTimeoutsPostRecovery[srvIdx], delta)
		}
		zeroes = runRoundTriggerFilter(clocks, activityMonitor, zeroes)
	}

	for i := range clocks {
		require.Len(t, filterTimeoutsPostRecovery[i], baseHistoryRounds)
		// check that history was discarded, so filter time increased back to its original default
		require.Less(t, filterTimeouts[i][baseHistoryRounds], filterTimeoutsPostRecovery[i][0])
		require.Equal(t, filterTimeouts[i][baseHistoryRounds-2], filterTimeoutsPostRecovery[i][0])

		// check that filter timeout was updated to at the end of the history window
		for j := 1; j < dynamicFilterCredentialArrivalHistory-2; j++ {
			require.Equal(t, filterTimeoutsPostRecovery[i][j-1], filterTimeoutsPostRecovery[i][j])
		}
		require.Less(t, filterTimeoutsPostRecovery[i][dynamicFilterCredentialArrivalHistory-1], filterTimeoutsPostRecovery[i][dynamicFilterCredentialArrivalHistory-2])
	}

	sanityCheck(startRound, 2*round(baseHistoryRounds+2), ledgers)
}

func TestAgreementSynchronousFuture1(t *testing.T) {
	partitiontest.PartitionTest(t)

	//if testing.Short() {
	//	t.Skip("Skipping agreement integration test")
	//}

	consensusVersion := func(r basics.Round) (protocol.ConsensusVersion, error) {
		return protocol.ConsensusFuture, nil
	}
	simulateAgreementWithConsensusVersion(t, 1, 5, disabled, consensusVersion)
}

func TestAgreementSynchronousFuture5(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	consensusVersion := func(r basics.Round) (protocol.ConsensusVersion, error) {
		return protocol.ConsensusFuture, nil
	}
	simulateAgreementWithConsensusVersion(t, 5, 5, disabled, consensusVersion)
}

func TestAgreementSynchronousFutureUpgrade(t *testing.T) {
	partitiontest.PartitionTest(t)

	if testing.Short() {
		t.Skip("Skipping agreement integration test")
	}

	consensusVersion := func(r basics.Round) (protocol.ConsensusVersion, error) {
		if r >= 5 {
			return protocol.ConsensusFuture, nil
		}
		return protocol.ConsensusCurrentVersion, nil
	}
	simulateAgreementWithConsensusVersion(t, 5, 10, disabled, consensusVersion)
}

func TestAgreementFastRecoveryDownEarly(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(startRound)
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force fast partition recovery into bottom
	{
		baseNetwork.dropAllSoftVotes()
		baseNetwork.dropAllSlowNextVotes()

		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeoutType(TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(firstFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 1
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementFastRecoveryDownMiss(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force fast partition recovery into bottom
	{
		// fail all steps
		baseNetwork.dropAllVotes()
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)

		firstClocks := clocks[:4]
		restClocks := clocks[4:]

		for i := range firstClocks {
			firstClocks[i].(*testingClock).prepareToFire()
		}
		for i := range firstClocks {
			firstClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		baseNetwork.repairAll()
		for i := range restClocks {
			restClocks[i].(*testingClock).prepareToFire()
		}
		for i := range restClocks {
			restClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(secondFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 1
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementFastRecoveryLate(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force fast partition recovery into value
	var expected proposalValue
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		baseNetwork.dropAllSlowNextVotes()
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if expected == (proposalValue{}) {
				expected = uv.R.Proposal
			} else {
				if uv.R.Proposal != expected {
					errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
					panic(errstr)
				}
			}
		}

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)
		baseNetwork.dropAllVotes()

		firstClocks := clocks[:4]
		restClocks := clocks[4:]

		for i := range firstClocks {
			firstClocks[i].(*testingClock).prepareToFire()
		}
		for i := range firstClocks {
			firstClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		baseNetwork.repairAll()
		for i := range restClocks {
			restClocks[i].(*testingClock).prepareToFire()
		}
		for i := range restClocks {
			restClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(secondFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 1
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	for _, l := range ledgers {
		lastHash, err := l.LookupDigest(l.NextRound() - 1)
		if err != nil {
			panic(err)
		}
		if lastHash != expected.BlockDigest {
			errstr := fmt.Sprintf("converged on wrong block: %v != %v", lastHash, expected.BlockDigest)
			panic(errstr)
		}
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementFastRecoveryRedo(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force fast partition recovery into value
	var expected proposalValue
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		baseNetwork.dropAllSlowNextVotes()
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if expected == (proposalValue{}) {
				expected = uv.R.Proposal
			} else {
				if uv.R.Proposal != expected {
					errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
					panic(errstr)
				}
			}
		}

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)
		baseNetwork.dropAllVotes()

		firstClocks := clocks[:4]
		restClocks := clocks[4:]

		for i := range firstClocks {
			firstClocks[i].(*testingClock).prepareToFire()
		}
		for i := range firstClocks {
			firstClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		baseNetwork.repairAll()
		for i := range restClocks {
			restClocks[i].(*testingClock).prepareToFire()
		}
		for i := range restClocks {
			restClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(secondFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// fail period 1 with value again
	{
		baseNetwork.dropAllVotes()
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(DeadlineTimeout(1, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(0, TimeoutFastRecovery, clocks, activityMonitor) // activates fast partition recovery timer
		zeroes = expectNoNewPeriod(clocks, zeroes)
		baseNetwork.dropAllVotes()

		firstClocks := clocks[:4]
		restClocks := clocks[4:]

		for i := range firstClocks {
			firstClocks[i].(*testingClock).prepareToFire()
		}
		for i := range firstClocks {
			firstClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		baseNetwork.repairAll()
		for i := range restClocks {
			restClocks[i].(*testingClock).prepareToFire()
		}
		for i := range restClocks {
			restClocks[i].(*testingClock).fire(TimeoutFastRecovery)
		}
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(secondFPR, TimeoutFastRecovery, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 2
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(2, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	for _, l := range ledgers {
		lastHash, err := l.LookupDigest(l.NextRound() - 1)
		if err != nil {
			panic(err)
		}
		if lastHash != expected.BlockDigest {
			errstr := fmt.Sprintf("converged on wrong block: %v != %v", lastHash, expected.BlockDigest)
			panic(errstr)
		}
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementBlockReplayBug_b29ea57(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 2
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// fail period 0
	{
		baseNetwork.dropAllSoftVotes()
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// fail period 1 on bottom with block
	{
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(DeadlineTimeout(1, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 2
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(2, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementLateCertBug(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// delay minority cert votes to force period 1
	pocket := make(chan multicastParams, 100)
	{
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()
		baseNetwork.repairAll()

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// terminate on period 0 in period 1
	{
		baseNetwork.prepareAllMulticast()
		for p := range pocket {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementRecoverGlobalStartingValue(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force partition recovery into value
	var expected proposalValue
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)

		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if expected == (proposalValue{}) {
				expected = uv.R.Proposal
			} else {
				if uv.R.Proposal != expected {
					errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
					panic(errstr)
				}
			}
		}

		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 4, int(zeroes))
	}

	// now, enter period 1; check that the pocket cert is for the same value
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)

		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if uv.R.Proposal != expected {
				errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
				panic(errstr)
			}
		}

		triggerGlobalTimeout(DeadlineTimeout(1, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 5, int(zeroes))
	}

	// now, enter period 2, and ensure agreement.
	// todo: make more transparent, I want to kow what v we agreed on
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(2, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 6, int(zeroes))
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementRecoverGlobalStartingValueBadProposal(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force partition recovery into value.
	var expected proposalValue
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if expected == (proposalValue{}) {
				expected = uv.R.Proposal
			} else {
				if uv.R.Proposal != expected {
					errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
					panic(errstr)
				}
			}
		}
		// intercept all proposals for the next period; replace with unexpected
		baseNetwork.intercept(func(params multicastParams) multicastParams {
			if params.tag == protocol.ProposalPayloadTag {
				params.tag = UnknownMsgTag
			}
			return params
		})
		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 4, int(zeroes))
	}

	// Now, try again in period 1. Bad proposal should not make it and starting value should be preserved
	{
		baseNetwork.repairAll()
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if uv.R.Proposal != expected {
				errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
				panic(errstr)
			}
		}
		triggerGlobalTimeout(DeadlineTimeout(1, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)

	}

	// Finish in period 2
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(2, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 6, int(zeroes))
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementRecoverBothVAndBotQuorums(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// force partition recovery into both bottom and value. one node enters bottom, the rest enter value
	var expected proposalValue
	{
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllSoftVotes(pocket)
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()
		pocketedSoft := make([]multicastParams, len(pocket))
		i := 0
		for params := range pocket {
			r := bytes.NewBuffer(params.data)
			var uv unauthenticatedVote
			err := protocol.DecodeStream(r, &uv)
			if err != nil {
				panic(err)
			}
			if expected == (proposalValue{}) {
				expected = uv.R.Proposal
			} else {
				if uv.R.Proposal != expected {
					errstr := fmt.Sprintf("got unexpected soft vote: %v != %v", uv.R.Proposal, expected)
					panic(errstr)
				}
			}
			pocketedSoft[i] = params
			i++
		}
		// generate a bottom quorum; let only one node see it.
		baseNetwork.crown(0)
		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		if clocks[0].(*testingClock).zeroes != zeroes+1 {
			errstr := fmt.Sprintf("node 0 did not enter new period from bot quorum")
			panic(errstr)
		}
		zeroes = expectNoNewPeriod(clocks[1:], zeroes)

		// enable creation of a value quorum; let everyone else see it
		baseNetwork.repairAll()
		baseNetwork.prepareAllMulticast()
		for _, p := range pocketedSoft {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()

		// actually create the value quorum
		_, upper := (next).nextVoteRanges(DeadlineTimeout(0, version))
		triggerGlobalTimeout(upper, TimeoutDeadline, clocks[1:], activityMonitor) // activates next timers
		zeroes = expectNoNewPeriod(clocks[1:], zeroes)

		lower, upper := (next + 1).nextVoteRanges(DeadlineTimeout(0, version))
		delta := time.Duration(testingRand{}.Uint64() % uint64(upper-lower))
		triggerGlobalTimeout(lower+delta, TimeoutDeadline, clocks[1:], activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 4, int(zeroes))
	}

	// Now, try again in period 1. We should vote on reproposal due to non-propagation of bottom bundle.
	{
		baseNetwork.repairAll()
		pocket := make(chan multicastParams, 100)
		closeFn := baseNetwork.pocketAllCertVotes(pocket)
		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		closeFn()

		for msg := range pocket {
			var uv unauthenticatedVote
			err := protocol.DecodeStream(bytes.NewBuffer(msg.data), &uv)
			if err != nil {
				panic(err)
			}

			if uv.R.Proposal != expected {
				errstr := fmt.Sprintf("got unexpected proposal: %v != %v", uv.R.Proposal, expected)
				panic(errstr)
			}
		}

		triggerGlobalTimeout(DeadlineTimeout(1, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// Finish in period 2
	{
		baseNetwork.repairAll()
		triggerGlobalTimeout(FilterTimeout(2, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
		require.Equal(t, 6, int(zeroes))
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 5, ledgers)
}

func TestAgreementSlowPayloadsPreDeadline(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// run round and then start pocketing payloads
	pocket := make(chan multicastParams, 100)
	closeFn := baseNetwork.pocketAllCompound(pocket) // (takes effect next round)
	{
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run round with late payload
	{
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)

		// release payloads; expect new round
		closeFn()
		baseNetwork.repairAll()
		baseNetwork.prepareAllMulticast()
		for p := range pocket {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 6, ledgers)
}

func TestAgreementSlowPayloadsPostDeadline(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// run round and then start pocketing payloads
	pocket := make(chan multicastParams, 100)
	closeFn := baseNetwork.pocketAllCompound(pocket) // (takes effect next round)
	{
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// force network into period 1 by delaying proposals
	{
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNoNewPeriod(clocks, zeroes)
		triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// recover in period 1
	{
		closeFn()
		baseNetwork.repairAll()
		baseNetwork.prepareAllMulticast()
		for p := range pocket {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()
		activityMonitor.waitForActivity()
		activityMonitor.waitForQuiet()
		zeroes = expectNoNewPeriod(clocks, zeroes)

		triggerGlobalTimeout(FilterTimeout(1, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	sanityCheck(startRound, 6, ledgers)
}

func TestAgreementLargePeriods(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()
	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}

	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// partition the network, run until period 60
	for p := 0; p < 60; p++ {
		{
			baseNetwork.partition(0, 1, 2)
			triggerGlobalTimeout(FilterTimeout(period(p), version), TimeoutFilter, clocks, activityMonitor)
			zeroes = expectNoNewPeriod(clocks, zeroes)

			baseNetwork.repairAll()
			triggerGlobalTimeout(DeadlineTimeout(period(p), version), TimeoutDeadline, clocks, activityMonitor)
			zeroes = expectNewPeriod(clocks, zeroes)
			require.Equal(t, 4+p, int(zeroes))
		}
	}

	// terminate
	{
		triggerGlobalTimeout(FilterTimeout(60, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// run two more rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}
	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	const expectNumRounds = 5
	for i := 0; i < numNodes; i++ {
		if ledgers[i].NextRound() != startRound+round(expectNumRounds) {
			panic("did not progress 5 rounds")
		}
	}

	for j := 0; j < expectNumRounds; j++ {
		ledger := ledgers[0].(*testLedger)
		reference := ledger.entries[startRound+round(j)].Digest()
		for i := 0; i < numNodes; i++ {
			ledger := ledgers[i].(*testLedger)
			if ledger.entries[startRound+round(j)].Digest() != reference {
				panic("wrong block confirmed")
			}
		}
	}
}

type testSuspendableBlockValidator struct {
	mu deadlock.Mutex
	x  chan struct{}
}

func makeTestSuspendableBlockValidator() (v *testSuspendableBlockValidator) {
	v = new(testSuspendableBlockValidator)
	v.x = make(chan struct{})
	close(v.x)
	return
}

func (v *testSuspendableBlockValidator) Validate(ctx context.Context, e bookkeeping.Block) (ValidatedBlock, error) {
	v.mu.Lock()
	ch := v.x
	v.mu.Unlock()

	<-ch
	return testValidatedBlock{Inside: e}, nil
}

// returns a channel which when closed terminates validation
func (v *testSuspendableBlockValidator) suspend() chan struct{} {
	v.mu.Lock()
	defer v.mu.Unlock()
	v.x = make(chan struct{})
	return v.x
}

func TestAgreementRegression_WrongPeriodPayloadVerificationCancellation_8ba23942(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5
	validator := makeTestSuspendableBlockValidator()
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreementWithValidator(t, numNodes, disabled, validator, makeTestLedger)
	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()

	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)

	// run two rounds
	for j := 0; j < 2; j++ {
		zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	}

	// run round and then start pocketing payloads, suspending validation
	pocket0 := make(chan multicastParams, 100)
	ch := validator.suspend()
	closeFn := baseNetwork.pocketAllCompound(pocket0) // (takes effect next round)
	{
		triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
		zeroes = expectNewPeriod(clocks, zeroes)
	}

	// force network into period 1 by failing period 0, entering with bottom and no soft threshold (to prevent proposal value pinning)
	baseNetwork.dropAllSoftVotes()
	triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
	zeroes = expectNoNewPeriod(clocks, zeroes)

	// resume delivery of payloads in following period
	baseNetwork.repairAll()
	closeFn()

	// trigger the deadlineTimeout to enter the new period
	// release proposed blocks in a controlled manner to prevent oversubscription of verification
	pocket1 := make(chan multicastParams, 100)
	closeFn = baseNetwork.pocketAllCompound(pocket1)
	triggerGlobalTimeout(DeadlineTimeout(0, version), TimeoutDeadline, clocks, activityMonitor)
	baseNetwork.repairAll()
	close(pocket1)
	{
		// setup synchronization channel
		var csmu deadlock.Mutex
		closed := false
		vch := make(chan struct{})
		cryptoStates := make(map[nodeID]uint)
		activityMonitor.setCallback(func(id nodeID, v map[coserviceType]uint) {
			csmu.Lock()
			defer csmu.Unlock()
			cryptoStates[id] = v[cryptoVerifierCoserviceType]

			var s uint
			for _, c := range cryptoStates {
				s += c
			}
			if s == uint(numNodes-1) && !closed {
				closed = true
				close(vch)
			}
		})

		baseNetwork.prepareAllMulticast()
		for p := range pocket1 {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()

		// wait for numNodes-1 pending crypto verification requests
		<-vch
	}

	// attack the network with the stale payloads
	{
		// setup synchronization channel
		var csmu deadlock.Mutex
		closed := false
		vch := make(chan struct{})
		cryptoStates := make(map[nodeID]uint)
		activityMonitor.setCallback(func(id nodeID, v map[coserviceType]uint) {
			csmu.Lock()
			defer csmu.Unlock()
			cryptoStates[id] = v[cryptoVerifierCoserviceType]

			var s uint
			for _, c := range cryptoStates {
				s += c
			}
			if s == uint(numNodes-1)*2 && !closed {
				closed = true
				close(vch)
			}
		})

		baseNetwork.prepareAllMulticast()
		for p := range pocket0 {
			baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
		}
		baseNetwork.finishAllMulticast()

		// wait for (numNodes-1)*2 pending crypto verification requests
		<-vch
	}

	// resume block verification, replay potentially cancelled blocks to ensure good caching
	// then wait for network to converge (round should terminate at this point)
	activityMonitor.setCallback(nil)
	close(ch)

	baseNetwork.prepareAllMulticast()
	for p := range pocket1 {
		baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
	}
	baseNetwork.finishAllMulticast()

	zeroes = expectNewPeriod(clocks, zeroes)
	activityMonitor.waitForQuiet()

	// run two more rounds
	//for j := 0; j < 2; j++ {
	//	zeroes = runRound(clocks, activityMonitor, zeroes, period(1-j))
	//}
	zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(1, version))
	zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}

	const expectNumRounds = 5
	for i := 0; i < numNodes; i++ {
		if ledgers[i].NextRound() != startRound+round(expectNumRounds) {
			panic("did not progress 5 rounds")
		}
	}

	for j := 0; j < expectNumRounds; j++ {
		ledger := ledgers[0].(*testLedger)
		reference := ledger.entries[startRound+round(j)].Digest()
		for i := 0; i < numNodes; i++ {
			ledger := ledgers[i].(*testLedger)
			if ledger.entries[startRound+round(j)].Digest() != reference {
				panic("wrong block confirmed")
			}
		}
	}
}

// Receiving a certificate should not cause a node to stop relaying important messages
// (such as blocks and pipelined messages for the next round)
// Note that the stall will be resolved by catchup even if the relay blocks.
func TestAgreementCertificateDoesNotStallSingleRelay(t *testing.T) {
	partitiontest.PartitionTest(t)

	numNodes := 5 // single relay, four leaf nodes
	relayID := nodeID(0)
	baseNetwork, baseLedger, cleanupFn, services, clocks, ledgers, activityMonitor := setupAgreement(t, numNodes, disabled, makeTestLedger)

	startRound := baseLedger.NextRound()
	version, _ := baseLedger.ConsensusVersion(baseLedger.NextRound())
	defer cleanupFn()
	for i := 0; i < numNodes; i++ {
		services[i].Start()
	}
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	zeroes := expectNewPeriod(clocks, 0)
	// run two rounds
	zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))
	// make sure relay does not see block proposal for round 3
	baseNetwork.intercept(func(params multicastParams) multicastParams {
		if params.tag == protocol.ProposalPayloadTag {
			var tp transmittedPayload
			err := protocol.DecodeStream(bytes.NewBuffer(params.data), &tp)
			if err != nil {
				panic(err)
			}
			if tp.Round() == basics.Round(startRound+2) {
				params.exclude = relayID
			}
		}
		if params.source == relayID {
			// must also drop relay's proposal so it cannot win leadership
			r := bytes.NewBuffer(params.data)
			if params.tag == protocol.AgreementVoteTag {
				var uv unauthenticatedVote
				err := protocol.DecodeStream(r, &uv)
				if err != nil {
					panic(err)
				}
				if uv.R.Step != propose {
					return params
				}
			}
			params.tag = UnknownMsgTag
		}

		return params
	})
	zeroes = runRound(clocks, activityMonitor, zeroes, FilterTimeout(0, version))

	// Round 3:
	// First partition the relay to prevent it from seeing certificate or block
	baseNetwork.repairAll()
	baseNetwork.partition(relayID)
	// Get a copy of the certificate
	pocketCert := make(chan multicastParams, 100)
	baseNetwork.intercept(func(params multicastParams) multicastParams {
		if params.tag == protocol.AgreementVoteTag {
			r := bytes.NewBuffer(params.data)
			var uv unauthenticatedVote
			err := protocol.DecodeStream(r, &uv)
			if err != nil {
				panic(err)
			}
			if uv.R.Step == cert {
				pocketCert <- params
			}
		}
		return params
	})
	// And with some hypothetical second relay the network achieves consensus on a certificate and block.
	triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks, activityMonitor)
	zeroes = expectNewPeriod(clocks[1:], zeroes)
	require.Equal(t, uint(3), clocks[0].(*testingClock).zeroes)
	close(pocketCert)

	// Round 4:
	// Return to the relay topology
	baseNetwork.repairAll()
	baseNetwork.makeRelays(relayID)
	// Trigger ensureDigest on the relay
	baseNetwork.prepareAllMulticast()
	for p := range pocketCert {
		baseNetwork.multicast(p.tag, p.data, p.source, p.exclude)
	}
	baseNetwork.finishAllMulticast()
	activityMonitor.waitForActivity()
	activityMonitor.waitForQuiet()
	// this relay must still relay initial messages. Note that payloads were already relayed with
	// the previous global timeout.
	triggerGlobalTimeout(FilterTimeout(0, version), TimeoutFilter, clocks[1:], activityMonitor)
	zeroes = expectNewPeriod(clocks[1:], zeroes)
	require.Equal(t, uint(3), clocks[0].(*testingClock).zeroes)

	for i := 0; i < numNodes; i++ {
		services[i].Shutdown()
	}
	const expectNumRounds = 4
	for i := 1; i < numNodes; i++ {
		if ledgers[i].NextRound() != startRound+round(expectNumRounds) {
			panic("did not progress 4 rounds")
		}
	}
	for j := 0; j < expectNumRounds; j++ {
		ledger := ledgers[1].(*testLedger)
		reference := ledger.entries[startRound+round(j)].Digest()
		for i := 1; i < numNodes; i++ {
			ledger := ledgers[i].(*testLedger)
			if ledger.entries[startRound+round(j)].Digest() != reference {
				panic("wrong block confirmed")
			}
		}
	}
}

func TestAgreementServiceStartDeadline(t *testing.T) {
	partitiontest.PartitionTest(t)

	accessor, err := db.MakeAccessor(t.Name()+"_crash.db", false, true)
	require.NoError(t, err)

	_, balances := createTestAccountsAndBalances(t, 1, (&[32]byte{})[:])
	baseLedger := makeTestLedger(balances).(*testLedger)

	testConsensusProtocolVersion := protocol.ConsensusVersion("TestAgreementServiceStartDeadline-testversion")
	testConsensusParams := config.Consensus[protocol.ConsensusCurrentVersion]
	testConsensusParams.AgreementFilterTimeoutPeriod0 *= 100
	config.Consensus[testConsensusProtocolVersion] = testConsensusParams
	defer func() {
		delete(config.Consensus, testConsensusProtocolVersion)
	}()

	baseLedger.consensusVersion = func(basics.Round) (protocol.ConsensusVersion, error) {
		return testConsensusProtocolVersion, nil
	}

	s := Service{
		log: serviceLogger{Logger: logging.TestingLog(t)},
		parameters: parameters{
			Accessor: accessor,
			Ledger:   baseLedger,
		},
	}
	s.log.Logger.SetLevel(logging.Error)

	inputCh := make(chan externalEvent, 1)
	close(inputCh)
	output := make(chan []action, 10)
	ready := make(chan externalDemuxSignals, 1)
	s.mainLoop(inputCh, output, ready)

	// check the ready channel:
	var demuxSignal externalDemuxSignals
	var ok bool
	select {
	case demuxSignal, ok = <-ready:
		require.True(t, ok)
	default:
		require.Fail(t, "ready channel was empty while it should have contained a single entry")
	}
	require.Equal(t, testConsensusParams.AgreementFilterTimeoutPeriod0, demuxSignal.Deadline.Duration)
	require.Equal(t, baseLedger.NextRound(), demuxSignal.CurrentRound)
}