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
//! Announcement effects.
//!
//! Announcements indicate new incoming data or events from various sources. See the top-level
//! module documentation for details.

use std::{
    collections::BTreeMap,
    fmt::{self, Debug, Display, Formatter},
    fs::File,
    sync::Arc,
};

use datasize::DataSize;
use itertools::Itertools;
use serde::Serialize;

use casper_types::{
    execution::Effects, Block, EraId, FinalitySignature, FinalitySignatureV2, NextUpgrade,
    PublicKey, Timestamp, Transaction, TransactionHash, U512,
};

use crate::{
    components::{
        consensus::{ClContext, ProposedBlock},
        diagnostics_port::FileSerializer,
        fetcher::FetchItem,
        gossiper::GossipItem,
        network::blocklist::BlocklistJustification,
    },
    effect::Responder,
    failpoints::FailpointActivation,
    types::{FinalizedBlock, MetaBlock, NodeId},
    utils::Source,
};

/// Control announcements are special announcements handled directly by the runtime/runner.
///
/// Reactors are never passed control announcements back in and every reactor event must be able to
/// be constructed from a `ControlAnnouncement` to be run.
///
/// Control announcements also use a priority queue to ensure that a component that reports a fatal
/// error is given as few follow-up events as possible. However, there currently is no guarantee
/// that this happens.
#[derive(Serialize)]
#[must_use]
pub(crate) enum ControlAnnouncement {
    /// A shutdown has been requested by the user.
    ShutdownDueToUserRequest,

    /// The node should shut down with exit code 0 in readiness for the next binary to start.
    ShutdownForUpgrade,

    /// The node started in catch up and shutdown mode has caught up to tip and can now exit.
    ShutdownAfterCatchingUp,

    /// The component has encountered a fatal error and cannot continue.
    ///
    /// This usually triggers a shutdown of the application.
    FatalError {
        file: &'static str,
        line: u32,
        msg: String,
    },
    /// An external event queue dump has been requested.
    QueueDumpRequest {
        /// The format to dump the queue in.
        #[serde(skip)]
        dump_format: QueueDumpFormat,
        /// Responder called when the dump has been finished.
        finished: Responder<()>,
    },
    /// Activates/deactivates a failpoint.
    ActivateFailpoint {
        /// The failpoint activation to process.
        activation: FailpointActivation,
    },
}

impl Debug for ControlAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ControlAnnouncement::ShutdownDueToUserRequest => write!(f, "ShutdownDueToUserRequest"),
            ControlAnnouncement::ShutdownForUpgrade => write!(f, "ShutdownForUpgrade"),
            ControlAnnouncement::ShutdownAfterCatchingUp => write!(f, "ShutdownAfterCatchingUp"),
            ControlAnnouncement::FatalError { file, line, msg } => f
                .debug_struct("FatalError")
                .field("file", file)
                .field("line", line)
                .field("msg", msg)
                .finish(),
            ControlAnnouncement::QueueDumpRequest { .. } => {
                f.debug_struct("QueueDump").finish_non_exhaustive()
            }
            ControlAnnouncement::ActivateFailpoint { activation } => f
                .debug_struct("ActivateFailpoint")
                .field("activation", activation)
                .finish(),
        }
    }
}

impl Display for ControlAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ControlAnnouncement::ShutdownDueToUserRequest => {
                write!(f, "shutdown due to user request")
            }
            ControlAnnouncement::ShutdownForUpgrade => write!(f, "shutdown for upgrade"),
            ControlAnnouncement::ShutdownAfterCatchingUp => write!(f, "shutdown after catching up"),
            ControlAnnouncement::FatalError { file, line, msg } => {
                write!(f, "fatal error [{}:{}]: {}", file, line, msg)
            }
            ControlAnnouncement::QueueDumpRequest { .. } => {
                write!(f, "dump event queue")
            }
            ControlAnnouncement::ActivateFailpoint { activation } => {
                write!(f, "failpoint activation: {}", activation)
            }
        }
    }
}

/// A component has encountered a fatal error and cannot continue.
///
/// This usually triggers a shutdown of the application.
#[derive(Serialize, Debug)]
#[must_use]
pub(crate) struct FatalAnnouncement {
    pub(crate) file: &'static str,
    pub(crate) line: u32,
    pub(crate) msg: String,
}

impl Display for FatalAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "fatal error [{}:{}]: {}", self.file, self.line, self.msg)
    }
}

#[derive(DataSize, Serialize, Debug)]
pub(crate) struct MetaBlockAnnouncement(pub(crate) MetaBlock);

impl Display for MetaBlockAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "announcement for meta block {} at height {}",
            self.0.hash(),
            self.0.height(),
        )
    }
}

#[derive(DataSize, Serialize, Debug)]
pub(crate) struct UnexecutedBlockAnnouncement(pub(crate) u64);

impl Display for UnexecutedBlockAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "announcement for unexecuted finalized block at height {}",
            self.0,
        )
    }
}

/// Queue dump format with handler.
#[derive(Serialize)]
pub(crate) enum QueueDumpFormat {
    /// Dump using given serde serializer.
    Serde(#[serde(skip)] FileSerializer),
    /// Dump writing debug output to file.
    Debug(#[serde(skip)] File),
}

impl QueueDumpFormat {
    /// Creates a new queue dump serde format.
    pub(crate) fn serde(serializer: FileSerializer) -> Self {
        QueueDumpFormat::Serde(serializer)
    }

    /// Creates a new queue dump debug format.
    pub(crate) fn debug(file: File) -> Self {
        QueueDumpFormat::Debug(file)
    }
}

/// A `TransactionAcceptor` announcement.
#[derive(Debug, Serialize)]
pub(crate) enum TransactionAcceptorAnnouncement {
    /// A transaction which wasn't previously stored on this node has been accepted and stored.
    AcceptedNewTransaction {
        /// The new transaction.
        transaction: Arc<Transaction>,
        /// The source (peer or client) of the transaction.
        source: Source,
    },

    /// An invalid transaction was received.
    InvalidTransaction {
        /// The invalid transaction.
        transaction: Transaction,
        /// The source (peer or client) of the transaction.
        source: Source,
    },
}

impl Display for TransactionAcceptorAnnouncement {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            TransactionAcceptorAnnouncement::AcceptedNewTransaction {
                transaction,
                source,
            } => write!(
                formatter,
                "accepted new transaction {} from {}",
                transaction.hash(),
                source
            ),
            TransactionAcceptorAnnouncement::InvalidTransaction {
                transaction,
                source,
            } => {
                write!(
                    formatter,
                    "invalid transaction {} from {}",
                    transaction.hash(),
                    source
                )
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) enum TransactionBufferAnnouncement {
    /// Hashes of the transactions that expired.
    TransactionsExpired(Vec<TransactionHash>),
}

impl Display for TransactionBufferAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            TransactionBufferAnnouncement::TransactionsExpired(hashes) => {
                write!(f, "pruned hashes: {}", hashes.iter().join(", "))
            }
        }
    }
}

/// A consensus announcement.
#[derive(Debug)]
pub(crate) enum ConsensusAnnouncement {
    /// A block was proposed.
    Proposed(Box<ProposedBlock<ClContext>>),
    /// A block was finalized.
    Finalized(Box<FinalizedBlock>),
    /// An equivocation has been detected.
    Fault {
        /// The Id of the era in which the equivocation was detected
        era_id: EraId,
        /// The public key of the equivocator.
        public_key: Box<PublicKey>,
        /// The timestamp when the evidence of the equivocation was detected.
        timestamp: Timestamp,
    },
}

impl Display for ConsensusAnnouncement {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ConsensusAnnouncement::Proposed(block) => {
                write!(formatter, "proposed block payload {}", block)
            }
            ConsensusAnnouncement::Finalized(block) => {
                write!(formatter, "finalized block payload {}", block)
            }
            ConsensusAnnouncement::Fault {
                era_id,
                public_key,
                timestamp,
            } => write!(
                formatter,
                "Validator fault with public key: {} has been identified at time: {} in {}",
                public_key, timestamp, era_id,
            ),
        }
    }
}

/// Notable / unexpected peer behavior has been detected by some part of the system.
#[derive(Debug, Serialize)]
pub(crate) enum PeerBehaviorAnnouncement {
    /// A given peer committed a blockable offense.
    OffenseCommitted {
        /// The peer ID of the offending node.
        offender: Box<NodeId>,
        /// Justification for blocking the peer.
        justification: Box<BlocklistJustification>,
    },
}

impl Display for PeerBehaviorAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            PeerBehaviorAnnouncement::OffenseCommitted {
                offender,
                justification,
            } => {
                write!(f, "peer {} committed offense: {}", offender, justification)
            }
        }
    }
}

/// A Gossiper announcement.
#[derive(Debug)]
pub(crate) enum GossiperAnnouncement<T: GossipItem> {
    /// A new gossip has been received, but not necessarily the full item.
    GossipReceived { item_id: T::Id, sender: NodeId },

    /// A new item has been received, where the item's ID is the complete item.
    NewCompleteItem(T::Id),

    /// A new item has been received where the item's ID is NOT the complete item.
    NewItemBody { item: Box<T>, sender: NodeId },

    /// Finished gossiping about the indicated item.
    FinishedGossiping(T::Id),
}

impl<T: GossipItem> Display for GossiperAnnouncement<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            GossiperAnnouncement::GossipReceived { item_id, sender } => {
                write!(f, "new gossiped item {} from sender {}", item_id, sender)
            }
            GossiperAnnouncement::NewCompleteItem(item) => write!(f, "new complete item {}", item),
            GossiperAnnouncement::NewItemBody { item, sender } => {
                write!(f, "new item body {} from {}", item.gossip_id(), sender)
            }
            GossiperAnnouncement::FinishedGossiping(item_id) => {
                write!(f, "finished gossiping {}", item_id)
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct UpgradeWatcherAnnouncement(pub(crate) Option<NextUpgrade>);

impl Display for UpgradeWatcherAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Some(next_upgrade) => write!(f, "read {}", next_upgrade),
            None => write!(f, "no upgrade staged"),
        }
    }
}

/// A ContractRuntime announcement.
#[derive(Debug, Serialize)]
pub(crate) enum ContractRuntimeAnnouncement {
    /// A step was committed successfully and has altered global state.
    CommitStepSuccess {
        /// The era id in which the step was committed to global state.
        era_id: EraId,
        /// The operations and transforms committed to global state.
        effects: Effects,
    },
    /// New era validators.
    UpcomingEraValidators {
        /// The era id in which the step was committed to global state.
        era_that_is_ending: EraId,
        /// The validators for the eras after the `era_that_is_ending` era.
        upcoming_era_validators: BTreeMap<EraId, BTreeMap<PublicKey, U512>>,
    },
    /// New gas price for an upcoming era has been determined.
    NextEraGasPrice {
        /// The era id for which the gas price has been determined
        era_id: EraId,
        /// The gas price as determined by chain utilization.
        next_era_gas_price: u8,
    },
}

impl Display for ContractRuntimeAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ContractRuntimeAnnouncement::CommitStepSuccess { era_id, .. } => {
                write!(f, "commit step completed for {}", era_id)
            }
            ContractRuntimeAnnouncement::UpcomingEraValidators {
                era_that_is_ending, ..
            } => {
                write!(
                    f,
                    "upcoming era validators after current {}.",
                    era_that_is_ending,
                )
            }
            ContractRuntimeAnnouncement::NextEraGasPrice {
                era_id,
                next_era_gas_price,
            } => {
                write!(
                    f,
                    "Calculated gas price {} for era {}",
                    next_era_gas_price, era_id
                )
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) enum BlockAccumulatorAnnouncement {
    /// A finality signature which wasn't previously stored on this node has been accepted and
    /// stored.
    AcceptedNewFinalitySignature {
        finality_signature: Box<FinalitySignatureV2>,
    },
}

impl Display for BlockAccumulatorAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            BlockAccumulatorAnnouncement::AcceptedNewFinalitySignature { finality_signature } => {
                write!(
                    f,
                    "finality signature {} accepted",
                    finality_signature.gossip_id()
                )
            }
        }
    }
}

/// A block which wasn't previously stored on this node has been fetched and stored.
#[derive(Debug, Serialize)]
pub(crate) struct FetchedNewBlockAnnouncement {
    pub(crate) block: Arc<Block>,
    pub(crate) peer: NodeId,
}

impl Display for FetchedNewBlockAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "new block {} fetched from {}",
            self.block.fetch_id(),
            self.peer
        )
    }
}

/// A finality signature which wasn't previously stored on this node has been fetched and stored.
#[derive(Debug, Serialize)]
pub(crate) struct FetchedNewFinalitySignatureAnnouncement {
    pub(crate) finality_signature: Box<FinalitySignature>,
    pub(crate) peer: NodeId,
}

impl Display for FetchedNewFinalitySignatureAnnouncement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "new finality signature {} fetched from {}",
            self.finality_signature.fetch_id(),
            self.peer
        )
    }
}