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
use std::{collections::BTreeMap, thread, time::Duration};

use num_rational::Ratio;

use casper_types::{
    testing::TestRng, ChainNameDigest, FinalitySignatureV2, TestBlockBuilder, Transaction,
};

use crate::components::consensus::tests::utils::{ALICE_PUBLIC_KEY, ALICE_SECRET_KEY};

use super::*;

#[test]
fn handle_acceptance_promotes_and_disqualifies_peers() {
    let mut rng = TestRng::new();
    let block = TestBlockBuilder::new().build(&mut rng);
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );

    let honest_peer = NodeId::random(&mut rng);
    let dishonest_peer = NodeId::random(&mut rng);

    // Builder acceptance for needed signature from ourselves.
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::NeededIt)), true)
        .is_ok());
    assert!(builder.peer_list().qualified_peers(&mut rng).is_empty());
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for existent signature from ourselves.
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::HadIt)), true)
        .is_ok());
    assert!(builder.peer_list().qualified_peers(&mut rng).is_empty());
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for no signature from ourselves.
    assert!(builder.handle_acceptance(None, Ok(None), true).is_ok());
    assert!(builder.peer_list().qualified_peers(&mut rng).is_empty());
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for no signature from a peer.
    // Peer shouldn't be registered.
    assert!(builder
        .handle_acceptance(Some(honest_peer), Ok(None), true)
        .is_ok());
    assert!(builder.peer_list().qualified_peers(&mut rng).is_empty());
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for existent signature from a peer.
    // Peer shouldn't be registered.
    assert!(builder
        .handle_acceptance(Some(honest_peer), Ok(Some(Acceptance::HadIt)), true)
        .is_ok());
    assert!(builder.peer_list().qualified_peers(&mut rng).is_empty());
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for needed signature from a peer.
    // Peer should be registered as honest.
    assert!(builder
        .handle_acceptance(Some(honest_peer), Ok(Some(Acceptance::NeededIt)), true)
        .is_ok());
    assert!(builder
        .peer_list()
        .qualified_peers(&mut rng)
        .contains(&honest_peer));
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for error on signature handling from ourselves.
    assert!(builder
        .handle_acceptance(
            None,
            Err(BlockAcquisitionError::InvalidStateTransition),
            true
        )
        .is_err());
    assert!(builder
        .peer_list()
        .qualified_peers(&mut rng)
        .contains(&honest_peer));
    assert!(builder.peer_list().dishonest_peers().is_empty());
    // Builder acceptance for error on signature handling from a peer.
    // Peer should be registered as dishonest.
    assert!(builder
        .handle_acceptance(
            Some(dishonest_peer),
            Err(BlockAcquisitionError::InvalidStateTransition),
            true
        )
        .is_err());
    assert!(builder
        .peer_list()
        .qualified_peers(&mut rng)
        .contains(&honest_peer));
    assert!(builder
        .peer_list()
        .dishonest_peers()
        .contains(&dishonest_peer));
}

#[test]
fn handle_acceptance_unlatches_builder() {
    let mut rng = TestRng::new();
    let block = TestBlockBuilder::new().build(&mut rng);
    let mut builder = BlockBuilder::new(
        block.header().block_hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );

    // Check that if a valid element was received, the latch is reset
    builder.latch_by(2);
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::NeededIt)), true)
        .is_ok());
    assert_eq!(builder.latch.count(), 0);
    builder.latch_by(2);
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::NeededIt)), false)
        .is_ok());
    assert_eq!(builder.latch.count(), 0);

    // Check that if a element that was previously received,
    // the latch is not decremented since this is a late response
    builder.latch_by(2);
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::HadIt)), true)
        .is_ok());
    assert_eq!(builder.latch.count(), 2);
    assert!(builder
        .handle_acceptance(None, Ok(Some(Acceptance::HadIt)), false)
        .is_ok());
    assert_eq!(builder.latch.count(), 2);

    // Check that the latch is decremented if a response lead to an error,
    // but only if the builder was waiting for that element in its current state
    assert!(builder
        .handle_acceptance(
            None,
            Err(BlockAcquisitionError::InvalidStateTransition),
            true
        )
        .is_err());
    assert_eq!(builder.latch.count(), 1);
    assert!(builder
        .handle_acceptance(
            None,
            Err(BlockAcquisitionError::InvalidStateTransition),
            false
        )
        .is_err());
    assert_eq!(builder.latch.count(), 1);

    // Check that the latch is decremented if a valid response was received that did not produce any
    // side effect, but only if the builder was waiting for that element in its current state
    builder.latch_by(1);
    assert!(builder.handle_acceptance(None, Ok(None), false).is_ok());
    assert_eq!(builder.latch.count(), 2);
    assert!(builder.handle_acceptance(None, Ok(None), true).is_ok());
    assert_eq!(builder.latch.count(), 1);
}

#[test]
fn register_era_validator_weights() {
    let mut rng = TestRng::new();
    let block = TestBlockBuilder::new().build(&mut rng);
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );
    let latest_timestamp = builder.last_progress;

    let mut validator_matrix = ValidatorMatrix::new_with_validator(ALICE_SECRET_KEY.clone());

    thread::sleep(Duration::from_millis(5));
    // Register default era (0). We have no information in the builder to
    // determine if these weights are relevant, so they shouldn't be stored.
    builder.register_era_validator_weights(&validator_matrix);
    assert!(builder.validator_weights.is_none());
    assert_eq!(latest_timestamp, builder.last_progress);
    // Set the era of the builder to 1000.
    builder.era_id = Some(EraId::from(1000));
    thread::sleep(Duration::from_millis(5));
    // Register the default era again. The builder is interested in weights
    // for era 1000, but the matrix has weights only for era 0, so they
    // shouldn't be registered.
    builder.register_era_validator_weights(&validator_matrix);
    assert!(builder.validator_weights.is_none());
    assert_eq!(latest_timestamp, builder.last_progress);
    // Set the era of the builder to the random block's era.
    builder.era_id = Some(block.era_id());
    // Add weights for that era to the validator matrix.
    let weights = EraValidatorWeights::new(
        block.era_id(),
        BTreeMap::from([(ALICE_PUBLIC_KEY.clone(), 100.into())]),
        Ratio::new(1, 3),
    );
    validator_matrix.register_era_validator_weights(weights.clone());
    thread::sleep(Duration::from_millis(5));
    // Register the random block's era weights. This should store the weights.
    builder.register_era_validator_weights(&validator_matrix);
    assert_eq!(builder.validator_weights.unwrap(), weights);
    assert_ne!(latest_timestamp, builder.last_progress);
}

#[test]
fn register_executable_block() {
    let mut rng = TestRng::new();
    let chain_name_hash = ChainNameDigest::random(&mut rng);
    // Create a random block.
    let block = TestBlockBuilder::new().build(&mut rng);
    // Create a builder for the block.
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );
    let mut latest_timestamp = builder.last_progress;
    // Create mock era weights for the block's era.
    let weights = EraValidatorWeights::new(
        block.era_id(),
        BTreeMap::from([(ALICE_PUBLIC_KEY.clone(), 100.into())]),
        Ratio::new(1, 3),
    );
    // Create a signature acquisition to fill.
    let mut signature_acquisition = SignatureAcquisition::new(
        vec![ALICE_PUBLIC_KEY.clone()],
        LegacyRequiredFinality::Strict,
    );
    let sig = FinalitySignatureV2::create(
        *block.hash(),
        block.height(),
        block.era_id(),
        chain_name_hash,
        &ALICE_SECRET_KEY,
    );
    assert_eq!(
        signature_acquisition.apply_signature(sig.into(), &weights),
        Acceptance::NeededIt
    );
    // Set the builder's state to `HaveStrictFinalitySignatures`.
    let expected_txns = vec![Transaction::random(&mut rng)];
    let executable_block =
        ExecutableBlock::from_block_and_transactions(block.clone(), expected_txns.clone());
    builder.acquisition_state = BlockAcquisitionState::HaveStrictFinalitySignatures(
        Box::new(block.clone().into()),
        signature_acquisition.clone(),
    );

    // Register the finalized block.
    thread::sleep(Duration::from_millis(5));
    builder.register_made_executable_block(executable_block.clone());
    match &builder.acquisition_state {
        BlockAcquisitionState::HaveExecutableBlock(actual_block, executable_block, enqueued) => {
            assert_eq!(actual_block.hash(), block.hash());
            assert_eq!(expected_txns, *executable_block.transactions);
            assert!(!enqueued);
        }
        _ => panic!("Unexpected outcome in registering finalized block"),
    }
    assert!(!builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
    latest_timestamp = builder.last_progress;

    // Make the builder historical.
    builder.should_fetch_execution_state = true;
    // Reset the state to `HaveStrictFinalitySignatures`.
    builder.acquisition_state = BlockAcquisitionState::HaveStrictFinalitySignatures(
        Box::new(block.into()),
        signature_acquisition.clone(),
    );
    // Register the finalized block. This should fail on historical builders.
    thread::sleep(Duration::from_millis(5));
    builder.register_made_executable_block(executable_block);
    assert!(builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
}

#[test]
fn register_block_execution() {
    let mut rng = TestRng::new();
    let chain_name_hash = ChainNameDigest::random(&mut rng);
    // Create a random block.
    let block = TestBlockBuilder::new().build(&mut rng);
    // Create a builder for the block.
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );
    let mut latest_timestamp = builder.last_progress;
    // Create mock era weights for the block's era.
    let weights = EraValidatorWeights::new(
        block.era_id(),
        BTreeMap::from([(ALICE_PUBLIC_KEY.clone(), 100.into())]),
        Ratio::new(1, 3),
    );
    // Create a signature acquisition to fill.
    let mut signature_acquisition = SignatureAcquisition::new(
        vec![ALICE_PUBLIC_KEY.clone()],
        LegacyRequiredFinality::Strict,
    );
    let sig = FinalitySignatureV2::create(
        *block.hash(),
        block.height(),
        block.era_id(),
        chain_name_hash,
        &ALICE_SECRET_KEY,
    );
    assert_eq!(
        signature_acquisition.apply_signature(sig.into(), &weights),
        Acceptance::NeededIt
    );

    let executable_block = Box::new(ExecutableBlock::from_block_and_transactions(
        block.clone(),
        vec![Transaction::random(&mut rng)],
    ));
    builder.acquisition_state =
        BlockAcquisitionState::HaveExecutableBlock(Box::new(block.into()), executable_block, false);

    assert_eq!(builder.execution_progress, ExecutionProgress::Idle);
    // Register the block execution enquement as successful. This should
    // advance the execution progress.
    thread::sleep(Duration::from_millis(5));
    builder.register_block_execution_enqueued();
    assert_eq!(builder.execution_progress, ExecutionProgress::Started);
    assert!(matches!(
        builder.acquisition_state,
        BlockAcquisitionState::HaveExecutableBlock(_, _, true)
    ));
    assert!(!builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
    latest_timestamp = builder.last_progress;

    // Attempt to register the block for execution again. The state shouldn't
    // change and the builder shouldn't fail.
    thread::sleep(Duration::from_millis(5));
    builder.register_block_execution_enqueued();
    assert_eq!(builder.execution_progress, ExecutionProgress::Started);
    assert!(matches!(
        builder.acquisition_state,
        BlockAcquisitionState::HaveExecutableBlock(_, _, true)
    ));
    assert!(!builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
    latest_timestamp = builder.last_progress;

    // Make the builder historical.
    builder.should_fetch_execution_state = true;
    // Register the block execution enquement as successful. This should put
    // the builder in a failed state as we shouldn't execute historical blocks.
    thread::sleep(Duration::from_millis(5));
    builder.register_block_execution_enqueued();
    assert!(builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
}

#[test]
fn register_block_executed() {
    let mut rng = TestRng::new();
    let chain_name_hash = ChainNameDigest::random(&mut rng);
    // Create a random block.
    let block = TestBlockBuilder::new().build(&mut rng);
    // Create a builder for the block.
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );
    let mut latest_timestamp = builder.last_progress;
    // Create mock era weights for the block's era.
    let weights = EraValidatorWeights::new(
        block.era_id(),
        BTreeMap::from([(ALICE_PUBLIC_KEY.clone(), 100.into())]),
        Ratio::new(1, 3),
    );
    // Create a signature acquisition to fill.
    let mut signature_acquisition = SignatureAcquisition::new(
        vec![ALICE_PUBLIC_KEY.clone()],
        LegacyRequiredFinality::Strict,
    );
    let sig = FinalitySignatureV2::create(
        *block.hash(),
        block.height(),
        block.era_id(),
        chain_name_hash,
        &ALICE_SECRET_KEY,
    );
    assert_eq!(
        signature_acquisition.apply_signature(sig.into(), &weights),
        Acceptance::NeededIt
    );
    // Set the builder state to `HaveStrictFinalitySignatures`.
    builder.acquisition_state = BlockAcquisitionState::HaveStrictFinalitySignatures(
        Box::new(block.into()),
        signature_acquisition,
    );
    // Mark execution as started.
    builder.execution_progress = ExecutionProgress::Started;

    thread::sleep(Duration::from_millis(5));
    // Register the block as executed. This should advance the execution
    // progress to `Done`.
    builder.register_block_executed();
    assert_eq!(builder.execution_progress, ExecutionProgress::Done);
    assert!(!builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
    latest_timestamp = builder.last_progress;

    thread::sleep(Duration::from_millis(5));
    // Register the block as executed again. This should not change the
    // builder's state.
    builder.register_block_executed();
    assert_eq!(builder.execution_progress, ExecutionProgress::Done);
    assert!(!builder.is_failed());
    assert_eq!(latest_timestamp, builder.last_progress);

    // Set the builder to be historical and register the block as executed
    // again. This should put the builder in the failed state.
    builder.should_fetch_execution_state = true;
    thread::sleep(Duration::from_millis(5));
    builder.register_block_executed();
    assert!(builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
}

#[test]
fn register_block_marked_complete() {
    let mut rng = TestRng::new();
    let chain_name_hash = ChainNameDigest::random(&mut rng);
    // Create a random block.
    let block = TestBlockBuilder::new().build(&mut rng);
    // Create a builder for the block.
    let mut builder = BlockBuilder::new(
        *block.hash(),
        false,
        1,
        TimeDiff::from_seconds(1),
        LegacyRequiredFinality::Strict,
        ProtocolVersion::V1_0_0,
    );
    // Make the builder historical.
    builder.should_fetch_execution_state = true;
    let mut latest_timestamp = builder.last_progress;
    // Create mock era weights for the block's era.
    let weights = EraValidatorWeights::new(
        block.era_id(),
        BTreeMap::from([(ALICE_PUBLIC_KEY.clone(), 100.into())]),
        Ratio::new(1, 3),
    );
    // Create a signature acquisition to fill.
    let mut signature_acquisition = SignatureAcquisition::new(
        vec![ALICE_PUBLIC_KEY.clone()],
        LegacyRequiredFinality::Strict,
    );
    let sig = FinalitySignatureV2::create(
        *block.hash(),
        block.height(),
        block.era_id(),
        chain_name_hash,
        &ALICE_SECRET_KEY,
    );
    assert_eq!(
        signature_acquisition.apply_signature(sig.into(), &weights),
        Acceptance::NeededIt
    );

    // Set the builder state to `HaveStrictFinalitySignatures`.
    builder.acquisition_state = BlockAcquisitionState::HaveStrictFinalitySignatures(
        Box::new(block.clone().into()),
        signature_acquisition.clone(),
    );
    // Register the block as marked complete. Since there are no missing
    // deploys, this should transition the builder state to
    // `HaveStrictFinalitySignatures`.
    thread::sleep(Duration::from_millis(5));
    builder.register_marked_complete();
    assert!(matches!(
        builder.acquisition_state,
        BlockAcquisitionState::Complete(..)
    ));
    assert!(!builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
    latest_timestamp = builder.last_progress;

    // Make this a forward builder.
    builder.should_fetch_execution_state = false;
    // Set the builder state to `HaveStrictFinalitySignatures`.
    builder.acquisition_state = BlockAcquisitionState::HaveStrictFinalitySignatures(
        Box::new(block.into()),
        signature_acquisition.clone(),
    );
    // Register the block as marked complete. In the forward flow we should
    // abort the builder as an attempt to mark the block complete is invalid.
    thread::sleep(Duration::from_millis(5));
    builder.register_marked_complete();
    assert!(builder.is_failed());
    assert_ne!(latest_timestamp, builder.last_progress);
}