casper-node 2.0.3

The Casper blockchain node
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
//! Main reactor for nodes.

mod config;
mod control;
mod error;
mod event;
mod fetchers;
mod memory_metrics;
mod utils;

mod catch_up;
mod genesis_instruction;
mod keep_up;
mod reactor_state;
#[cfg(test)]
mod tests;
mod upgrade_shutdown;
mod upgrading_instruction;
mod validate;

use std::{collections::BTreeMap, convert::TryInto, sync::Arc, time::Instant};

use datasize::DataSize;
use memory_metrics::MemoryMetrics;
use prometheus::Registry;
use tracing::{debug, error, info, warn};

use casper_binary_port::{LastProgress, NetworkName, Uptime};
use casper_types::{
    Block, BlockHash, BlockV2, Chainspec, ChainspecRawBytes, EraId, FinalitySignature,
    FinalitySignatureV2, PublicKey, TimeDiff, Timestamp, Transaction, U512,
};

#[cfg(test)]
use crate::testing::network::NetworkedReactor;
use crate::{
    components::{
        binary_port::{BinaryPort, BinaryPortInitializationError, Metrics as BinaryPortMetrics},
        block_accumulator::{self, BlockAccumulator},
        block_synchronizer::{self, BlockSynchronizer},
        block_validator::{self, BlockValidator},
        consensus::{self, EraSupervisor},
        contract_runtime::ContractRuntime,
        diagnostics_port::DiagnosticsPort,
        event_stream_server::{self, EventStreamServer},
        gossiper::{self, GossipItem, Gossiper},
        metrics::Metrics,
        network::{self, GossipedAddress, Identity as NetworkIdentity, Network},
        rest_server::RestServer,
        shutdown_trigger::{self, CompletedBlockInfo, ShutdownTrigger},
        storage::Storage,
        sync_leaper::SyncLeaper,
        transaction_acceptor::{self, TransactionAcceptor},
        transaction_buffer,
        transaction_buffer::TransactionBuffer,
        upgrade_watcher::{self, UpgradeWatcher},
        Component, ValidatorBoundComponent,
    },
    effect::{
        announcements::{
            BlockAccumulatorAnnouncement, ConsensusAnnouncement, ContractRuntimeAnnouncement,
            ControlAnnouncement, FetchedNewBlockAnnouncement,
            FetchedNewFinalitySignatureAnnouncement, GossiperAnnouncement, MetaBlockAnnouncement,
            PeerBehaviorAnnouncement, TransactionAcceptorAnnouncement,
            TransactionBufferAnnouncement, UnexecutedBlockAnnouncement, UpgradeWatcherAnnouncement,
        },
        incoming::{NetResponseIncoming, TrieResponseIncoming},
        requests::{
            AcceptTransactionRequest, ChainspecRawBytesRequest, ContractRuntimeRequest,
            ReactorInfoRequest,
        },
        EffectBuilder, EffectExt, Effects, GossipTarget,
    },
    failpoints::FailpointActivation,
    fatal,
    protocol::Message,
    reactor::{
        self,
        event_queue_metrics::EventQueueMetrics,
        main_reactor::{fetchers::Fetchers, upgrade_shutdown::SignatureGossipTracker},
        EventQueueHandle, QueueKind,
    },
    types::{
        ForwardMetaBlock, MetaBlock, MetaBlockState, SyncHandling, TrieOrChunk, ValidatorMatrix,
    },
    utils::{Source, WithDir},
    NodeRng,
};
pub use config::Config;
pub(crate) use error::Error;
pub(crate) use event::MainEvent;
pub(crate) use reactor_state::ReactorState;

/// Main node reactor.
///
/// This following diagram represents how the components involved in the **sync process** interact
/// with each other.
#[cfg_attr(doc, aquamarine::aquamarine)]
/// ```mermaid
/// flowchart TD
///     G((Network))
///     E((BlockAccumulator))
///     H[(Storage)]
///     I((SyncLeaper))
///     A(("Reactor<br/>(control logic)"))
///     B((ContractRuntime))
///     C((BlockSynchronizer))
///     D((Consensus))
///     K((Gossiper))
///     J((Fetcher))
///     F((TransactionBuffer))
///
///     I -->|"❌<br/>Never get<br/>SyncLeap<br/>from storage"| H
///     linkStyle 0 fill:none,stroke:red,color:red
///
///     A -->|"Execute block<br/>(genesis or upgrade)"| B
///
///     G -->|Peers| C
///     G -->|Peers| D
///
///     C -->|Block data| E
///
///     J -->|Block data| C
///
///     D -->|Execute block| B
///
///     A -->|SyncLeap| I
///
///     B -->|Put block| H
///     C -->|Mark block complete| H
///     E -->|Mark block complete| H
///     C -->|Execute block| B
///
///     C -->|Complete block<br/>with Transactions| F
///
///     K -->|Transaction| F
///     K -->|Block data| E
/// ```
#[derive(DataSize, Debug)]
pub(crate) struct MainReactor {
    // components
    //   i/o bound components
    storage: Storage,
    contract_runtime: ContractRuntime,
    upgrade_watcher: UpgradeWatcher,
    rest_server: RestServer,
    binary_port: BinaryPort,
    event_stream_server: EventStreamServer,
    diagnostics_port: DiagnosticsPort,
    shutdown_trigger: ShutdownTrigger,
    net: Network<MainEvent, Message>,
    consensus: EraSupervisor,

    // block handling
    block_validator: BlockValidator,
    block_accumulator: BlockAccumulator,
    block_synchronizer: BlockSynchronizer,

    // transaction handling
    transaction_acceptor: TransactionAcceptor,
    transaction_buffer: TransactionBuffer,

    // gossiping components
    address_gossiper: Gossiper<{ GossipedAddress::ID_IS_COMPLETE_ITEM }, GossipedAddress>,
    transaction_gossiper: Gossiper<{ Transaction::ID_IS_COMPLETE_ITEM }, Transaction>,
    block_gossiper: Gossiper<{ BlockV2::ID_IS_COMPLETE_ITEM }, BlockV2>,
    finality_signature_gossiper:
        Gossiper<{ FinalitySignatureV2::ID_IS_COMPLETE_ITEM }, FinalitySignatureV2>,

    // record retrieval
    sync_leaper: SyncLeaper,
    fetchers: Fetchers, // <-- this contains all fetchers to reduce top-level clutter

    // Non-components.
    //   metrics
    metrics: Metrics,
    #[data_size(skip)] // Never allocates heap data.
    memory_metrics: MemoryMetrics,
    #[data_size(skip)]
    event_queue_metrics: EventQueueMetrics,

    //   ambient settings / data / load-bearing config
    validator_matrix: ValidatorMatrix,
    trusted_hash: Option<BlockHash>,
    chainspec: Arc<Chainspec>,
    chainspec_raw_bytes: Arc<ChainspecRawBytes>,

    //   control logic
    state: ReactorState,
    max_attempts: usize,

    last_progress: Timestamp,
    attempts: usize,
    idle_tolerance: TimeDiff,
    control_logic_default_delay: TimeDiff,
    shutdown_for_upgrade_timeout: TimeDiff,
    switched_to_shutdown_for_upgrade: Timestamp,
    upgrade_timeout: TimeDiff,
    sync_handling: SyncHandling,
    signature_gossip_tracker: SignatureGossipTracker,
    /// The instant at which the node has started.
    node_startup_instant: Instant,

    finality_signature_creation: bool,
    prevent_validator_shutdown: bool,
}

impl reactor::Reactor for MainReactor {
    type Event = MainEvent;
    type Config = WithDir<Config>;
    type Error = Error;

    fn dispatch_event(
        &mut self,
        effect_builder: EffectBuilder<MainEvent>,
        rng: &mut NodeRng,
        event: MainEvent,
    ) -> Effects<MainEvent> {
        match event {
            MainEvent::ControlAnnouncement(ctrl_ann) => {
                error!("unhandled control announcement: {}", ctrl_ann);
                Effects::new()
            }
            MainEvent::SetNodeStopRequest(req) => reactor::wrap_effects(
                MainEvent::ShutdownTrigger,
                self.shutdown_trigger
                    .handle_event(effect_builder, rng, req.into()),
            ),

            MainEvent::FatalAnnouncement(fatal_ann) => {
                if self.consensus.is_active_validator() && self.prevent_validator_shutdown {
                    warn!(%fatal_ann, "consensus is active, not shutting down");
                    Effects::new()
                } else {
                    let ctrl_ann =
                        MainEvent::ControlAnnouncement(ControlAnnouncement::FatalError {
                            file: fatal_ann.file,
                            line: fatal_ann.line,
                            msg: fatal_ann.msg,
                        });
                    effect_builder
                        .into_inner()
                        .schedule(ctrl_ann, QueueKind::Control)
                        .ignore()
                }
            }

            // PRIMARY REACTOR STATE CONTROL LOGIC
            MainEvent::ReactorCrank => self.crank(effect_builder, rng),

            MainEvent::MainReactorRequest(req) => match req {
                ReactorInfoRequest::ReactorState { responder } => {
                    responder.respond(self.state).ignore()
                }
                ReactorInfoRequest::LastProgress { responder } => responder
                    .respond(LastProgress::new(self.last_progress))
                    .ignore(),
                ReactorInfoRequest::Uptime { responder } => responder
                    .respond(Uptime::new(self.node_startup_instant.elapsed().as_secs()))
                    .ignore(),
                ReactorInfoRequest::NetworkName { responder } => responder
                    .respond(NetworkName::new(self.chainspec.network_config.name.clone()))
                    .ignore(),
                ReactorInfoRequest::BalanceHoldsInterval { responder } => responder
                    .respond(self.chainspec.core_config.gas_hold_interval)
                    .ignore(),
            },
            MainEvent::MetaBlockAnnouncement(MetaBlockAnnouncement(meta_block)) => self
                .handle_meta_block(
                    effect_builder,
                    rng,
                    self.finality_signature_creation,
                    meta_block,
                ),
            MainEvent::UnexecutedBlockAnnouncement(UnexecutedBlockAnnouncement(block_height)) => {
                let only_from_available_block_range = true;
                if let Ok(Some(block_header)) = self
                    .storage
                    .read_block_header_by_height(block_height, only_from_available_block_range)
                {
                    let block_hash = block_header.block_hash();
                    reactor::wrap_effects(
                        MainEvent::Consensus,
                        self.consensus.handle_event(
                            effect_builder,
                            rng,
                            consensus::Event::BlockAdded {
                                header: Box::new(block_header),
                                header_hash: block_hash,
                            },
                        ),
                    )
                } else {
                    // Warn logging here because this codepath of handling an
                    // `UnexecutedBlockAnnouncement` is coming from the
                    // contract runtime when a block with a lower height than
                    // the next expected executable height is enqueued. This
                    // happens after restarts when consensus is creating the
                    // required eras and attempts to retrace its steps in the
                    // era by enqueuing all finalized blocks starting from the
                    // first one in that era, blocks which should have already
                    // been executed and marked complete in storage.
                    warn!(
                        block_height,
                        "Finalized block enqueued for execution, but a complete \
                        block header with the same height is not present in storage."
                    );
                    Effects::new()
                }
            }

            // LOCAL I/O BOUND COMPONENTS
            MainEvent::UpgradeWatcher(event) => reactor::wrap_effects(
                MainEvent::UpgradeWatcher,
                self.upgrade_watcher
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::UpgradeWatcherRequest(req) => reactor::wrap_effects(
                MainEvent::UpgradeWatcher,
                self.upgrade_watcher
                    .handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::UpgradeWatcherAnnouncement(UpgradeWatcherAnnouncement(
                maybe_next_upgrade,
            )) => {
                // register activation point of upgrade w/ block accumulator
                self.block_accumulator.register_activation_point(
                    maybe_next_upgrade
                        .as_ref()
                        .map(|next_upgrade| next_upgrade.activation_point()),
                );
                reactor::wrap_effects(
                    MainEvent::UpgradeWatcher,
                    self.upgrade_watcher.handle_event(
                        effect_builder,
                        rng,
                        upgrade_watcher::Event::GotNextUpgrade(maybe_next_upgrade),
                    ),
                )
            }
            MainEvent::RestServer(event) => reactor::wrap_effects(
                MainEvent::RestServer,
                self.rest_server.handle_event(effect_builder, rng, event),
            ),
            MainEvent::MetricsRequest(req) => reactor::wrap_effects(
                MainEvent::MetricsRequest,
                self.metrics.handle_event(effect_builder, rng, req),
            ),
            MainEvent::ChainspecRawBytesRequest(
                ChainspecRawBytesRequest::GetChainspecRawBytes(responder),
            ) => responder.respond(self.chainspec_raw_bytes.clone()).ignore(),
            MainEvent::EventStreamServer(event) => reactor::wrap_effects(
                MainEvent::EventStreamServer,
                self.event_stream_server
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::ShutdownTrigger(event) => reactor::wrap_effects(
                MainEvent::ShutdownTrigger,
                self.shutdown_trigger
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::DiagnosticsPort(event) => reactor::wrap_effects(
                MainEvent::DiagnosticsPort,
                self.diagnostics_port
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::DumpConsensusStateRequest(req) => reactor::wrap_effects(
                MainEvent::Consensus,
                self.consensus.handle_event(effect_builder, rng, req.into()),
            ),

            // NETWORK CONNECTION AND ORIENTATION
            MainEvent::Network(event) => reactor::wrap_effects(
                MainEvent::Network,
                self.net.handle_event(effect_builder, rng, event),
            ),
            MainEvent::NetworkRequest(req) => {
                let event = MainEvent::Network(network::Event::from(req));
                self.dispatch_event(effect_builder, rng, event)
            }
            MainEvent::NetworkInfoRequest(req) => {
                let event = MainEvent::Network(network::Event::from(req));
                self.dispatch_event(effect_builder, rng, event)
            }
            MainEvent::NetworkPeerBehaviorAnnouncement(ann) => {
                let mut effects = Effects::new();
                match &ann {
                    PeerBehaviorAnnouncement::OffenseCommitted {
                        offender,
                        justification: _,
                    } => {
                        let event = MainEvent::BlockSynchronizer(
                            block_synchronizer::Event::DisconnectFromPeer(**offender),
                        );
                        effects.extend(self.dispatch_event(effect_builder, rng, event));
                    }
                }
                effects.extend(self.dispatch_event(
                    effect_builder,
                    rng,
                    MainEvent::Network(ann.into()),
                ));
                effects
            }
            MainEvent::NetworkPeerRequestingData(incoming) => reactor::wrap_effects(
                MainEvent::Storage,
                self.storage
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::NetworkPeerProvidingData(NetResponseIncoming { sender, message }) => {
                reactor::handle_get_response(self, effect_builder, rng, sender, message)
            }
            MainEvent::AddressGossiper(event) => reactor::wrap_effects(
                MainEvent::AddressGossiper,
                self.address_gossiper
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::AddressGossiperIncoming(incoming) => reactor::wrap_effects(
                MainEvent::AddressGossiper,
                self.address_gossiper
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::AddressGossiperCrank(req) => reactor::wrap_effects(
                MainEvent::AddressGossiper,
                self.address_gossiper
                    .handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::AddressGossiperAnnouncement(gossiper_ann) => match gossiper_ann {
                GossiperAnnouncement::GossipReceived { .. }
                | GossiperAnnouncement::NewItemBody { .. }
                | GossiperAnnouncement::FinishedGossiping(_) => Effects::new(),
                GossiperAnnouncement::NewCompleteItem(gossiped_address) => {
                    let reactor_event =
                        MainEvent::Network(network::Event::PeerAddressReceived(gossiped_address));
                    self.dispatch_event(effect_builder, rng, reactor_event)
                }
            },
            MainEvent::SyncLeaper(event) => reactor::wrap_effects(
                MainEvent::SyncLeaper,
                self.sync_leaper.handle_event(effect_builder, rng, event),
            ),
            MainEvent::Consensus(event) => reactor::wrap_effects(
                MainEvent::Consensus,
                self.consensus.handle_event(effect_builder, rng, event),
            ),
            MainEvent::ConsensusMessageIncoming(incoming) => reactor::wrap_effects(
                MainEvent::Consensus,
                self.consensus
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::ConsensusDemand(demand) => reactor::wrap_effects(
                MainEvent::Consensus,
                self.consensus
                    .handle_event(effect_builder, rng, demand.into()),
            ),
            MainEvent::ConsensusAnnouncement(consensus_announcement) => {
                match consensus_announcement {
                    ConsensusAnnouncement::Proposed(block) => {
                        let reactor_event = MainEvent::TransactionBuffer(
                            transaction_buffer::Event::BlockProposed(block),
                        );
                        self.dispatch_event(effect_builder, rng, reactor_event)
                    }
                    ConsensusAnnouncement::Finalized(block) => {
                        let reactor_event = MainEvent::TransactionBuffer(
                            transaction_buffer::Event::BlockFinalized(block),
                        );
                        self.dispatch_event(effect_builder, rng, reactor_event)
                    }
                    ConsensusAnnouncement::Fault {
                        era_id,
                        public_key,
                        timestamp,
                    } => {
                        let reactor_event =
                            MainEvent::EventStreamServer(event_stream_server::Event::Fault {
                                era_id,
                                public_key,
                                timestamp,
                            });
                        self.dispatch_event(effect_builder, rng, reactor_event)
                    }
                }
            }

            // BLOCKS
            MainEvent::BlockValidator(event) => reactor::wrap_effects(
                MainEvent::BlockValidator,
                self.block_validator
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::BlockValidatorRequest(req) => self.dispatch_event(
                effect_builder,
                rng,
                MainEvent::BlockValidator(block_validator::Event::from(req)),
            ),
            MainEvent::BlockAccumulator(event) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::BlockAccumulatorRequest(request) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator
                    .handle_event(effect_builder, rng, request.into()),
            ),
            MainEvent::BlockSynchronizer(event) => reactor::wrap_effects(
                MainEvent::BlockSynchronizer,
                self.block_synchronizer
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::BlockSynchronizerRequest(req) => reactor::wrap_effects(
                MainEvent::BlockSynchronizer,
                self.block_synchronizer
                    .handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::BlockAccumulatorAnnouncement(
                BlockAccumulatorAnnouncement::AcceptedNewFinalitySignature { finality_signature },
            ) => {
                debug!(
                    "notifying finality signature gossiper to start gossiping for: {} , {}",
                    finality_signature.block_hash(),
                    finality_signature.public_key(),
                );
                let mut effects = reactor::wrap_effects(
                    MainEvent::FinalitySignatureGossiper,
                    self.finality_signature_gossiper.handle_event(
                        effect_builder,
                        rng,
                        gossiper::Event::ItemReceived {
                            item_id: finality_signature.gossip_id(),
                            source: Source::Ourself,
                            target: finality_signature.gossip_target(),
                        },
                    ),
                );

                effects.extend(reactor::wrap_effects(
                    MainEvent::EventStreamServer,
                    self.event_stream_server.handle_event(
                        effect_builder,
                        rng,
                        event_stream_server::Event::FinalitySignature(Box::new(
                            (*finality_signature).into(),
                        )),
                    ),
                ));

                effects
            }
            MainEvent::BlockGossiper(event) => reactor::wrap_effects(
                MainEvent::BlockGossiper,
                self.block_gossiper.handle_event(effect_builder, rng, event),
            ),
            MainEvent::BlockGossiperIncoming(incoming) => reactor::wrap_effects(
                MainEvent::BlockGossiper,
                self.block_gossiper
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::BlockGossiperAnnouncement(GossiperAnnouncement::GossipReceived {
                item_id: gossiped_block_id,
                sender,
            }) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator.handle_event(
                    effect_builder,
                    rng,
                    block_accumulator::Event::RegisterPeer {
                        block_hash: gossiped_block_id,
                        era_id: None,
                        sender,
                    },
                ),
            ),
            MainEvent::BlockGossiperAnnouncement(GossiperAnnouncement::NewCompleteItem(
                gossiped_block_id,
            )) => {
                error!(%gossiped_block_id, "gossiper should not announce new block");
                Effects::new()
            }
            MainEvent::BlockGossiperAnnouncement(GossiperAnnouncement::NewItemBody {
                item,
                sender,
            }) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator.handle_event(
                    effect_builder,
                    rng,
                    block_accumulator::Event::ReceivedBlock {
                        block: Arc::new(*item),
                        sender,
                    },
                ),
            ),
            MainEvent::BlockGossiperAnnouncement(GossiperAnnouncement::FinishedGossiping(
                _gossiped_block_id,
            )) => Effects::new(),
            MainEvent::BlockFetcherAnnouncement(FetchedNewBlockAnnouncement { block, peer }) => {
                // The block accumulator shouldn't concern itself with historical blocks that are
                // being fetched. If the block is not convertible to the current version it means
                // that it is surely a historical block.
                if let Ok(block) = (*block).clone().try_into() {
                    reactor::wrap_effects(
                        MainEvent::BlockAccumulator,
                        self.block_accumulator.handle_event(
                            effect_builder,
                            rng,
                            block_accumulator::Event::ReceivedBlock {
                                block: Arc::new(block),
                                sender: peer,
                            },
                        ),
                    )
                } else {
                    Effects::new()
                }
            }

            MainEvent::FinalitySignatureIncoming(incoming) => {
                // Finality signature received via broadcast.
                let sender = incoming.sender;
                let finality_signature = incoming.message;
                debug!(
                    "FinalitySignatureIncoming({},{},{},{})",
                    finality_signature.era_id(),
                    finality_signature.block_hash(),
                    finality_signature.public_key(),
                    sender
                );
                let block_accumulator_event = block_accumulator::Event::ReceivedFinalitySignature {
                    finality_signature,
                    sender,
                };
                reactor::wrap_effects(
                    MainEvent::BlockAccumulator,
                    self.block_accumulator.handle_event(
                        effect_builder,
                        rng,
                        block_accumulator_event,
                    ),
                )
            }
            MainEvent::FinalitySignatureGossiper(event) => reactor::wrap_effects(
                MainEvent::FinalitySignatureGossiper,
                self.finality_signature_gossiper
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::FinalitySignatureGossiperIncoming(incoming) => reactor::wrap_effects(
                MainEvent::FinalitySignatureGossiper,
                self.finality_signature_gossiper
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::FinalitySignatureGossiperAnnouncement(
                GossiperAnnouncement::GossipReceived {
                    item_id: gossiped_finality_signature_id,
                    sender,
                },
            ) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator.handle_event(
                    effect_builder,
                    rng,
                    block_accumulator::Event::RegisterPeer {
                        block_hash: *gossiped_finality_signature_id.block_hash(),
                        era_id: Some(gossiped_finality_signature_id.era_id()),
                        sender,
                    },
                ),
            ),
            MainEvent::FinalitySignatureGossiperAnnouncement(
                GossiperAnnouncement::NewCompleteItem(gossiped_finality_signature_id),
            ) => {
                error!(%gossiped_finality_signature_id, "gossiper should not announce new finality signature");
                Effects::new()
            }
            MainEvent::FinalitySignatureGossiperAnnouncement(
                GossiperAnnouncement::NewItemBody { item, sender },
            ) => reactor::wrap_effects(
                MainEvent::BlockAccumulator,
                self.block_accumulator.handle_event(
                    effect_builder,
                    rng,
                    block_accumulator::Event::ReceivedFinalitySignature {
                        finality_signature: item,
                        sender,
                    },
                ),
            ),
            MainEvent::FinalitySignatureGossiperAnnouncement(
                GossiperAnnouncement::FinishedGossiping(gossiped_finality_signature_id),
            ) => {
                self.signature_gossip_tracker
                    .register_signature(gossiped_finality_signature_id);
                Effects::new()
            }
            MainEvent::FinalitySignatureFetcherAnnouncement(
                FetchedNewFinalitySignatureAnnouncement {
                    finality_signature,
                    peer,
                },
            ) => {
                // If the signature is not convertible to the current version it means
                // that it is historical.
                if let FinalitySignature::V2(sig) = *finality_signature {
                    reactor::wrap_effects(
                        MainEvent::BlockAccumulator,
                        self.block_accumulator.handle_event(
                            effect_builder,
                            rng,
                            block_accumulator::Event::ReceivedFinalitySignature {
                                finality_signature: Box::new(sig),
                                sender: peer,
                            },
                        ),
                    )
                } else {
                    Effects::new()
                }
            }

            // TRANSACTIONS
            MainEvent::TransactionAcceptor(event) => reactor::wrap_effects(
                MainEvent::TransactionAcceptor,
                self.transaction_acceptor
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::AcceptTransactionRequest(AcceptTransactionRequest {
                transaction,
                is_speculative,
                responder,
            }) => {
                let source = if is_speculative {
                    Source::SpeculativeExec
                } else {
                    Source::Client
                };
                let event = transaction_acceptor::Event::Accept {
                    transaction,
                    source,
                    maybe_responder: Some(responder),
                };
                reactor::wrap_effects(
                    MainEvent::TransactionAcceptor,
                    self.transaction_acceptor
                        .handle_event(effect_builder, rng, event),
                )
            }
            MainEvent::TransactionAcceptorAnnouncement(
                TransactionAcceptorAnnouncement::AcceptedNewTransaction {
                    transaction,
                    source,
                },
            ) => {
                let mut effects = Effects::new();

                match source {
                    Source::Ourself => (), // internal activity does not require further action
                    Source::Peer(_) => {
                        // this is a response to a transaction fetch request, dispatch to fetcher
                        effects.extend(self.fetchers.dispatch_fetcher_event(
                            effect_builder,
                            rng,
                            MainEvent::TransactionAcceptorAnnouncement(
                                TransactionAcceptorAnnouncement::AcceptedNewTransaction {
                                    transaction,
                                    source,
                                },
                            ),
                        ));
                    }
                    Source::Client | Source::PeerGossiped(_) => {
                        // we must attempt to gossip onwards
                        effects.extend(self.dispatch_event(
                            effect_builder,
                            rng,
                            MainEvent::TransactionGossiper(gossiper::Event::ItemReceived {
                                item_id: transaction.gossip_id(),
                                source,
                                target: transaction.gossip_target(),
                            }),
                        ));
                        // notify event stream
                        effects.extend(self.dispatch_event(
                            effect_builder,
                            rng,
                            MainEvent::EventStreamServer(
                                event_stream_server::Event::TransactionAccepted(Arc::clone(
                                    &transaction,
                                )),
                            ),
                        ));
                    }
                    Source::SpeculativeExec => {
                        error!(
                            %transaction,
                            "transaction acceptor should not announce speculative exec transactions"
                        );
                    }
                }

                effects
            }
            MainEvent::TransactionAcceptorAnnouncement(
                TransactionAcceptorAnnouncement::InvalidTransaction {
                    transaction: _,
                    source: _,
                },
            ) => Effects::new(),
            MainEvent::TransactionGossiper(event) => reactor::wrap_effects(
                MainEvent::TransactionGossiper,
                self.transaction_gossiper
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::TransactionGossiperIncoming(incoming) => reactor::wrap_effects(
                MainEvent::TransactionGossiper,
                self.transaction_gossiper
                    .handle_event(effect_builder, rng, incoming.into()),
            ),
            MainEvent::TransactionGossiperAnnouncement(GossiperAnnouncement::GossipReceived {
                ..
            }) => {
                // Ignore the announcement.
                Effects::new()
            }
            MainEvent::TransactionGossiperAnnouncement(GossiperAnnouncement::NewCompleteItem(
                gossiped_transaction_id,
            )) => {
                error!(%gossiped_transaction_id, "gossiper should not announce new transaction");
                Effects::new()
            }
            MainEvent::TransactionGossiperAnnouncement(GossiperAnnouncement::NewItemBody {
                item,
                sender,
            }) => reactor::wrap_effects(
                MainEvent::TransactionAcceptor,
                self.transaction_acceptor.handle_event(
                    effect_builder,
                    rng,
                    transaction_acceptor::Event::Accept {
                        transaction: *item,
                        source: Source::PeerGossiped(sender),
                        maybe_responder: None,
                    },
                ),
            ),
            MainEvent::TransactionGossiperAnnouncement(
                GossiperAnnouncement::FinishedGossiping(gossiped_txn_id),
            ) => {
                let reactor_event = MainEvent::TransactionBuffer(
                    transaction_buffer::Event::ReceiveTransactionGossiped(gossiped_txn_id),
                );
                self.dispatch_event(effect_builder, rng, reactor_event)
            }
            MainEvent::TransactionBuffer(event) => reactor::wrap_effects(
                MainEvent::TransactionBuffer,
                self.transaction_buffer
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::TransactionBufferRequest(req) => self.dispatch_event(
                effect_builder,
                rng,
                MainEvent::TransactionBuffer(req.into()),
            ),
            MainEvent::TransactionBufferAnnouncement(
                TransactionBufferAnnouncement::TransactionsExpired(hashes),
            ) => {
                let reactor_event = MainEvent::EventStreamServer(
                    event_stream_server::Event::TransactionsExpired(hashes),
                );
                self.dispatch_event(effect_builder, rng, reactor_event)
            }

            // CONTRACT RUNTIME & GLOBAL STATE
            MainEvent::ContractRuntime(event) => reactor::wrap_effects(
                MainEvent::ContractRuntime,
                self.contract_runtime
                    .handle_event(effect_builder, rng, event),
            ),
            MainEvent::ContractRuntimeRequest(req) => reactor::wrap_effects(
                MainEvent::ContractRuntime,
                self.contract_runtime
                    .handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::ContractRuntimeAnnouncement(
                ContractRuntimeAnnouncement::CommitStepSuccess { era_id, effects },
            ) => {
                let reactor_event =
                    MainEvent::EventStreamServer(event_stream_server::Event::Step {
                        era_id,
                        execution_effects: effects,
                    });
                self.dispatch_event(effect_builder, rng, reactor_event)
            }
            MainEvent::ContractRuntimeAnnouncement(
                ContractRuntimeAnnouncement::UpcomingEraValidators {
                    era_that_is_ending,
                    upcoming_era_validators,
                },
            ) => {
                info!(
                    "UpcomingEraValidators era_that_is_ending: {}",
                    era_that_is_ending
                );
                self.validator_matrix.register_eras(upcoming_era_validators);
                Effects::new()
            }
            MainEvent::ContractRuntimeAnnouncement(
                ContractRuntimeAnnouncement::NextEraGasPrice {
                    era_id,
                    next_era_gas_price,
                },
            ) => {
                info!(
                    "New era gas price {} for era {}",
                    next_era_gas_price, era_id
                );
                let event = MainEvent::ContractRuntimeRequest(
                    ContractRuntimeRequest::UpdateRuntimePrice(era_id, next_era_gas_price),
                );
                let mut effects = self.dispatch_event(effect_builder, rng, event);
                let reactor_event = MainEvent::TransactionBuffer(
                    transaction_buffer::Event::UpdateEraGasPrice(era_id, next_era_gas_price),
                );
                effects.extend(self.dispatch_event(effect_builder, rng, reactor_event));
                let reactor_event = MainEvent::BlockValidator(
                    block_validator::Event::UpdateEraGasPrice(era_id, next_era_gas_price),
                );
                effects.extend(self.dispatch_event(effect_builder, rng, reactor_event));
                effects
            }

            MainEvent::TrieRequestIncoming(req) => reactor::wrap_effects(
                MainEvent::ContractRuntime,
                self.contract_runtime
                    .handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::TrieDemand(demand) => reactor::wrap_effects(
                MainEvent::ContractRuntime,
                self.contract_runtime
                    .handle_event(effect_builder, rng, demand.into()),
            ),
            MainEvent::TrieResponseIncoming(TrieResponseIncoming { sender, message }) => {
                reactor::handle_fetch_response::<Self, TrieOrChunk>(
                    self,
                    effect_builder,
                    rng,
                    sender,
                    &message.0,
                )
            }

            // STORAGE
            MainEvent::Storage(event) => reactor::wrap_effects(
                MainEvent::Storage,
                self.storage.handle_event(effect_builder, rng, event),
            ),
            MainEvent::StorageRequest(req) => reactor::wrap_effects(
                MainEvent::Storage,
                self.storage.handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::MarkBlockCompletedRequest(req) => reactor::wrap_effects(
                MainEvent::Storage,
                self.storage.handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::MakeBlockExecutableRequest(req) => reactor::wrap_effects(
                MainEvent::Storage,
                self.storage.handle_event(effect_builder, rng, req.into()),
            ),
            MainEvent::BinaryPort(req) => reactor::wrap_effects(
                MainEvent::BinaryPort,
                self.binary_port.handle_event(effect_builder, rng, req),
            ),

            // This event gets emitted when we manage to read the era validators from the global
            // states of a block after an upgrade and its parent. Once that happens, we can check
            // for the signs of any changes happening during the upgrade and register the correct
            // set of validators in the validators matrix.
            MainEvent::GotBlockAfterUpgradeEraValidators(
                era_id,
                parent_era_validators,
                block_era_validators,
            ) => {
                // `era_id`, being the era of the block after the upgrade, will be absent in the
                // validators stored in the block after the upgrade - therefore we will use its
                // successor for the comparison.
                let era_to_check = era_id.successor();
                // We read the validators for era_id+1 from the parent of the block after the
                // upgrade.
                let validators_in_parent = match parent_era_validators.get(&era_to_check) {
                    Some(validators) => validators,
                    None => {
                        return fatal!(
                            effect_builder,
                            "couldn't find validators for era {} in parent_era_validators",
                            era_to_check
                        )
                        .ignore();
                    }
                };
                // We also read the validators from the block after the upgrade itself.
                let validators_in_block = match block_era_validators.get(&era_to_check) {
                    Some(validators) => validators,
                    None => {
                        return fatal!(
                            effect_builder,
                            "couldn't find validators for era {} in block_era_validators",
                            era_to_check
                        )
                        .ignore();
                    }
                };
                // Decide which validators to use for `era_id` in the validators matrix.
                let validators_to_register = if validators_in_parent == validators_in_block {
                    // Nothing interesting happened - register the regular validators, ie. the
                    // ones stored for `era_id` in the parent of the block after the upgrade.
                    match parent_era_validators.get(&era_id) {
                        Some(validators) => validators,
                        None => {
                            return fatal!(
                                effect_builder,
                                "couldn't find validators for era {} in parent_era_validators",
                                era_id
                            )
                            .ignore();
                        }
                    }
                } else {
                    // We had an upgrade changing the validators! We use the same validators that
                    // will be used for the era after the upgrade, as we can't trust the ones we
                    // would use normally.
                    validators_in_block
                };
                let mut effects = self.update_validator_weights(
                    effect_builder,
                    rng,
                    era_id,
                    validators_to_register.clone(),
                );
                // Crank the reactor so that any synchronizing tasks blocked by the lack of
                // validators for `era_id` can resume.
                effects.extend(
                    effect_builder
                        .immediately()
                        .event(|_| MainEvent::ReactorCrank),
                );
                effects
            }

            // DELEGATE ALL FETCHER RELEVANT EVENTS to self.fetchers.dispatch_fetcher_event(..)
            MainEvent::LegacyDeployFetcher(..)
            | MainEvent::LegacyDeployFetcherRequest(..)
            | MainEvent::BlockFetcher(..)
            | MainEvent::BlockFetcherRequest(..)
            | MainEvent::TransactionFetcher(..)
            | MainEvent::TransactionFetcherRequest(..)
            | MainEvent::BlockHeaderFetcher(..)
            | MainEvent::BlockHeaderFetcherRequest(..)
            | MainEvent::TrieOrChunkFetcher(..)
            | MainEvent::TrieOrChunkFetcherRequest(..)
            | MainEvent::SyncLeapFetcher(..)
            | MainEvent::SyncLeapFetcherRequest(..)
            | MainEvent::ApprovalsHashesFetcher(..)
            | MainEvent::ApprovalsHashesFetcherRequest(..)
            | MainEvent::FinalitySignatureFetcher(..)
            | MainEvent::FinalitySignatureFetcherRequest(..)
            | MainEvent::BlockExecutionResultsOrChunkFetcher(..)
            | MainEvent::BlockExecutionResultsOrChunkFetcherRequest(..) => self
                .fetchers
                .dispatch_fetcher_event(effect_builder, rng, event),
        }
    }

    fn new(
        config: Self::Config,
        chainspec: Arc<Chainspec>,
        chainspec_raw_bytes: Arc<ChainspecRawBytes>,
        network_identity: NetworkIdentity,
        registry: &Registry,
        event_queue: EventQueueHandle<Self::Event>,
        _rng: &mut NodeRng,
    ) -> Result<(Self, Effects<MainEvent>), Error> {
        let node_startup_instant = Instant::now();

        let effect_builder = EffectBuilder::new(event_queue);

        let metrics = Metrics::new(registry.clone());
        let memory_metrics = MemoryMetrics::new(registry.clone())?;
        let event_queue_metrics = EventQueueMetrics::new(registry.clone(), event_queue)?;

        let protocol_version = chainspec.protocol_config.version;
        let prevent_validator_shutdown = config.value().node.prevent_validator_shutdown;

        let trusted_hash = config.value().node.trusted_hash;
        let (root_dir, config) = config.into_parts();
        let (our_secret_key, our_public_key) = config.consensus.load_keys(&root_dir)?;
        let validator_matrix = ValidatorMatrix::new(
            chainspec.core_config.finality_threshold_fraction,
            chainspec.name_hash(),
            chainspec
                .protocol_config
                .global_state_update
                .as_ref()
                .and_then(|global_state_update| global_state_update.validators.clone()),
            chainspec.protocol_config.activation_point.era_id(),
            our_secret_key.clone(),
            our_public_key.clone(),
            chainspec.core_config.auction_delay,
            chainspec.core_config.signature_rewards_max_delay,
        );

        let storage_config = WithDir::new(&root_dir, config.storage.clone());

        let hard_reset_to_start_of_era = chainspec.hard_reset_to_start_of_era();
        let storage = Storage::new(
            &storage_config,
            hard_reset_to_start_of_era,
            protocol_version,
            chainspec.protocol_config.activation_point.era_id(),
            &chainspec.network_config.name,
            chainspec.transaction_config.max_ttl.into(),
            chainspec.core_config.recent_era_count(),
            Some(registry),
            config.node.force_resync,
            chainspec.transaction_config.clone(),
        )?;

        let contract_runtime = ContractRuntime::new(
            storage.root_path(),
            &config.contract_runtime,
            chainspec.clone(),
            registry,
        )?;

        let allow_handshake = config.node.sync_handling != SyncHandling::Isolated;

        let network = Network::new(
            config.network.clone(),
            network_identity,
            Some((our_secret_key, our_public_key)),
            registry,
            chainspec.as_ref(),
            validator_matrix.clone(),
            allow_handshake,
        )?;

        let address_gossiper = Gossiper::<{ GossipedAddress::ID_IS_COMPLETE_ITEM }, _>::new(
            "address_gossiper",
            config.gossip,
            registry,
        )?;

        let rest_server = RestServer::new(
            config.rest_server.clone(),
            protocol_version,
            chainspec.network_config.name.clone(),
        );
        let binary_port_metrics =
            BinaryPortMetrics::new(registry).map_err(BinaryPortInitializationError::from)?;
        let binary_port = BinaryPort::new(
            config.binary_port_server.clone(),
            chainspec.clone(),
            binary_port_metrics,
        );
        let event_stream_server = EventStreamServer::new(
            config.event_stream_server.clone(),
            storage.root_path().to_path_buf(),
            protocol_version,
        );
        let diagnostics_port =
            DiagnosticsPort::new(WithDir::new(&root_dir, config.diagnostics_port));
        let shutdown_trigger = ShutdownTrigger::new();

        // local / remote data management
        let sync_leaper = SyncLeaper::new(chainspec.clone(), registry)?;
        let fetchers = Fetchers::new(&config.fetcher, registry)?;

        // gossipers
        let block_gossiper = Gossiper::<{ BlockV2::ID_IS_COMPLETE_ITEM }, _>::new(
            "block_gossiper",
            config.gossip,
            registry,
        )?;
        let transaction_gossiper = Gossiper::<{ Transaction::ID_IS_COMPLETE_ITEM }, _>::new(
            "transaction_gossiper",
            config.gossip,
            registry,
        )?;
        let finality_signature_gossiper = Gossiper::<
            { FinalitySignatureV2::ID_IS_COMPLETE_ITEM },
            _,
        >::new(
            "finality_signature_gossiper", config.gossip, registry
        )?;

        // consensus
        let consensus = EraSupervisor::new(
            storage.root_path(),
            validator_matrix.clone(),
            config.consensus,
            chainspec.clone(),
            registry,
        )?;

        // chain / transaction management

        let block_accumulator = BlockAccumulator::new(
            config.block_accumulator,
            validator_matrix.clone(),
            chainspec.core_config.unbonding_delay,
            chainspec.core_config.minimum_block_time,
            chainspec.core_config.validator_slots,
            registry,
        )?;
        let block_synchronizer = BlockSynchronizer::new(
            config.block_synchronizer,
            chainspec.clone(),
            chainspec.core_config.simultaneous_peer_requests,
            validator_matrix.clone(),
            registry,
        )?;
        let block_validator = BlockValidator::new(
            Arc::clone(&chainspec),
            validator_matrix.clone(),
            config.block_validator,
            chainspec.vacancy_config.min_gas_price,
        );
        let upgrade_watcher =
            UpgradeWatcher::new(chainspec.as_ref(), config.upgrade_watcher, &root_dir)?;
        let transaction_acceptor = TransactionAcceptor::new(
            config.transaction_acceptor,
            Arc::clone(&chainspec),
            registry,
        )?;
        let transaction_buffer =
            TransactionBuffer::new(Arc::clone(&chainspec), config.transaction_buffer, registry)?;

        let reactor = MainReactor {
            chainspec,
            chainspec_raw_bytes,
            storage,
            contract_runtime,
            upgrade_watcher,
            net: network,
            address_gossiper,

            rest_server,
            binary_port,
            event_stream_server,
            transaction_acceptor,
            fetchers,

            block_gossiper,
            transaction_gossiper,
            finality_signature_gossiper,
            sync_leaper,
            transaction_buffer,
            consensus,
            block_validator,
            block_accumulator,
            block_synchronizer,
            diagnostics_port,
            shutdown_trigger,

            metrics,
            memory_metrics,
            event_queue_metrics,

            state: ReactorState::Initialize {},
            attempts: 0,
            last_progress: Timestamp::now(),
            max_attempts: config.node.max_attempts,
            idle_tolerance: config.node.idle_tolerance,
            control_logic_default_delay: config.node.control_logic_default_delay,
            trusted_hash,
            validator_matrix,
            sync_handling: config.node.sync_handling,
            signature_gossip_tracker: SignatureGossipTracker::new(),
            shutdown_for_upgrade_timeout: config.node.shutdown_for_upgrade_timeout,
            switched_to_shutdown_for_upgrade: Timestamp::from(0),
            upgrade_timeout: config.node.upgrade_timeout,
            node_startup_instant,
            finality_signature_creation: true,
            prevent_validator_shutdown,
        };
        info!("MainReactor: instantiated");

        // If there's an upgrade staged with the same activation point as the current one, we must
        // shut down immediately for upgrade.
        let should_upgrade_immediately = reactor.upgrade_watcher.next_upgrade_activation_point()
            == Some(reactor.chainspec.protocol_config.activation_point.era_id());
        let effects = if should_upgrade_immediately {
            info!("MainReactor: immediate shutdown for upgrade");
            effect_builder
                .immediately()
                .event(|()| MainEvent::ControlAnnouncement(ControlAnnouncement::ShutdownForUpgrade))
        } else {
            effect_builder
                .immediately()
                .event(|()| MainEvent::ReactorCrank)
        };
        Ok((reactor, effects))
    }

    fn update_metrics(&mut self, event_queue_handle: EventQueueHandle<Self::Event>) {
        self.memory_metrics.estimate(self);
        self.event_queue_metrics
            .record_event_queue_counts(&event_queue_handle)
    }

    fn activate_failpoint(&mut self, activation: &FailpointActivation) {
        if activation.key().starts_with("consensus") {
            <EraSupervisor as Component<MainEvent>>::activate_failpoint(
                &mut self.consensus,
                activation,
            );
        }
        if activation.key().starts_with("finality_signature_creation") {
            self.finality_signature_creation = false;
        }
    }
}

impl MainReactor {
    fn update_validator_weights(
        &mut self,
        effect_builder: EffectBuilder<MainEvent>,
        rng: &mut NodeRng,
        era_id: EraId,
        validator_weights: BTreeMap<PublicKey, U512>,
    ) -> Effects<MainEvent> {
        self.validator_matrix
            .register_validator_weights(era_id, validator_weights);
        info!(%era_id, "validator_matrix updated");
        // notify validator bound components
        let mut effects = reactor::wrap_effects(
            MainEvent::BlockAccumulator,
            self.block_accumulator
                .handle_validators(effect_builder, rng),
        );
        effects.extend(reactor::wrap_effects(
            MainEvent::BlockSynchronizer,
            self.block_synchronizer
                .handle_validators(effect_builder, rng),
        ));
        effects
    }

    fn handle_meta_block(
        &mut self,
        effect_builder: EffectBuilder<MainEvent>,
        rng: &mut NodeRng,
        create_finality_signatures: bool,
        mut meta_block: MetaBlock,
    ) -> Effects<MainEvent> {
        debug!(
            "MetaBlock: handling meta block {} {} {:?}",
            meta_block.height(),
            meta_block.hash(),
            meta_block.state()
        );
        if !meta_block.state().is_stored() {
            return fatal!(
                effect_builder,
                "MetaBlock: block should be stored after execution or accumulation"
            )
            .ignore();
        }

        let mut effects = Effects::new();

        if meta_block
            .mut_state()
            .register_as_sent_to_transaction_buffer()
            .was_updated()
        {
            debug!(
                "MetaBlock: notifying transaction buffer: {} {}",
                meta_block.height(),
                meta_block.hash(),
            );

            match &meta_block {
                MetaBlock::Forward(fwd_meta_block) => {
                    effects.extend(reactor::wrap_effects(
                        MainEvent::TransactionBuffer,
                        self.transaction_buffer.handle_event(
                            effect_builder,
                            rng,
                            transaction_buffer::Event::Block(Arc::clone(&fwd_meta_block.block)),
                        ),
                    ));
                }
                MetaBlock::Historical(historical_meta_block) => {
                    effects.extend(reactor::wrap_effects(
                        MainEvent::TransactionBuffer,
                        self.transaction_buffer.handle_event(
                            effect_builder,
                            rng,
                            transaction_buffer::Event::VersionedBlock(Arc::clone(
                                &historical_meta_block.block,
                            )),
                        ),
                    ));
                }
            }
        }

        if let MetaBlock::Forward(forward_meta_block) = &meta_block {
            let block = forward_meta_block.block.clone();
            if meta_block
                .mut_state()
                .register_updated_validator_matrix()
                .was_updated()
            {
                if let Some(validator_weights) = block.header().next_era_validator_weights() {
                    let era_id = block.era_id();
                    let next_era_id = era_id.successor();
                    debug!(
                        "MetaBlock: updating validator matrix: {} {} {} {}",
                        block.height(),
                        block.hash(),
                        era_id,
                        next_era_id
                    );
                    effects.extend(self.update_validator_weights(
                        effect_builder,
                        rng,
                        next_era_id,
                        validator_weights.clone(),
                    ));
                }
            }

            // Validators gossip the block as soon as they deem it valid, but non-validators
            // only gossip once the block is marked complete.
            if let Some(true) = self
                .validator_matrix
                .is_self_validator_in_era(block.era_id())
            {
                debug!(
                    "MetaBlock: updating validator gossip state: {} {}",
                    block.height(),
                    block.hash(),
                );
                self.update_meta_block_gossip_state(
                    effect_builder,
                    rng,
                    block.hash(),
                    block.gossip_target(),
                    meta_block.mut_state(),
                    &mut effects,
                );
            }

            if !meta_block.state().is_executed() {
                debug!(
                    "MetaBlock: unexecuted block: {} {}",
                    block.height(),
                    block.hash(),
                );
                // We've done as much as we can on a valid but un-executed block.
                return effects;
            }

            if meta_block
                .mut_state()
                .register_we_have_tried_to_sign()
                .was_updated()
                && create_finality_signatures
            {
                // When this node is a validator in this era, sign and announce.
                if let Some(finality_signature) = self
                    .validator_matrix
                    .create_finality_signature(block.header())
                {
                    debug!(
                        %finality_signature,
                        "MetaBlock: registering finality signature: {} {}",
                        block.height(),
                        block.hash(),
                    );

                    effects.extend(reactor::wrap_effects(
                        MainEvent::Storage,
                        effect_builder
                            .put_finality_signature_to_storage(finality_signature.clone().into())
                            .ignore(),
                    ));

                    effects.extend(reactor::wrap_effects(
                        MainEvent::BlockAccumulator,
                        self.block_accumulator.handle_event(
                            effect_builder,
                            rng,
                            block_accumulator::Event::CreatedFinalitySignature {
                                finality_signature: Box::new(finality_signature.clone()),
                            },
                        ),
                    ));

                    let era_id = finality_signature.era_id();
                    let payload = Message::FinalitySignature(Box::new(finality_signature));
                    effects.extend(reactor::wrap_effects(
                        MainEvent::Network,
                        effect_builder
                            .broadcast_message_to_validators(payload, era_id)
                            .ignore(),
                    ));
                }
            }
        }

        if meta_block
            .mut_state()
            .register_as_validator_notified()
            .was_updated()
        {
            debug!(
                "MetaBlock: notifying block validator: {} {}",
                meta_block.height(),
                meta_block.hash(),
            );
            effects.extend(reactor::wrap_effects(
                MainEvent::BlockValidator,
                self.block_validator.handle_event(
                    effect_builder,
                    rng,
                    block_validator::Event::BlockStored(meta_block.height()),
                ),
            ));
        }

        if meta_block
            .mut_state()
            .register_as_consensus_notified()
            .was_updated()
        {
            debug!(
                "MetaBlock: notifying consensus: {} {}",
                meta_block.height(),
                meta_block.hash(),
            );

            match &meta_block {
                MetaBlock::Forward(fwd_meta_block) => {
                    effects.extend(reactor::wrap_effects(
                        MainEvent::Consensus,
                        self.consensus.handle_event(
                            effect_builder,
                            rng,
                            consensus::Event::BlockAdded {
                                header: Box::new(fwd_meta_block.block.header().clone().into()),
                                header_hash: *fwd_meta_block.block.hash(),
                            },
                        ),
                    ));
                }
                MetaBlock::Historical(_historical_meta_block) => {
                    // Historical meta blocks aren't of interest to consensus - consensus only
                    // cares about new blocks. Hence, we can just do nothing here.
                }
            }
        }

        if let MetaBlock::Forward(forward_meta_block) = &meta_block {
            let block = forward_meta_block.block.clone();
            let execution_results = forward_meta_block.execution_results.clone();

            if meta_block
                .mut_state()
                .register_as_accumulator_notified()
                .was_updated()
            {
                debug!(
                    "MetaBlock: notifying accumulator: {} {}",
                    block.height(),
                    block.hash(),
                );
                let meta_block = ForwardMetaBlock {
                    block,
                    execution_results,
                    state: *meta_block.state(),
                };

                effects.extend(reactor::wrap_effects(
                    MainEvent::BlockAccumulator,
                    self.block_accumulator.handle_event(
                        effect_builder,
                        rng,
                        block_accumulator::Event::ExecutedBlock { meta_block },
                    ),
                ));
                // We've done as much as we can for now, we need to wait for the block
                // accumulator to mark the block complete before proceeding further.
                return effects;
            }
        }

        // We *always* want to initialize the contract runtime with the highest complete block.
        // In case of an upgrade, we want the reactor to hold off in the `Upgrading` state until
        // the immediate switch block is stored and *also* marked complete.
        // This will allow the contract runtime to initialize properly (see
        // [`refresh_contract_runtime`]) when the reactor is transitioning from `CatchUp` to
        // `KeepUp`.
        if !meta_block.state().is_marked_complete() {
            error!(
                block_hash = ?meta_block.hash(),
                state = ?meta_block.state(),
                "should be a complete block after passing to accumulator"
            );
        } else {
            debug!(
                "MetaBlock: block is marked complete: {} {}",
                meta_block.height(),
                meta_block.hash(),
            );
        }

        if let MetaBlock::Forward(forward_meta_block) = &meta_block {
            let block = forward_meta_block.block.clone();

            debug!(
                "MetaBlock: update gossip state: {} {}",
                block.height(),
                block.hash(),
            );
            self.update_meta_block_gossip_state(
                effect_builder,
                rng,
                block.hash(),
                block.gossip_target(),
                meta_block.mut_state(),
                &mut effects,
            );

            if meta_block
                .mut_state()
                .register_as_synchronizer_notified()
                .was_updated()
            {
                debug!(
                    "MetaBlock: notifying block synchronizer: {} {}",
                    block.height(),
                    block.hash(),
                );

                effects.extend(reactor::wrap_effects(
                    MainEvent::BlockSynchronizer,
                    self.block_synchronizer.handle_event(
                        effect_builder,
                        rng,
                        block_synchronizer::Event::MarkBlockExecuted(*block.hash()),
                    ),
                ));
            }
        }

        debug_assert!(
            meta_block.state().verify_complete(),
            "meta block {} at height {} has invalid state: {:?}",
            meta_block.hash(),
            meta_block.height(),
            meta_block.state()
        );

        if meta_block
            .mut_state()
            .register_all_actions_done()
            .was_already_registered()
        {
            error!(
                block_hash = ?meta_block.hash(),
                state = ?meta_block.state(),
                "duplicate meta block announcement emitted"
            );
            return effects;
        }

        debug!(
            "MetaBlock: notifying event stream: {} {}",
            meta_block.height(),
            meta_block.hash(),
        );
        let versioned_block: Arc<Block> = match &meta_block {
            MetaBlock::Forward(fwd_meta_block) => Arc::new((*fwd_meta_block.block).clone().into()),
            MetaBlock::Historical(historical_meta_block) => historical_meta_block.block.clone(),
        };
        effects.extend(reactor::wrap_effects(
            MainEvent::EventStreamServer,
            self.event_stream_server.handle_event(
                effect_builder,
                rng,
                event_stream_server::Event::BlockAdded(Arc::clone(&versioned_block)),
            ),
        ));

        match &meta_block {
            MetaBlock::Forward(fwd_meta_block) => {
                for exec_artifact in fwd_meta_block.execution_results.iter() {
                    let event = event_stream_server::Event::TransactionProcessed {
                        transaction_hash: exec_artifact.transaction_hash,
                        transaction_header: Box::new(exec_artifact.transaction_header.clone()),
                        block_hash: *fwd_meta_block.block.hash(),
                        execution_result: Box::new(exec_artifact.execution_result.clone()),
                        messages: exec_artifact.messages.clone(),
                    };

                    effects.extend(reactor::wrap_effects(
                        MainEvent::EventStreamServer,
                        self.event_stream_server
                            .handle_event(effect_builder, rng, event),
                    ));
                }
            }
            MetaBlock::Historical(historical_meta_block) => {
                for (transaction_hash, transaction_header, execution_result) in
                    historical_meta_block.execution_results.iter()
                {
                    let event = event_stream_server::Event::TransactionProcessed {
                        transaction_hash: *transaction_hash,
                        transaction_header: Box::new(transaction_header.clone()),
                        block_hash: *historical_meta_block.block.hash(),
                        execution_result: Box::new(execution_result.clone()),
                        messages: Vec::new(),
                    };
                    effects.extend(reactor::wrap_effects(
                        MainEvent::EventStreamServer,
                        self.event_stream_server
                            .handle_event(effect_builder, rng, event),
                    ));
                }
            }
        }

        debug!(
            "MetaBlock: notifying shutdown watcher: {} {}",
            meta_block.height(),
            meta_block.hash(),
        );
        effects.extend(reactor::wrap_effects(
            MainEvent::ShutdownTrigger,
            self.shutdown_trigger.handle_event(
                effect_builder,
                rng,
                shutdown_trigger::Event::CompletedBlock(CompletedBlockInfo::new(
                    meta_block.height(),
                    meta_block.era_id(),
                    meta_block.is_switch_block(),
                )),
            ),
        ));

        effects
    }

    fn update_meta_block_gossip_state(
        &mut self,
        effect_builder: EffectBuilder<MainEvent>,
        rng: &mut NodeRng,
        block_hash: &BlockHash,
        gossip_target: GossipTarget,
        state: &mut MetaBlockState,
        effects: &mut Effects<MainEvent>,
    ) {
        if state.register_as_gossiped().was_updated() {
            debug!(
                "notifying block gossiper to start gossiping for: {}",
                block_hash
            );
            effects.extend(reactor::wrap_effects(
                MainEvent::BlockGossiper,
                self.block_gossiper.handle_event(
                    effect_builder,
                    rng,
                    gossiper::Event::ItemReceived {
                        item_id: *block_hash,
                        source: Source::Ourself,
                        target: gossip_target,
                    },
                ),
            ));
        }
    }
}

// TEST ENABLEMENT -- used by integration tests elsewhere
#[cfg(test)]
impl MainReactor {
    pub(crate) fn consensus(&self) -> &EraSupervisor {
        &self.consensus
    }

    pub(crate) fn storage(&self) -> &Storage {
        &self.storage
    }

    pub(crate) fn contract_runtime(&self) -> &ContractRuntime {
        &self.contract_runtime
    }
}

#[cfg(test)]
impl NetworkedReactor for MainReactor {
    fn node_id(&self) -> crate::types::NodeId {
        self.net.node_id()
    }
}