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
//! Request effects.
//!
//! Requests typically ask other components to perform a service and report back the result. See the
//! top-level module documentation for details.

use std::{
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    fmt::{self, Display, Formatter},
    sync::Arc,
};

use datasize::DataSize;
use hex_fmt::HexFmt;
use serde::Serialize;
use smallvec::SmallVec;
use static_assertions::const_assert;

use casper_binary_port::{
    ConsensusStatus, ConsensusValidatorChanges, LastProgress, NetworkName, RecordId, Uptime,
};
use casper_storage::{
    block_store::types::ApprovalsHashes,
    data_access_layer::{
        prefixed_values::{PrefixedValuesRequest, PrefixedValuesResult},
        tagged_values::{TaggedValuesRequest, TaggedValuesResult},
        AddressableEntityResult, BalanceRequest, BalanceResult, EntryPointExistsResult,
        EraValidatorsRequest, EraValidatorsResult, ExecutionResultsChecksumResult, PutTrieRequest,
        PutTrieResult, QueryRequest, QueryResult, SeigniorageRecipientsRequest,
        SeigniorageRecipientsResult, TrieRequest, TrieResult,
    },
    DbRawBytesSpec,
};
use casper_types::{
    execution::ExecutionResult, Approval, AvailableBlockRange, Block, BlockHash, BlockHeader,
    BlockSignatures, BlockSynchronizerStatus, BlockV2, ChainspecRawBytes, DeployHash, Digest,
    DisplayIter, EntityAddr, EraId, ExecutionInfo, FinalitySignature, FinalitySignatureId,
    HashAddr, NextUpgrade, ProtocolUpgradeConfig, PublicKey, TimeDiff, Timestamp, Transaction,
    TransactionHash, TransactionId, Transfer,
};

use super::{AutoClosingResponder, GossipTarget, Responder};
use crate::{
    components::{
        block_synchronizer::{
            GlobalStateSynchronizerError, GlobalStateSynchronizerResponse, TrieAccumulatorError,
            TrieAccumulatorResponse,
        },
        consensus::{ClContext, ProposedBlock},
        contract_runtime::SpeculativeExecutionResult,
        diagnostics_port::StopAtSpec,
        fetcher::{FetchItem, FetchResult},
        gossiper::GossipItem,
        network::NetworkInsights,
        transaction_acceptor,
    },
    contract_runtime::ExecutionPreState,
    reactor::main_reactor::ReactorState,
    types::{
        appendable_block::AppendableBlock, BlockExecutionResultsOrChunk,
        BlockExecutionResultsOrChunkId, BlockWithMetadata, ExecutableBlock, InvalidProposalError,
        LegacyDeploy, MetaBlockState, NodeId, StatusFeed, TransactionHeader,
    },
    utils::Source,
};

const _STORAGE_REQUEST_SIZE: usize = size_of::<StorageRequest>();
const_assert!(_STORAGE_REQUEST_SIZE < 129);

/// A metrics request.
#[derive(Debug)]
pub(crate) enum MetricsRequest {
    /// Render current node metrics as prometheus-formatted string.
    RenderNodeMetricsText {
        /// Responder returning the rendered metrics or `None`, if an internal error occurred.
        responder: Responder<Option<String>>,
    },
}

impl Display for MetricsRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            MetricsRequest::RenderNodeMetricsText { .. } => write!(formatter, "get metrics text"),
        }
    }
}

const _NETWORK_EVENT_SIZE: usize = size_of::<NetworkRequest<String>>();
const_assert!(_NETWORK_EVENT_SIZE < 105);

/// A networking request.
#[derive(Debug, Serialize)]
#[must_use]
pub(crate) enum NetworkRequest<P> {
    /// Send a message on the network to a specific peer.
    SendMessage {
        /// Message destination.
        dest: Box<NodeId>,
        /// Message payload.
        payload: Box<P>,
        /// If `true`, the responder will be called early after the message has been queued, not
        /// waiting until it has passed to the kernel.
        respond_after_queueing: bool,
        /// Responder to be called when the message has been *buffered for sending*.
        #[serde(skip_serializing)]
        auto_closing_responder: AutoClosingResponder<()>,
    },
    /// Send a message on the network to validator peers in the given era.
    ValidatorBroadcast {
        /// Message payload.
        payload: Box<P>,
        /// Era whose validators are recipients.
        era_id: EraId,
        /// Responder to be called when all messages are queued.
        #[serde(skip_serializing)]
        auto_closing_responder: AutoClosingResponder<()>,
    },
    /// Gossip a message to a random subset of peers.
    Gossip {
        /// Payload to gossip.
        payload: Box<P>,
        /// Type of peers that should receive the gossip message.
        gossip_target: GossipTarget,
        /// Number of peers to gossip to. This is an upper bound, otherwise best-effort.
        count: usize,
        /// Node IDs of nodes to exclude from gossiping to.
        #[serde(skip_serializing)]
        exclude: HashSet<NodeId>,
        /// Responder to be called when all messages are queued.
        #[serde(skip_serializing)]
        auto_closing_responder: AutoClosingResponder<HashSet<NodeId>>,
    },
}

impl<P> NetworkRequest<P> {
    /// Transform a network request by mapping the contained payload.
    ///
    /// This is a replacement for a `From` conversion that is not possible without specialization.
    pub(crate) fn map_payload<F, P2>(self, wrap_payload: F) -> NetworkRequest<P2>
    where
        F: FnOnce(P) -> P2,
    {
        match self {
            NetworkRequest::SendMessage {
                dest,
                payload,
                respond_after_queueing,
                auto_closing_responder,
            } => NetworkRequest::SendMessage {
                dest,
                payload: Box::new(wrap_payload(*payload)),
                respond_after_queueing,
                auto_closing_responder,
            },
            NetworkRequest::ValidatorBroadcast {
                payload,
                era_id,
                auto_closing_responder,
            } => NetworkRequest::ValidatorBroadcast {
                payload: Box::new(wrap_payload(*payload)),
                era_id,
                auto_closing_responder,
            },
            NetworkRequest::Gossip {
                payload,
                gossip_target,
                count,
                exclude,
                auto_closing_responder,
            } => NetworkRequest::Gossip {
                payload: Box::new(wrap_payload(*payload)),
                gossip_target,
                count,
                exclude,
                auto_closing_responder,
            },
        }
    }
}

impl<P> Display for NetworkRequest<P>
where
    P: Display,
{
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            NetworkRequest::SendMessage { dest, payload, .. } => {
                write!(formatter, "send to {}: {}", dest, payload)
            }
            NetworkRequest::ValidatorBroadcast { payload, .. } => {
                write!(formatter, "broadcast: {}", payload)
            }
            NetworkRequest::Gossip { payload, .. } => write!(formatter, "gossip: {}", payload),
        }
    }
}

/// A networking info request.
#[derive(Debug, Serialize)]
pub(crate) enum NetworkInfoRequest {
    /// Get incoming and outgoing peers.
    Peers {
        /// Responder to be called with all connected peers.
        /// Responds with a map from [NodeId]s to a socket address, represented as a string.
        responder: Responder<BTreeMap<NodeId, String>>,
    },
    /// Get up to `count` fully-connected peers in random order.
    FullyConnectedPeers {
        count: usize,
        /// Responder to be called with the peers.
        responder: Responder<Vec<NodeId>>,
    },
    /// Get detailed insights into the nodes networking.
    Insight {
        responder: Responder<NetworkInsights>,
    },
}

impl Display for NetworkInfoRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            NetworkInfoRequest::Peers { responder: _ } => {
                formatter.write_str("get peers-to-socket-address map")
            }
            NetworkInfoRequest::FullyConnectedPeers {
                count,
                responder: _,
            } => {
                write!(formatter, "get up to {} fully connected peers", count)
            }
            NetworkInfoRequest::Insight { responder: _ } => {
                formatter.write_str("get networking insights")
            }
        }
    }
}

/// A gossip request.
///
/// This request usually initiates gossiping process of the specified item. Note that the gossiper
/// will fetch the item itself, so only the ID is needed.
///
/// The responder will be called as soon as the gossiper has initiated the process.
// Note: This request should eventually entirely replace `ItemReceived`.
#[derive(Debug, Serialize)]
#[must_use]
pub(crate) struct BeginGossipRequest<T>
where
    T: GossipItem,
{
    pub(crate) item_id: T::Id,
    pub(crate) source: Source,
    pub(crate) target: GossipTarget,
    pub(crate) responder: Responder<()>,
}

impl<T> Display for BeginGossipRequest<T>
where
    T: GossipItem,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "begin gossip of {} from {}", self.item_id, self.source)
    }
}

#[derive(Debug, Serialize)]
/// A storage request.
pub(crate) enum StorageRequest {
    /// Store given block.
    PutBlock {
        /// Block to be stored.
        block: Arc<Block>,
        /// Responder to call with the result.  Returns true if the block was stored on this
        /// attempt or false if it was previously stored.
        responder: Responder<bool>,
    },
    /// Store the approvals hashes.
    PutApprovalsHashes {
        /// Approvals hashes to store.
        approvals_hashes: Box<ApprovalsHashes>,
        responder: Responder<bool>,
    },
    /// Store the block and approvals hashes.
    PutExecutedBlock {
        /// Block to be stored.
        block: Arc<BlockV2>,
        /// Approvals hashes to store.
        approvals_hashes: Box<ApprovalsHashes>,
        execution_results: HashMap<TransactionHash, ExecutionResult>,
        responder: Responder<bool>,
    },
    /// Retrieve block with given hash.
    GetBlock {
        /// Hash of block to be retrieved.
        block_hash: BlockHash,
        /// Responder to call with the result.  Returns `None` if the block doesn't exist in local
        /// storage.
        responder: Responder<Option<Block>>,
    },
    IsBlockStored {
        block_hash: BlockHash,
        responder: Responder<bool>,
    },
    /// Retrieve the approvals hashes.
    GetApprovalsHashes {
        /// Hash of the block for which to retrieve approvals hashes.
        block_hash: BlockHash,
        /// Responder to call with the result.  Returns `None` if the approvals hashes don't exist
        /// in local storage.
        responder: Responder<Option<ApprovalsHashes>>,
    },
    /// Retrieve the highest complete block.
    GetHighestCompleteBlock {
        /// Responder.
        responder: Responder<Option<Block>>,
    },
    /// Retrieve the highest complete block header.
    GetHighestCompleteBlockHeader {
        /// Responder.
        responder: Responder<Option<BlockHeader>>,
    },
    /// Retrieve the era IDs of the blocks in which the given transactions were executed.
    GetTransactionsEraIds {
        transaction_hashes: HashSet<TransactionHash>,
        responder: Responder<HashSet<EraId>>,
    },
    /// Retrieve block header with given hash.
    GetBlockHeader {
        /// Hash of block to get header of.
        block_hash: BlockHash,
        /// If true, only return `Some` if the block is in the available block range, i.e. the
        /// highest contiguous range of complete blocks.
        only_from_available_block_range: bool,
        /// Responder to call with the result.  Returns `None` if the block header doesn't exist in
        /// local storage.
        responder: Responder<Option<BlockHeader>>,
    },
    /// Retrieve block header with given hash.
    GetRawData {
        /// Which record to get.
        record_id: RecordId,
        /// bytesrepr serialized key.
        key: Vec<u8>,
        /// Responder to call with the result.  Returns `None` if the data doesn't exist in
        /// local storage.
        responder: Responder<Option<DbRawBytesSpec>>,
    },
    GetBlockHeaderByHeight {
        /// Height of block to get header of.
        block_height: u64,
        /// If true, only return `Some` if the block is in the available block range, i.e. the
        /// highest contiguous range of complete blocks.
        only_from_available_block_range: bool,
        /// Responder to call with the result.  Returns `None` if the block header doesn't exist in
        /// local storage.
        responder: Responder<Option<BlockHeader>>,
    },
    GetLatestSwitchBlockHeader {
        responder: Responder<Option<BlockHeader>>,
    },
    GetSwitchBlockHeaderByEra {
        /// Era ID for which to get the block header.
        era_id: EraId,
        /// Responder to call with the result.
        responder: Responder<Option<BlockHeader>>,
    },
    /// Retrieve all transfers in a block with given hash.
    GetBlockTransfers {
        /// Hash of block to get transfers of.
        block_hash: BlockHash,
        /// Responder to call with the result.  Returns `None` if the transfers do not exist in
        /// local storage under the block_hash provided.
        responder: Responder<Option<Vec<Transfer>>>,
    },
    PutTransaction {
        transaction: Arc<Transaction>,
        /// Returns `true` if the transaction was stored on this attempt or false if it was
        /// previously stored.
        responder: Responder<bool>,
    },
    /// Retrieve transaction with given hashes.
    GetTransactions {
        transaction_hashes: Vec<TransactionHash>,
        #[allow(clippy::type_complexity)]
        responder: Responder<SmallVec<[Option<(Transaction, Option<BTreeSet<Approval>>)>; 1]>>,
    },
    /// Retrieve legacy deploy with given hash.
    GetLegacyDeploy {
        deploy_hash: DeployHash,
        responder: Responder<Option<LegacyDeploy>>,
    },
    GetTransaction {
        transaction_id: TransactionId,
        responder: Responder<Option<Transaction>>,
    },
    IsTransactionStored {
        transaction_id: TransactionId,
        responder: Responder<bool>,
    },
    GetTransactionAndExecutionInfo {
        transaction_hash: TransactionHash,
        with_finalized_approvals: bool,
        responder: Responder<Option<(Transaction, Option<ExecutionInfo>)>>,
    },
    /// Store execution results for a set of transactions of a single block.
    ///
    /// Will return a fatal error if there are already execution results known for a specific
    /// transaction/block combination and a different result is inserted.
    ///
    /// Inserting the same transaction/block combination multiple times with the same execution
    /// results is not an error and will silently be ignored.
    PutExecutionResults {
        /// Hash of block.
        block_hash: Box<BlockHash>,
        block_height: u64,
        era_id: EraId,
        /// Mapping of transactions to execution results of the block.
        execution_results: HashMap<TransactionHash, ExecutionResult>,
        /// Responder to call when done storing.
        responder: Responder<()>,
    },
    GetExecutionResults {
        block_hash: BlockHash,
        responder: Responder<Option<Vec<(TransactionHash, TransactionHeader, ExecutionResult)>>>,
    },
    GetBlockExecutionResultsOrChunk {
        /// Request ID.
        id: BlockExecutionResultsOrChunkId,
        /// Responder to call with the execution results.
        /// None is returned when we don't have the block in the storage.
        responder: Responder<Option<BlockExecutionResultsOrChunk>>,
    },
    /// Retrieve a finality signature by block hash and public key.
    GetFinalitySignature {
        id: Box<FinalitySignatureId>,
        responder: Responder<Option<FinalitySignature>>,
    },
    IsFinalitySignatureStored {
        id: Box<FinalitySignatureId>,
        responder: Responder<bool>,
    },
    /// Retrieve block and its metadata at a given height.
    GetBlockAndMetadataByHeight {
        /// The height of the block.
        block_height: BlockHeight,
        /// Flag indicating whether storage should check the block availability before trying to
        /// retrieve it.
        only_from_available_block_range: bool,
        /// The responder to call with the results.
        responder: Responder<Option<BlockWithMetadata>>,
    },
    /// Get a single finality signature for a block hash.
    GetBlockSignature {
        /// The hash for the request.
        block_hash: BlockHash,
        /// The public key of the signer.
        public_key: Box<PublicKey>,
        /// Responder to call with the result.
        responder: Responder<Option<FinalitySignature>>,
    },
    /// Store finality signatures.
    PutBlockSignatures {
        /// Signatures that are to be stored.
        signatures: BlockSignatures,
        /// Responder to call with the result, if true then the signatures were successfully
        /// stored.
        responder: Responder<bool>,
    },
    PutFinalitySignature {
        signature: Box<FinalitySignature>,
        responder: Responder<bool>,
    },
    /// Store a block header.
    PutBlockHeader {
        /// Block header that is to be stored.
        block_header: Box<BlockHeader>,
        /// Responder to call with the result, if true then the block header was successfully
        /// stored.
        responder: Responder<bool>,
    },
    /// Retrieve the height range of fully available blocks (not just block headers). Returns
    /// `[u64::MAX, u64::MAX]` when there are no sequences.
    GetAvailableBlockRange {
        /// Responder to call with the result.
        responder: Responder<AvailableBlockRange>,
    },
    /// Store a set of finalized approvals for a specific transaction.
    StoreFinalizedApprovals {
        /// The transaction hash to store the finalized approvals for.
        transaction_hash: TransactionHash,
        /// The set of finalized approvals.
        finalized_approvals: BTreeSet<Approval>,
        /// Responder, responded to once the approvals are written.  If true, new approvals were
        /// written.
        responder: Responder<bool>,
    },
    /// Retrieve the height of the final block of the previous protocol version, if known.
    GetKeyBlockHeightForActivationPoint { responder: Responder<Option<u64>> },
    /// Retrieve the block utilization score.
    GetBlockUtilizationScore {
        /// The era id.
        era_id: EraId,
        /// The block height of the switch block
        block_height: u64,
        /// The utilization within the switch block.
        switch_block_utilization: u64,
        /// Responder, responded once the utilization for the era has been determined.
        responder: Responder<Option<(u64, u64)>>,
    },
}

impl Display for StorageRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            StorageRequest::PutBlock { block, .. } => {
                write!(formatter, "put {}", block)
            }
            StorageRequest::PutApprovalsHashes {
                approvals_hashes, ..
            } => {
                write!(formatter, "put {}", approvals_hashes)
            }
            StorageRequest::GetBlock { block_hash, .. } => {
                write!(formatter, "get block {}", block_hash)
            }
            StorageRequest::IsBlockStored { block_hash, .. } => {
                write!(formatter, "is block {} stored", block_hash)
            }
            StorageRequest::GetApprovalsHashes { block_hash, .. } => {
                write!(formatter, "get approvals hashes {}", block_hash)
            }
            StorageRequest::GetHighestCompleteBlock { .. } => {
                write!(formatter, "get highest complete block")
            }
            StorageRequest::GetHighestCompleteBlockHeader { .. } => {
                write!(formatter, "get highest complete block header")
            }
            StorageRequest::GetTransactionsEraIds {
                transaction_hashes, ..
            } => {
                write!(
                    formatter,
                    "get era ids for {} transactions",
                    transaction_hashes.len()
                )
            }
            StorageRequest::GetBlockHeader { block_hash, .. } => {
                write!(formatter, "get {}", block_hash)
            }
            StorageRequest::GetBlockHeaderByHeight { block_height, .. } => {
                write!(formatter, "get header for height {}", block_height)
            }
            StorageRequest::GetLatestSwitchBlockHeader { .. } => {
                write!(formatter, "get latest switch block header")
            }
            StorageRequest::GetSwitchBlockHeaderByEra { era_id, .. } => {
                write!(formatter, "get header for era {}", era_id)
            }
            StorageRequest::GetBlockTransfers { block_hash, .. } => {
                write!(formatter, "get transfers for {}", block_hash)
            }
            StorageRequest::PutTransaction { transaction, .. } => {
                write!(formatter, "put {}", transaction)
            }
            StorageRequest::GetTransactions {
                transaction_hashes, ..
            } => {
                write!(
                    formatter,
                    "get {}",
                    DisplayIter::new(transaction_hashes.iter())
                )
            }
            StorageRequest::GetLegacyDeploy { deploy_hash, .. } => {
                write!(formatter, "get legacy deploy {}", deploy_hash)
            }
            StorageRequest::GetTransaction { transaction_id, .. } => {
                write!(formatter, "get transaction {}", transaction_id)
            }
            StorageRequest::GetTransactionAndExecutionInfo {
                transaction_hash, ..
            } => {
                write!(
                    formatter,
                    "get transaction and exec info {}",
                    transaction_hash
                )
            }
            StorageRequest::IsTransactionStored { transaction_id, .. } => {
                write!(formatter, "is transaction {} stored", transaction_id)
            }
            StorageRequest::PutExecutionResults { block_hash, .. } => {
                write!(formatter, "put execution results for {}", block_hash)
            }
            StorageRequest::GetExecutionResults { block_hash, .. } => {
                write!(formatter, "get execution results for {}", block_hash)
            }
            StorageRequest::GetBlockExecutionResultsOrChunk { id, .. } => {
                write!(formatter, "get block execution results or chunk for {}", id)
            }
            StorageRequest::GetFinalitySignature { id, .. } => {
                write!(formatter, "get finality signature {}", id)
            }
            StorageRequest::IsFinalitySignatureStored { id, .. } => {
                write!(formatter, "is finality signature {} stored", id)
            }
            StorageRequest::GetBlockAndMetadataByHeight { block_height, .. } => {
                write!(
                    formatter,
                    "get block and metadata for block at height: {}",
                    block_height
                )
            }
            StorageRequest::GetBlockSignature {
                block_hash,
                public_key,
                ..
            } => {
                write!(
                    formatter,
                    "get finality signature for block hash {} from {}",
                    block_hash, public_key
                )
            }
            StorageRequest::PutBlockSignatures { .. } => {
                write!(formatter, "put finality signatures")
            }
            StorageRequest::PutFinalitySignature { .. } => {
                write!(formatter, "put finality signature")
            }
            StorageRequest::PutBlockHeader { block_header, .. } => {
                write!(formatter, "put block header: {}", block_header)
            }
            StorageRequest::GetAvailableBlockRange { .. } => {
                write!(formatter, "get available block range",)
            }
            StorageRequest::StoreFinalizedApprovals {
                transaction_hash, ..
            } => {
                write!(
                    formatter,
                    "finalized approvals for transaction {}",
                    transaction_hash
                )
            }
            StorageRequest::PutExecutedBlock { block, .. } => {
                write!(formatter, "put executed block {}", block.hash(),)
            }
            StorageRequest::GetKeyBlockHeightForActivationPoint { .. } => {
                write!(
                    formatter,
                    "get key block height for current activation point"
                )
            }
            StorageRequest::GetRawData {
                key,
                responder: _responder,
                record_id,
            } => {
                write!(formatter, "get raw data {}::{:?}", record_id, key)
            }
            StorageRequest::GetBlockUtilizationScore { era_id, .. } => {
                write!(formatter, "get utilization score for era {}", era_id)
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct MakeBlockExecutableRequest {
    /// Hash of the block to be made executable.
    pub block_hash: BlockHash,
    /// Responder with the executable block and it's transactions
    pub responder: Responder<Option<ExecutableBlock>>,
}

impl Display for MakeBlockExecutableRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "block made executable: {}", self.block_hash)
    }
}

/// A request to mark a block at a specific height completed.
///
/// A block is considered complete if
///
/// * the block header and the actual block are persisted in storage,
/// * all of its transactions are persisted in storage, and
/// * the global state root the block refers to has no missing dependencies locally.
#[derive(Debug, Serialize)]
pub(crate) struct MarkBlockCompletedRequest {
    pub block_height: u64,
    /// Responds `true` if the block was not previously marked complete.
    pub responder: Responder<bool>,
}

impl Display for MarkBlockCompletedRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "block completed: height {}", self.block_height)
    }
}

#[derive(DataSize, Debug, Serialize)]
pub(crate) enum TransactionBufferRequest {
    GetAppendableBlock {
        timestamp: Timestamp,
        era_id: EraId,
        request_expiry: Timestamp,
        responder: Responder<AppendableBlock>,
    },
}

impl Display for TransactionBufferRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            TransactionBufferRequest::GetAppendableBlock {
                timestamp,
                era_id,
                request_expiry,
                ..
            } => {
                write!(
                    formatter,
                    "request for appendable block at instant {} for era {} (expires at {})",
                    timestamp, era_id, request_expiry
                )
            }
        }
    }
}

/// Abstract REST request.
///
/// An REST request is an abstract request that does not concern itself with serialization or
/// transport.
#[derive(Debug)]
#[must_use]
pub(crate) enum RestRequest {
    /// Return string formatted status or `None` if an error occurred.
    Status {
        /// Responder to call with the result.
        responder: Responder<StatusFeed>,
    },
    /// Return string formatted, prometheus compatible metrics or `None` if an error occurred.
    Metrics {
        /// Responder to call with the result.
        responder: Responder<Option<String>>,
    },
}

impl Display for RestRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            RestRequest::Status { .. } => write!(formatter, "get status"),
            RestRequest::Metrics { .. } => write!(formatter, "get metrics"),
        }
    }
}

/// A contract runtime request.
#[derive(Debug, Serialize)]
#[must_use]
pub(crate) enum ContractRuntimeRequest {
    /// A request to enqueue a `ExecutableBlock` for execution.
    EnqueueBlockForExecution {
        /// A `ExecutableBlock` to enqueue.
        executable_block: ExecutableBlock,
        /// The key block height for the current protocol version's activation point.
        key_block_height_for_activation_point: u64,
        meta_block_state: MetaBlockState,
    },
    /// A query request.
    Query {
        /// Query request.
        #[serde(skip_serializing)]
        request: QueryRequest,
        /// Responder to call with the query result.
        responder: Responder<QueryResult>,
    },
    /// A query by prefix request.
    QueryByPrefix {
        /// Query by prefix request.
        #[serde(skip_serializing)]
        request: PrefixedValuesRequest,
        /// Responder to call with the query result.
        responder: Responder<PrefixedValuesResult>,
    },
    /// A balance request.
    GetBalance {
        /// Balance request.
        #[serde(skip_serializing)]
        request: BalanceRequest,
        /// Responder to call with the balance result.
        responder: Responder<BalanceResult>,
    },
    /// Returns validator weights.
    GetEraValidators {
        /// Get validators weights request.
        #[serde(skip_serializing)]
        request: EraValidatorsRequest,
        /// Responder to call with the result.
        responder: Responder<EraValidatorsResult>,
    },
    /// Returns the seigniorage recipients snapshot at the given state root hash.
    GetSeigniorageRecipients {
        /// Get seigniorage recipients request.
        #[serde(skip_serializing)]
        request: SeigniorageRecipientsRequest,
        /// Responder to call with the result.
        responder: Responder<SeigniorageRecipientsResult>,
    },
    /// Return all values at a given state root hash and given key tag.
    GetTaggedValues {
        /// Get tagged values request.
        #[serde(skip_serializing)]
        request: TaggedValuesRequest,
        /// Responder to call with the result.
        responder: Responder<TaggedValuesResult>,
    },
    /// Returns the value of the execution results checksum stored in the ChecksumRegistry for the
    /// given state root hash.
    GetExecutionResultsChecksum {
        state_root_hash: Digest,
        responder: Responder<ExecutionResultsChecksumResult>,
    },
    /// Returns an `AddressableEntity` if found under the given entity_addr.  If a legacy `Account`
    /// or contract exists under the given key, it will be migrated to an `AddressableEntity`
    /// and returned. However, global state is not altered and the migrated record does not
    /// actually exist.
    GetAddressableEntity {
        state_root_hash: Digest,
        entity_addr: EntityAddr,
        responder: Responder<AddressableEntityResult>,
    },
    /// Returns information if an entry point exists under the given state root hash and entry
    /// point key.
    GetEntryPointExists {
        state_root_hash: Digest,
        contract_hash: HashAddr,
        entry_point_name: String,
        responder: Responder<EntryPointExistsResult>,
    },
    /// Get a trie or chunk by its ID.
    GetTrie {
        /// A request for a trie element.
        #[serde(skip_serializing)]
        request: TrieRequest,
        /// Responder to call with the result.
        responder: Responder<TrieResult>,
    },
    /// Insert a trie into global storage
    PutTrie {
        /// A request to persist a trie element.
        #[serde(skip_serializing)]
        request: PutTrieRequest,
        /// Responder to call with the result. Contains the hash of the persisted trie.
        responder: Responder<PutTrieResult>,
    },
    /// Execute transaction without committing results
    SpeculativelyExecute {
        /// Pre-state.
        block_header: Box<BlockHeader>,
        /// Transaction to execute.
        transaction: Box<Transaction>,
        /// Results
        responder: Responder<SpeculativeExecutionResult>,
    },
    UpdateRuntimePrice(EraId, u8),
    GetEraGasPrice {
        era_id: EraId,
        responder: Responder<Option<u8>>,
    },
    DoProtocolUpgrade {
        protocol_upgrade_config: ProtocolUpgradeConfig,
        next_block_height: u64,
        parent_hash: BlockHash,
        parent_seed: Digest,
    },
    UpdatePreState {
        new_pre_state: ExecutionPreState,
    },
}

impl Display for ContractRuntimeRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ContractRuntimeRequest::EnqueueBlockForExecution {
                executable_block, ..
            } => {
                write!(formatter, "executable_block: {}", executable_block)
            }
            ContractRuntimeRequest::Query {
                request: query_request,
                ..
            } => {
                write!(formatter, "query request: {:?}", query_request)
            }
            ContractRuntimeRequest::QueryByPrefix { request, .. } => {
                write!(formatter, "query by prefix request: {:?}", request)
            }
            ContractRuntimeRequest::GetBalance {
                request: balance_request,
                ..
            } => write!(formatter, "balance request: {:?}", balance_request),
            ContractRuntimeRequest::GetEraValidators { request, .. } => {
                write!(formatter, "get era validators: {:?}", request)
            }
            ContractRuntimeRequest::GetSeigniorageRecipients { request, .. } => {
                write!(formatter, "get seigniorage recipients for {:?}", request)
            }
            ContractRuntimeRequest::GetTaggedValues {
                request: get_all_values_request,
                ..
            } => {
                write!(
                    formatter,
                    "get all values request: {:?}",
                    get_all_values_request
                )
            }
            ContractRuntimeRequest::GetExecutionResultsChecksum {
                state_root_hash, ..
            } => write!(
                formatter,
                "get execution results checksum under {}",
                state_root_hash
            ),
            ContractRuntimeRequest::GetAddressableEntity {
                state_root_hash,
                entity_addr,
                ..
            } => {
                write!(
                    formatter,
                    "get addressable_entity {} under {}",
                    entity_addr, state_root_hash
                )
            }
            ContractRuntimeRequest::GetTrie { request, .. } => {
                write!(formatter, "get trie: {:?}", request)
            }
            ContractRuntimeRequest::PutTrie { request, .. } => {
                write!(formatter, "trie: {:?}", request)
            }
            ContractRuntimeRequest::SpeculativelyExecute {
                transaction,
                block_header,
                ..
            } => {
                write!(
                    formatter,
                    "Execute {} on {}",
                    transaction.hash(),
                    block_header.state_root_hash()
                )
            }
            ContractRuntimeRequest::UpdateRuntimePrice(_, era_gas_price) => {
                write!(formatter, "updating price to {}", era_gas_price)
            }
            ContractRuntimeRequest::GetEraGasPrice { era_id, .. } => {
                write!(formatter, "Get gas price for era {}", era_id)
            }
            ContractRuntimeRequest::GetEntryPointExists {
                state_root_hash,
                contract_hash,
                entry_point_name,
                ..
            } => {
                let formatted_contract_hash = HexFmt(contract_hash);
                write!(
                    formatter,
                    "get entry point {}-{} under {}",
                    formatted_contract_hash, entry_point_name, state_root_hash
                )
            }
            ContractRuntimeRequest::DoProtocolUpgrade {
                protocol_upgrade_config,
                ..
            } => {
                write!(
                    formatter,
                    "execute protocol upgrade against config: {:?}",
                    protocol_upgrade_config
                )
            }
            ContractRuntimeRequest::UpdatePreState { new_pre_state } => {
                write!(
                    formatter,
                    "Updating contract runtimes execution prestate: {:?}",
                    new_pre_state
                )
            }
        }
    }
}

/// Fetcher related requests.
#[derive(Debug, Serialize)]
#[must_use]
pub(crate) struct FetcherRequest<T: FetchItem> {
    /// The ID of the item to be retrieved.
    pub(crate) id: T::Id,
    /// The peer id of the peer to be asked if the item is not held locally
    pub(crate) peer: NodeId,
    /// Metadata used during validation of the fetched item.
    pub(crate) validation_metadata: Box<T::ValidationMetadata>,
    /// Responder to call with the result.
    pub(crate) responder: Responder<FetchResult<T>>,
}

impl<T: FetchItem> Display for FetcherRequest<T> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "request item by id {}", self.id)
    }
}

/// TrieAccumulator related requests.
#[derive(Debug, Serialize, DataSize)]
#[must_use]
pub(crate) struct TrieAccumulatorRequest {
    /// The hash of the trie node.
    pub(crate) hash: Digest,
    /// The peers to try to fetch from.
    pub(crate) peers: Vec<NodeId>,
    /// Responder to call with the result.
    pub(crate) responder: Responder<Result<TrieAccumulatorResponse, TrieAccumulatorError>>,
}

impl Display for TrieAccumulatorRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "request trie by hash {}", self.hash)
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct SyncGlobalStateRequest {
    pub(crate) block_hash: BlockHash,
    pub(crate) state_root_hash: Digest,
    #[serde(skip)]
    pub(crate) responder:
        Responder<Result<GlobalStateSynchronizerResponse, GlobalStateSynchronizerError>>,
}

impl Display for SyncGlobalStateRequest {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "request to sync global state at {}",
            self.block_hash
        )
    }
}

/// A block validator request.
#[derive(Debug, DataSize)]
#[must_use]
pub(crate) struct BlockValidationRequest {
    /// The height of the proposed block in the chain.
    pub(crate) proposed_block_height: u64,
    /// The block to be validated.
    pub(crate) block: ProposedBlock<ClContext>,
    /// The sender of the block, which will be asked to provide all missing transactions.
    pub(crate) sender: NodeId,
    /// Responder to call with the result.
    ///
    /// Indicates whether validation was successful.
    pub(crate) responder: Responder<Result<(), Box<InvalidProposalError>>>,
}

impl Display for BlockValidationRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let BlockValidationRequest { block, sender, .. } = self;
        write!(f, "validate block {} from {}", block, sender)
    }
}

type BlockHeight = u64;

#[derive(DataSize, Debug)]
#[must_use]
/// Consensus component requests.
pub(crate) enum ConsensusRequest {
    /// Request for our public key, and if we're a validator, the next round length.
    Status(Responder<Option<ConsensusStatus>>),
    /// Request for a list of validator status changes, by public key.
    ValidatorChanges(Responder<ConsensusValidatorChanges>),
}

/// ChainspecLoader component requests.
#[derive(Debug, Serialize)]
pub(crate) enum ChainspecRawBytesRequest {
    /// Request for the chainspec file bytes with the genesis_accounts and global_state bytes, if
    /// they are present.
    GetChainspecRawBytes(Responder<Arc<ChainspecRawBytes>>),
}

impl Display for ChainspecRawBytesRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ChainspecRawBytesRequest::GetChainspecRawBytes(_) => {
                write!(f, "get chainspec raw bytes")
            }
        }
    }
}

/// UpgradeWatcher component request to get the next scheduled upgrade, if any.
#[derive(Debug, Serialize)]
pub(crate) struct UpgradeWatcherRequest(pub(crate) Responder<Option<NextUpgrade>>);

impl Display for UpgradeWatcherRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "get next upgrade")
    }
}

#[derive(Debug, Serialize)]
pub(crate) enum ReactorInfoRequest {
    ReactorState { responder: Responder<ReactorState> },
    LastProgress { responder: Responder<LastProgress> },
    Uptime { responder: Responder<Uptime> },
    NetworkName { responder: Responder<NetworkName> },
    BalanceHoldsInterval { responder: Responder<TimeDiff> },
}

impl Display for ReactorInfoRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "get reactor status: {}",
            match self {
                ReactorInfoRequest::ReactorState { .. } => "ReactorState",
                ReactorInfoRequest::LastProgress { .. } => "LastProgress",
                ReactorInfoRequest::Uptime { .. } => "Uptime",
                ReactorInfoRequest::NetworkName { .. } => "NetworkName",
                ReactorInfoRequest::BalanceHoldsInterval { .. } => "BalanceHoldsInterval",
            }
        )
    }
}

#[derive(Debug, Serialize)]
#[allow(clippy::enum_variant_names)]
pub(crate) enum BlockAccumulatorRequest {
    GetPeersForBlock {
        block_hash: BlockHash,
        responder: Responder<Option<Vec<NodeId>>>,
    },
}

impl Display for BlockAccumulatorRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            BlockAccumulatorRequest::GetPeersForBlock { block_hash, .. } => {
                write!(f, "get peers for {}", block_hash)
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) enum BlockSynchronizerRequest {
    NeedNext,
    DishonestPeers,
    SyncGlobalStates(Vec<(BlockHash, Digest)>),
    Status {
        responder: Responder<BlockSynchronizerStatus>,
    },
}

impl Display for BlockSynchronizerRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            BlockSynchronizerRequest::NeedNext => {
                write!(f, "block synchronizer request: need next")
            }
            BlockSynchronizerRequest::DishonestPeers => {
                write!(f, "block synchronizer request: dishonest peers")
            }
            BlockSynchronizerRequest::Status { .. } => {
                write!(f, "block synchronizer request: status")
            }
            BlockSynchronizerRequest::SyncGlobalStates(_) => {
                write!(f, "request to sync global states")
            }
        }
    }
}

/// A request to set the current shutdown trigger.
#[derive(DataSize, Debug, Serialize)]
pub(crate) struct SetNodeStopRequest {
    /// The specific stop-at spec.
    ///
    /// If `None`, clears the current stop at setting.
    pub(crate) stop_at: Option<StopAtSpec>,
    /// Responder to send the previously set stop-at spec to, if any.
    pub(crate) responder: Responder<Option<StopAtSpec>>,
}

impl Display for SetNodeStopRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.stop_at {
            None => f.write_str("clear node stop"),
            Some(stop_at) => write!(f, "set node stop to: {}", stop_at),
        }
    }
}

/// A request to accept a new transaction.
#[derive(DataSize, Debug, Serialize)]
pub(crate) struct AcceptTransactionRequest {
    pub(crate) transaction: Transaction,
    pub(crate) is_speculative: bool,
    pub(crate) responder: Responder<Result<(), transaction_acceptor::Error>>,
}

impl Display for AcceptTransactionRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "accept transaction {} is_speculative: {}",
            self.transaction.hash(),
            self.is_speculative
        )
    }
}