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
use assert_matches::assert_matches;

use casper_types::{
    bytesrepr::ToBytes, execution::ExecutionResultV2, testing::TestRng, DeployHash,
    TestBlockBuilder,
};

use super::*;
use crate::{
    components::block_synchronizer::tests::test_utils::chunks_with_proof_from_data,
    types::BlockExecutionResultsOrChunkId,
};

const NUM_TEST_EXECUTION_RESULTS: u64 = 100000;

#[test]
fn execution_results_chunks_apply_correctly() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    // Create chunkable execution results
    let exec_results: Vec<ExecutionResult> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|_| ExecutionResult::from(ExecutionResultV2::random(rng)))
        .collect();
    let test_chunks = chunks_with_proof_from_data(&exec_results.to_bytes().unwrap());
    assert!(test_chunks.len() >= 3);

    // Start off with only one chunk applied
    let mut chunks: HashMap<u64, ChunkWithProof> = HashMap::new();
    let first_chunk = test_chunks.first_key_value().unwrap();
    let last_chunk = test_chunks.last_key_value().unwrap();
    chunks.insert(*first_chunk.0, first_chunk.1.clone());

    // Insert all the other chunks except the last; skip the first one since it should have been
    // added already
    for (index, chunk) in test_chunks.iter().take(test_chunks.len() - 1).skip(1) {
        let apply_result = apply_chunk(
            *block.hash(),
            ExecutionResultsChecksum::Uncheckable,
            chunks,
            chunk.clone(),
            None,
        );

        // Check the index of the next chunk that should be applied
        chunks = assert_matches!(apply_result, Ok(ApplyChunkOutcome::NeedNext{chunks, chunk_count, next}) => {
            assert_eq!(next, index + 1);
            assert_eq!(chunk_count as usize, test_chunks.len());
            chunks
        });
    }

    // Apply the last chunk, and expect to get back the execution results
    let apply_result = apply_chunk(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        chunks,
        last_chunk.1.clone(),
        None,
    );
    assert_matches!(apply_result, Ok(ApplyChunkOutcome::Complete{execution_results}) => {
        assert_eq!(execution_results, exec_results);
    });
}

#[test]
fn single_chunk_execution_results_dont_apply_other_chunks() {
    let rng = &mut TestRng::new();
    let test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES - 1]);
    assert_eq!(test_chunks.len(), 1);

    // We can't apply a chunk if the execution results are not chunked (only 1 chunk exists)
    // Expect an error in this case.
    let first_chunk = test_chunks.first_key_value().unwrap();

    let apply_result = apply_chunk(
        *TestBlockBuilder::new().build(rng).hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks.clone().into_iter().collect(),
        first_chunk.1.clone(),
        None,
    );

    assert_matches!(apply_result, Err(Error::InvalidChunkCount { .. }));
}

#[test]
fn execution_results_chunks_from_block_with_different_hash_are_not_applied() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);
    let test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES * 3]);

    // Start acquiring chunks
    let mut acquisition = ExecutionResultsAcquisition::new_acquiring(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks.clone().into_iter().take(1).collect(),
        3,
        1,
    );
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(test_chunks.last_key_value().unwrap().1.clone()),
    );
    acquisition = assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
        Ok((acq, Acceptance::NeededIt)) => acq
    );
    assert_matches!(acquisition, ExecutionResultsAcquisition::Acquiring { .. });

    // Applying execution results from other block should return an error
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *TestBlockBuilder::new().build(rng).hash(),
        ValueOrChunk::ChunkWithProof(test_chunks.first_key_value().unwrap().1.clone()),
    );
    assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
        Err(Error::BlockHashMismatch {expected, .. }) => assert_eq!(expected, *block.hash())
    );
}

#[test]
fn execution_results_chunks_from_trie_with_different_chunk_count_are_not_applied() {
    let rng = &mut TestRng::new();
    let test_chunks_1 = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES * 3]);
    assert_eq!(test_chunks_1.len(), 3);

    let test_chunks_2 = chunks_with_proof_from_data(&[1; ChunkWithProof::CHUNK_SIZE_BYTES * 2]);
    assert_eq!(test_chunks_2.len(), 2);

    // If chunk tries have different number of chunks we shouldn't attempt to apply the incoming
    // chunk and exit early
    let bad_chunk = test_chunks_2.first_key_value().unwrap();

    let apply_result = apply_chunk(
        *TestBlockBuilder::new().build(rng).hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks_1.into_iter().take(2).collect(),
        bad_chunk.1.clone(),
        Some(3),
    );

    assert_matches!(apply_result, Err(Error::ChunkCountMismatch {expected, actual, ..}) if expected == 3 && actual == 2);
}

#[test]
fn invalid_execution_results_from_applied_chunks_dont_deserialize() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    // Create some chunk data that cannot pe serialized into execution results
    let test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES * 2]);
    assert_eq!(test_chunks.len(), 2);
    let last_chunk = test_chunks.last_key_value().unwrap();

    // Expect that this data cannot be deserialized
    let apply_result = apply_chunk(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks.clone().into_iter().take(1).collect(),
        last_chunk.1.clone(),
        None,
    );
    assert_matches!(apply_result, Err(Error::FailedToDeserialize { .. }));
}

#[test]
fn cant_apply_chunk_from_different_exec_results_or_invalid_checksum() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    // Create valid execution results
    let valid_exec_results: Vec<ExecutionResult> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|_| ExecutionResult::from(ExecutionResultV2::random(rng)))
        .collect();
    let valid_test_chunks = chunks_with_proof_from_data(&valid_exec_results.to_bytes().unwrap());
    assert!(valid_test_chunks.len() >= 3);

    // Create some invalid chunks that are not part of the execution results we are building
    let invalid_test_chunks =
        chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES * 2]);
    assert_eq!(invalid_test_chunks.len(), 2);

    // Try to apply the invalid test chunks to the valid chunks and expect to fail since the
    // checksums for the proofs are different between the chunks.
    let apply_result = apply_chunk(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        valid_test_chunks.clone().into_iter().take(2).collect(),
        invalid_test_chunks.first_key_value().unwrap().1.clone(),
        None,
    );
    assert_matches!(apply_result, Err(Error::ChunksWithDifferentChecksum{block_hash: _, expected, actual}) => {
        assert_eq!(expected, valid_test_chunks.first_key_value().unwrap().1.proof().root_hash());
        assert_eq!(actual, invalid_test_chunks.first_key_value().unwrap().1.proof().root_hash());
    });

    // Same test but here we are explicitly specifying the execution results checksum that
    // should be checked.
    let apply_result = apply_chunk(
        *block.hash(),
        ExecutionResultsChecksum::Checkable(
            valid_test_chunks
                .first_key_value()
                .unwrap()
                .1
                .proof()
                .root_hash(),
        ),
        valid_test_chunks.clone().into_iter().take(2).collect(),
        invalid_test_chunks.first_key_value().unwrap().1.clone(),
        None,
    );
    assert_matches!(apply_result, Err(Error::ChecksumMismatch{block_hash: _, expected, actual}) => {
        assert_eq!(expected, valid_test_chunks.first_key_value().unwrap().1.proof().root_hash());
        assert_eq!(actual, invalid_test_chunks.first_key_value().unwrap().1.proof().root_hash());
    });
}

// Constructors for acquisition states used for testing and verifying generic properties of
// these states
impl ExecutionResultsAcquisition {
    fn new_needed(block_hash: BlockHash) -> Self {
        let acq = Self::Needed { block_hash };
        assert_eq!(acq.block_hash(), block_hash);
        assert!(!acq.is_checkable());
        assert_eq!(acq.needs_value_or_chunk(), None);
        acq
    }

    fn new_pending(block_hash: BlockHash, checksum: ExecutionResultsChecksum) -> Self {
        let acq = Self::Pending {
            block_hash,
            checksum,
        };
        assert_eq!(acq.block_hash(), block_hash);
        assert_eq!(acq.is_checkable(), checksum.is_checkable());
        assert_eq!(
            acq.needs_value_or_chunk(),
            Some((BlockExecutionResultsOrChunkId::new(block_hash), checksum))
        );
        acq
    }

    fn new_acquiring(
        block_hash: BlockHash,
        checksum: ExecutionResultsChecksum,
        chunks: HashMap<u64, ChunkWithProof>,
        chunk_count: u64,
        next: u64,
    ) -> Self {
        let acq = Self::Acquiring {
            block_hash,
            checksum,
            chunks,
            chunk_count,
            next,
        };
        assert_eq!(acq.block_hash(), block_hash);
        assert_eq!(acq.is_checkable(), checksum.is_checkable());
        assert_eq!(
            acq.needs_value_or_chunk(),
            Some((
                BlockExecutionResultsOrChunkId::new(block_hash).next_chunk(next),
                checksum
            ))
        );
        acq
    }

    fn new_complete(
        block_hash: BlockHash,
        checksum: ExecutionResultsChecksum,
        results: HashMap<TransactionHash, ExecutionResult>,
    ) -> Self {
        let acq = Self::Complete {
            block_hash,
            checksum,
            results,
        };
        assert_eq!(acq.block_hash(), block_hash);
        assert_eq!(acq.is_checkable(), checksum.is_checkable());
        assert_eq!(acq.needs_value_or_chunk(), None);
        acq
    }
}

#[test]
fn acquisition_needed_state_has_correct_transitions() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    let acquisition = ExecutionResultsAcquisition::new_needed(*block.hash());

    let exec_results_checksum = ExecutionResultsChecksum::Checkable(Digest::hash([0; 32]));
    assert_matches!(
        acquisition.clone().apply_checksum(exec_results_checksum),
        Ok(ExecutionResultsAcquisition::Pending{block_hash, checksum}) if block_hash == *block.hash() && checksum == exec_results_checksum
    );

    assert_matches!(
        acquisition.clone().apply_checksum(ExecutionResultsChecksum::Uncheckable),
        Ok(ExecutionResultsAcquisition::Pending{block_hash, checksum}) if block_hash == *block.hash() && checksum == ExecutionResultsChecksum::Uncheckable
    );

    let mut test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES]);
    assert_eq!(test_chunks.len(), 1);

    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(test_chunks.remove(&0).unwrap()),
    );
    assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
        Err(Error::AttemptToApplyDataWhenMissingChecksum { .. })
    );
}

#[test]
fn acquisition_pending_state_has_correct_transitions() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    let acquisition = ExecutionResultsAcquisition::new_pending(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
    );
    assert_matches!(
        acquisition
            .clone()
            .apply_checksum(ExecutionResultsChecksum::Uncheckable),
        Err(Error::InvalidAttemptToApplyChecksum { .. })
    );

    // Acquisition can transition from `Pending` to `Complete` if a value and deploy hashes are
    // applied
    let execution_results = vec![ExecutionResult::from(ExecutionResultV2::random(rng))];
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::new(execution_results, 0).unwrap(),
    );
    assert_matches!(
        acquisition
            .clone()
            .apply_block_execution_results_or_chunk(exec_result.clone(), vec![]),
        Err(Error::ExecutionResultToDeployHashLengthDiscrepancy { .. })
    );
    assert_matches!(
        acquisition.clone().apply_block_execution_results_or_chunk(
            exec_result,
            vec![DeployHash::new(Digest::hash([0; 32])).into()]
        ),
        Ok((
            ExecutionResultsAcquisition::Complete { .. },
            Acceptance::NeededIt
        ))
    );

    // Acquisition can transition from `Pending` to `Acquiring` if a single chunk is applied
    let exec_results: Vec<ExecutionResult> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|_| ExecutionResult::from(ExecutionResultV2::random(rng)))
        .collect();
    let test_chunks = chunks_with_proof_from_data(&exec_results.to_bytes().unwrap());
    assert!(test_chunks.len() >= 3);

    let first_chunk = test_chunks.first_key_value().unwrap().1;
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(first_chunk.clone()),
    );
    let transaction_hashes: Vec<TransactionHash> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|index| DeployHash::new(Digest::hash(index.to_bytes().unwrap())).into())
        .collect();
    assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, transaction_hashes),
        Ok((
            ExecutionResultsAcquisition::Acquiring { .. },
            Acceptance::NeededIt
        ))
    );
}

#[test]
fn acquisition_acquiring_state_has_correct_transitions() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    // Generate valid execution results that are chunkable
    let exec_results: Vec<ExecutionResult> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|_| ExecutionResult::from(ExecutionResultV2::random(rng)))
        .collect();
    let test_chunks = chunks_with_proof_from_data(&exec_results.to_bytes().unwrap());
    assert!(test_chunks.len() >= 3);

    let mut acquisition = ExecutionResultsAcquisition::new_acquiring(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks.clone().into_iter().take(1).collect(),
        test_chunks.len() as u64,
        1,
    );
    assert_matches!(
        acquisition
            .clone()
            .apply_checksum(ExecutionResultsChecksum::Uncheckable),
        Err(Error::InvalidAttemptToApplyChecksum { .. })
    );

    // Apply all chunks except the last and check if the acquisition state remains `Acquiring`
    for (_, chunk) in test_chunks.iter().take(test_chunks.len() - 1).skip(1) {
        let exec_result = BlockExecutionResultsOrChunk::new_from_value(
            *block.hash(),
            ValueOrChunk::ChunkWithProof(chunk.clone()),
        );
        acquisition = assert_matches!(
            acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
            Ok((acq, Acceptance::NeededIt)) => acq
        );
        assert_matches!(acquisition, ExecutionResultsAcquisition::Acquiring { .. });
    }

    // Now apply the last chunk and check if the acquisition completes
    let last_chunk = test_chunks.last_key_value().unwrap().1;
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(last_chunk.clone()),
    );
    let transaction_hashes: Vec<TransactionHash> = (0..NUM_TEST_EXECUTION_RESULTS)
        .map(|index| DeployHash::new(Digest::hash(index.to_bytes().unwrap())).into())
        .collect();
    acquisition = assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, transaction_hashes),
        Ok((acq, Acceptance::NeededIt)) => acq
    );
    assert_matches!(acquisition, ExecutionResultsAcquisition::Complete { .. });
}

#[test]
fn acquisition_acquiring_state_gets_overridden_by_value() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);
    let test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES * 3]);

    // Start acquiring chunks
    let mut acquisition = ExecutionResultsAcquisition::new_acquiring(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        test_chunks.clone().into_iter().take(1).collect(),
        3,
        1,
    );
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(test_chunks.last_key_value().unwrap().1.clone()),
    );
    acquisition = assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
        Ok((acq, Acceptance::NeededIt)) => acq
    );
    assert_matches!(acquisition, ExecutionResultsAcquisition::Acquiring { .. });

    // Assume we got a full execution result for this block.
    // Since we don't have a checksum for the execution results, we can't really determine which
    // data is the better one. We expect to overwrite the execution results chunks that
    // we previously acquired with this complete result.
    let execution_results = vec![ExecutionResult::from(ExecutionResultV2::random(rng))];
    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::new(execution_results, 0).unwrap(),
    );
    assert_matches!(
        acquisition
            .clone()
            .apply_block_execution_results_or_chunk(exec_result.clone(), vec![]),
        Err(Error::ExecutionResultToDeployHashLengthDiscrepancy { .. })
    );

    assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(
            exec_result,
            vec![DeployHash::new(Digest::hash([0; 32])).into()]
        ),
        Ok((
            ExecutionResultsAcquisition::Complete { .. },
            Acceptance::NeededIt
        ))
    );
}

#[test]
fn acquisition_complete_state_has_correct_transitions() {
    let rng = &mut TestRng::new();
    let block = TestBlockBuilder::new().build(rng);

    let acquisition = ExecutionResultsAcquisition::new_complete(
        *block.hash(),
        ExecutionResultsChecksum::Uncheckable,
        HashMap::new(),
    );

    let exec_results_checksum = ExecutionResultsChecksum::Checkable(Digest::hash([0; 32]));
    assert_matches!(
        acquisition.clone().apply_checksum(exec_results_checksum),
        Err(Error::InvalidAttemptToApplyChecksum { .. })
    );

    assert_matches!(
        acquisition
            .clone()
            .apply_checksum(ExecutionResultsChecksum::Uncheckable),
        Err(Error::InvalidAttemptToApplyChecksum { .. })
    );

    let mut test_chunks = chunks_with_proof_from_data(&[0; ChunkWithProof::CHUNK_SIZE_BYTES]);
    assert_eq!(test_chunks.len(), 1);

    let exec_result = BlockExecutionResultsOrChunk::new_from_value(
        *block.hash(),
        ValueOrChunk::ChunkWithProof(test_chunks.remove(&0).unwrap()),
    );
    assert_matches!(
        acquisition.apply_block_execution_results_or_chunk(exec_result, vec![]),
        Err(Error::AttemptToApplyDataAfterCompleted { .. })
    );
}