ckb-verification 0.37.0

TODO(doc): crate description
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
use crate::contextual_block_verifier::{UncleVerifierContext, VerifyContext};
use crate::uncles_verifier::UnclesVerifier;
use crate::UnclesError;
use ckb_chain::{
    chain::{ChainController, ChainService},
    switch::Switch,
};
use ckb_chain_spec::consensus::Consensus;
use ckb_error::assert_error_eq;
use ckb_shared::shared::{Shared, SharedBuilder};
use ckb_store::{ChainDB, ChainStore};
use ckb_types::{
    core::{
        BlockBuilder, BlockNumber, BlockView, EpochExt, HeaderView, TransactionBuilder,
        TransactionView, UncleBlockView,
    },
    packed::{Byte32, CellInput, ProposalShortId, Script, UncleBlockVec},
    prelude::*,
};
use rand::random;
use std::sync::Arc;

fn gen_block(parent_header: &HeaderView, nonce: u128, epoch: &EpochExt) -> BlockView {
    let now = parent_header.timestamp() + 1;
    let number = parent_header.number() + 1;
    let cellbase = create_cellbase(number);
    BlockBuilder::default()
        .transaction(cellbase)
        .proposal(ProposalShortId::from_slice(&[1; 10]).unwrap())
        .parent_hash(parent_header.hash())
        .timestamp(now.pack())
        .epoch(epoch.number_with_fraction(number).pack())
        .number(number.pack())
        .compact_target(epoch.compact_target().pack())
        .nonce(nonce.pack())
        .build()
}

fn start_chain(consensus: Option<Consensus>) -> (ChainController, Shared) {
    let mut builder = SharedBuilder::default();
    if let Some(consensus) = consensus {
        builder = builder.consensus(consensus);
    }
    let (shared, table) = builder.build().unwrap();

    let chain_service = ChainService::new(shared.clone(), table);
    let chain_controller = chain_service.start::<&str>(None);
    (chain_controller, shared)
}

fn create_cellbase(number: BlockNumber) -> TransactionView {
    TransactionBuilder::default()
        .witness(Script::default().into_witness())
        .input(CellInput::new_cellbase_input(number))
        .output(Default::default())
        .output_data(Default::default())
        .build()
}

fn prepare() -> (Shared, Vec<BlockView>, Vec<BlockView>) {
    let faketime_file = faketime::millis_tempfile(0).expect("create faketime file");
    faketime::enable(&faketime_file);

    let mut consensus = Consensus::default();
    consensus.max_block_proposals_limit = 3;
    consensus.genesis_epoch_ext.set_length(10);

    let (chain_controller, shared) = start_chain(Some(consensus));

    let number = 20;
    let mut chain1: Vec<BlockView> = Vec::new();
    let mut chain2: Vec<BlockView> = Vec::new();

    faketime::write_millis(&faketime_file, 10).expect("write millis");

    let genesis = shared
        .store()
        .get_block_header(&shared.store().get_block_hash(0).unwrap())
        .unwrap();

    let mut parent = genesis.clone();
    for _ in 1..number {
        let snapshot = shared.snapshot();
        let parent_epoch = snapshot.get_block_epoch(&parent.hash()).unwrap();
        let epoch = snapshot
            .next_epoch_ext(shared.consensus(), &parent_epoch, &parent)
            .unwrap_or(parent_epoch);
        let new_block = gen_block(&parent, random(), &epoch);
        chain_controller
            .internal_process_block(Arc::new(new_block.clone()), Switch::DISABLE_ALL)
            .expect("process block ok");
        chain1.push(new_block.clone());
        parent = new_block.header();
    }

    parent = genesis;

    // if block_number < 11 { chain1 == chain2 } else { chain1 != chain2 }
    for i in 1..number {
        let snapshot = shared.snapshot();
        let parent_epoch = snapshot.get_block_epoch(&parent.hash()).unwrap();
        let epoch = snapshot
            .next_epoch_ext(shared.consensus(), &parent_epoch, &parent)
            .unwrap_or(parent_epoch);
        let new_block = if i > 10 {
            gen_block(&parent, random(), &epoch)
        } else {
            chain1[(i - 1) as usize].clone()
        };
        chain_controller
            .internal_process_block(Arc::new(new_block.clone()), Switch::DISABLE_ALL)
            .expect("process block ok");
        chain2.push(new_block.clone());
        parent = new_block.header();
    }

    // According to the first-received policy, chain1 is the main chain
    (shared, chain1, chain2)
}

fn dummy_context(shared: &Shared) -> VerifyContext<'_, ChainDB> {
    VerifyContext::new(shared.store(), shared.consensus())
}

fn epoch(shared: &Shared, chain: &[BlockView], index: usize) -> EpochExt {
    let snapshot = shared.snapshot();
    let parent_epoch = snapshot.get_block_epoch(&chain[index].hash()).unwrap();
    snapshot
        .next_epoch_ext(shared.consensus(), &parent_epoch, &chain[index].header())
        .unwrap_or(parent_epoch)
}

#[test]
fn test_invalid_uncle_hash_case1() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    // header has uncle_count is 1 but uncles_hash is not Byte32::one()
    // body has 1 uncles
    let block = chain1
        .last()
        .cloned()
        .unwrap()
        .as_advanced_builder()
        .uncle(chain2.last().cloned().unwrap().as_uncle())
        .build_unchecked();

    let epoch = epoch(&shared, &chain1, chain1.len() - 2);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);

    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::InvalidHash {
            expected: Byte32::zero(),
            actual: block.calc_uncles_hash(),
        },
    );
}

#[test]
fn test_invalid_uncle_hash_case2() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    // header has empty uncles, but the uncles hash is not matched
    let uncles: UncleBlockVec = vec![chain2.last().cloned().unwrap().data().as_uncle()].pack();
    let uncles_hash = uncles.calc_uncles_hash();
    let block = chain1
        .last()
        .cloned()
        .unwrap()
        .as_advanced_builder()
        .uncles_hash(uncles_hash.clone())
        .build_unchecked();

    let epoch = epoch(&shared, &chain1, chain1.len() - 2);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);

    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::InvalidHash {
            expected: uncles_hash,
            actual: Byte32::zero(),
        },
    );
}

// Uncle is ancestor block
#[test]
fn test_double_inclusion() {
    let (shared, chain1, _) = prepare();
    let dummy_context = dummy_context(&shared);

    let block_number = 7;
    let uncle_number = 2;

    let block = chain1[block_number]
        .to_owned()
        .as_advanced_builder()
        .uncle(chain1[uncle_number].to_owned().as_uncle())
        .build();

    let epoch = epoch(&shared, &chain1, block_number - 1);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);

    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::DoubleInclusion(block.uncles().get(0).unwrap().header().hash()),
    );
}

// Uncle.compact_target != block.compact_target
#[test]
fn test_invalid_target() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);
    let epoch = epoch(&shared, &chain1, 17);
    let invalid_target = epoch.compact_target() + 1;

    let uncle = chain2[16]
        .clone()
        .as_advanced_builder()
        .compact_target(invalid_target.pack())
        .build()
        .as_uncle();
    let block = chain2[18]
        .clone()
        .as_advanced_builder()
        .uncle(uncle)
        .build();

    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(verifier.verify().unwrap_err(), UnclesError::InvalidTarget);
}
// Uncle.epoch != block.epoch
#[test]
fn test_invalid_epoch() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    let block_number = shared.consensus().genesis_epoch_ext().length() as usize + 2; // epoch = 1
    let uncle_number = shared.consensus().genesis_epoch_ext().length() as usize - 2; // epoch = 0

    let uncle = chain2[uncle_number]
        .clone()
        .as_advanced_builder()
        .compact_target(chain1[block_number].compact_target().pack())
        .build()
        .as_uncle();
    let block = chain1[block_number]
        .clone()
        .as_advanced_builder()
        .uncle(uncle)
        .build();

    let epoch = epoch(&shared, &chain1, block_number - 1);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);

    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::InvalidDifficultyEpoch,
    );
}

// Uncle.number >= block.number
#[test]
fn test_invalid_number() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    let uncle = chain2[18].as_uncle();

    let block = chain1[17]
        .clone()
        .as_advanced_builder()
        .uncle(uncle)
        .header(chain1[17].header())
        .build();

    let epoch = epoch(&shared, &chain1, 16);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(verifier.verify().unwrap_err(), UnclesError::InvalidNumber);
}

// Uncle proposals_hash is invalid
#[test]
fn test_uncle_proposals_hash() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);
    let block_number = 17;

    let uncle = chain2[16]
        .to_owned()
        .as_advanced_builder()
        .parent_hash(chain1[15].hash())
        .proposal([1; 10].pack())
        .build_unchecked()
        .as_uncle();
    let block = chain1[18]
        .to_owned()
        .as_advanced_builder()
        .uncle(uncle)
        .build();

    let epoch = epoch(&shared, &chain1, block_number);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(verifier.verify().unwrap_err(), UnclesError::ProposalsHash);
}

// Uncle contains duplicated proposals
#[test]
fn test_uncle_duplicated_proposals() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    // All the blocks in chain2 had a proposal before: ProposalShortId::from_slice(&[1; 10]
    let uncle = chain2[6]
        .to_owned()
        .as_advanced_builder()
        .proposal([1; 10].pack())
        .build()
        .as_uncle();
    let block = chain1[8]
        .to_owned()
        .as_advanced_builder()
        .uncle(uncle)
        .build();

    let epoch = epoch(&shared, &chain2, 7);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::ProposalDuplicate,
    );
}

// Duplicated uncles
#[test]
fn test_duplicated_uncles() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    let uncle = chain2[10].as_uncle();
    let duplicated_uncles = vec![uncle.clone(), uncle];

    let block = chain1[12]
        .to_owned()
        .as_advanced_builder()
        .uncles(duplicated_uncles)
        .build();

    let epoch = epoch(&shared, &chain1, 11);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::Duplicate(block.uncles().get(1).unwrap().header().hash()),
    );
}

// Uncles count exceeds limit
#[test]
fn test_uncle_over_count() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    let max_uncles_num = shared.consensus().max_uncles_num();
    let mut uncles: Vec<UncleBlockView> = Vec::new();
    for _ in 0..=max_uncles_num {
        let uncle = chain2[10].clone().as_uncle();
        uncles.push(uncle);
    }
    let block = chain1[12]
        .clone()
        .as_advanced_builder()
        .uncles(uncles)
        .build();
    // uncle overcount

    let epoch = epoch(&shared, &chain1, 11);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::OverCount {
            max: max_uncles_num as u32,
            actual: max_uncles_num as u32 + 1,
        },
    );
}

#[test]
fn test_exceeded_maximum_proposals_limit() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    let uncle = chain2[6]
        .clone()
        .as_advanced_builder()
        .proposals(vec![
            ProposalShortId::from_slice(&[1; 10]).unwrap(),
            ProposalShortId::from_slice(&[2; 10]).unwrap(),
            ProposalShortId::from_slice(&[3; 10]).unwrap(),
            ProposalShortId::from_slice(&[4; 10]).unwrap(),
        ])
        .build()
        .as_uncle();

    let block = chain1[8].clone().as_advanced_builder().uncle(uncle).build();

    let epoch = epoch(&shared, &chain1, 7);
    let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
    let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
    assert_error_eq!(
        verifier.verify().unwrap_err(),
        UnclesError::ExceededMaximumProposalsLimit,
    );
}

#[test]
fn test_descendant_limit() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    {
        let uncle = chain2[16].clone().as_uncle();
        let block = chain1[18]
            .clone()
            .as_advanced_builder()
            .uncle(uncle)
            .build();

        let epoch = epoch(&shared, &chain1, 17);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
        assert_error_eq!(verifier.verify().unwrap_err(), UnclesError::DescendantLimit);
    }

    // embedded should be ok
    {
        let uncle1 = chain2[15]
            .clone()
            .as_advanced_builder()
            .parent_hash(chain1[14].hash())
            .build()
            .as_uncle();
        let uncle2 = chain2[16]
            .clone()
            .as_advanced_builder()
            .parent_hash(uncle1.hash())
            .build()
            .as_uncle();
        let block = chain1[18]
            .clone()
            .as_advanced_builder()
            .uncle(uncle1)
            .uncle(uncle2)
            .build();

        let epoch = epoch(&shared, &chain1, 17);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
        assert!(verifier.verify().is_ok());
    }
}

#[test]
fn test_descendant_continuity() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    {
        let uncle = chain2[16]
            .clone()
            .as_advanced_builder()
            .parent_hash(chain1[14].hash())
            .build()
            .as_uncle();
        let block = chain1[18]
            .clone()
            .as_advanced_builder()
            .uncle(uncle)
            .build();

        let epoch = epoch(&shared, &chain1, 17);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
        assert_error_eq!(verifier.verify().unwrap_err(), UnclesError::DescendantLimit);
    }
}

#[test]
fn test_ok() {
    let (shared, chain1, chain2) = prepare();
    let dummy_context = dummy_context(&shared);

    {
        let uncle = chain2[16]
            .clone()
            .as_advanced_builder()
            .parent_hash(chain1[15].hash())
            .build()
            .as_uncle();
        let block = chain1[18]
            .clone()
            .as_advanced_builder()
            .uncle(uncle)
            .build();

        let epoch = epoch(&shared, &chain1, 17);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
        assert!(verifier.verify().is_ok());
    }

    {
        let uncle = chain2[10].clone().as_uncle();
        let block = chain1[12]
            .clone()
            .as_advanced_builder()
            .uncle(uncle)
            .build();

        let epoch = epoch(&shared, &chain1, 11);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &block);
        assert!(verifier.verify().is_ok());
    }
}

#[test]
fn test_uncle_with_uncle_descendant() {
    let (_, chain1, chain2) = prepare();

    let mut consensus = Consensus::default();
    consensus.max_block_proposals_limit = 3;
    consensus.genesis_epoch_ext.set_length(10);
    let (controller, shared) = start_chain(Some(consensus));

    for block in &chain2 {
        controller
            .internal_process_block(Arc::new(block.clone()), Switch::DISABLE_ALL)
            .expect("process block ok");
    }

    let uncle10 = chain1[10].clone().as_uncle();
    let parent = chain2.last().cloned().unwrap().header();
    let epoch18 = epoch(&shared, &chain2, 18); // last index 18
    let block = gen_block(&parent, random(), &epoch18)
        .as_advanced_builder()
        .uncle(uncle10)
        .build();

    controller
        .internal_process_block(Arc::new(block.clone()), Switch::DISABLE_ALL)
        .expect("process block ok");

    {
        let parent = block.header();
        let uncle11 = chain1[11].clone().as_uncle();
        let epoch18 = epoch(&shared, &chain2, 18);
        let new_block = gen_block(&parent, random(), &epoch18)
            .as_advanced_builder()
            .uncle(uncle11)
            .build();

        let dummy_context = dummy_context(&shared);
        let uncle_verifier_context = UncleVerifierContext::new(&dummy_context, &epoch18);
        let verifier = UnclesVerifier::new(uncle_verifier_context, &new_block);
        assert!(verifier.verify().is_ok());
    }
}