fuel-core-importer 0.48.2

Fuel Block Importer
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
#![allow(non_snake_case)]

use crate::{
    Importer,
    importer::Error,
    ports::{
        BlockReconciliationWritePort,
        ImporterDatabase,
        MockBlockVerifier,
        MockDatabaseTransaction,
        MockValidator,
        Transactional,
    },
};
use anyhow::anyhow;
use fuel_core_storage::{
    Error as StorageError,
    MerkleRoot,
    Result as StorageResult,
    transactional::{
        Changes,
        StorageChanges,
    },
};
use fuel_core_types::{
    blockchain::{
        SealedBlock,
        block::Block,
        consensus::Consensus,
    },
    fuel_types::BlockHeight,
    services::{
        Uncommitted,
        block_importer::{
            ImportResult,
            UncommittedResult,
        },
        executor::{
            Error as ExecutorError,
            Result as ExecutorResult,
            UncommittedValidationResult,
            ValidationResult,
        },
    },
};
use std::sync::{
    Arc,
    Mutex,
};
use test_case::test_case;
use tokio::sync::{
    TryAcquireError,
    broadcast::error::TryRecvError,
};

mockall::mock! {
    pub Database {}

    impl Transactional for Database {
        type Transaction<'a> = MockDatabaseTransaction
        where
            Self: 'a;

        fn storage_transaction(&self, changes: Changes) -> MockDatabaseTransaction;
    }

    impl ImporterDatabase for Database {
        fn latest_block_height(&self) -> StorageResult<Option<BlockHeight>>;

        fn latest_block_root(&self) -> StorageResult<Option<MerkleRoot>>;

        fn commit_changes(
            &mut self,
            changes: StorageChanges,
        ) -> StorageResult<()>;
    }
}

#[derive(Clone)]
struct FakeBlockReconciliationWriter {
    publish_result: Result<(), String>,
    published_blocks: Arc<Mutex<Vec<SealedBlock>>>,
}

impl Default for FakeBlockReconciliationWriter {
    fn default() -> Self {
        Self {
            publish_result: Ok(()),
            published_blocks: Arc::new(Mutex::new(vec![])),
        }
    }
}

impl FakeBlockReconciliationWriter {
    fn with_error(error: impl Into<String>) -> Self {
        Self {
            publish_result: Err(error.into()),
            ..Default::default()
        }
    }

    fn published_blocks(&self) -> Vec<SealedBlock> {
        self.published_blocks.lock().unwrap().clone()
    }
}

impl BlockReconciliationWritePort for FakeBlockReconciliationWriter {
    fn publish_produced_block(&self, block: &SealedBlock) -> anyhow::Result<()> {
        self.published_blocks.lock().unwrap().push(block.clone());
        self.publish_result
            .as_ref()
            .map_err(|error| anyhow!(error.clone()))?;
        Ok(())
    }
}

fn u32_to_merkle_root(number: u32) -> MerkleRoot {
    let mut root = [0; 32];
    root[0..4].copy_from_slice(&number.to_be_bytes());
    MerkleRoot::from(root)
}

fn genesis(height: u32) -> SealedBlock {
    let mut block = Block::default();
    block.header_mut().set_block_height(height.into());
    block.header_mut().recalculate_metadata();

    SealedBlock {
        entity: block,
        consensus: Consensus::Genesis(Default::default()),
    }
}

fn poa_block(height: u32) -> SealedBlock {
    let mut block = Block::default();
    block.header_mut().set_block_height(height.into());
    block.header_mut().recalculate_metadata();

    SealedBlock {
        entity: block,
        consensus: Consensus::PoA(Default::default()),
    }
}

fn underlying_db<R>(result: R, commits: usize) -> impl Fn() -> MockDatabase
where
    R: Fn() -> StorageResult<Option<u32>> + Send + Clone + 'static,
{
    move || {
        let result_height = result.clone();
        let result_root = result.clone();
        let mut db = MockDatabase::default();
        db.expect_latest_block_height()
            .returning(move || result_height().map(|v| v.map(Into::into)));
        db.expect_latest_block_root()
            .returning(move || result_root().map(|v| v.map(u32_to_merkle_root)));
        db.expect_commit_changes()
            .times(commits)
            .returning(|_| Ok(()));
        db
    }
}

fn db_transaction<H, B>(
    height: H,
    store_block: B,
) -> impl Fn() -> MockDatabaseTransaction + Sync + Send + 'static + Clone
where
    H: Fn() -> StorageResult<Option<u32>> + Sync + Send + 'static + Clone,
    B: Fn() -> StorageResult<bool> + Sync + Send + 'static + Clone,
{
    move || {
        let height = height.clone();
        let store_block = store_block.clone();
        let mut db = MockDatabaseTransaction::default();
        db.expect_latest_block_root()
            .returning(move || height().map(|v| v.map(u32_to_merkle_root)));
        db.expect_store_new_block()
            .returning(move |_, _| store_block());
        db.expect_into_changes().returning(Changes::default);
        db
    }
}

fn ok<T: Clone, Err>(entity: T) -> impl Fn() -> Result<T, Err> + Clone {
    move || Ok(entity.clone())
}

fn storage_failure<T>() -> StorageResult<T> {
    Err(StorageError::Other(anyhow!("Some failure")))
}

fn storage_failure_error() -> Error {
    storage_failure::<()>().unwrap_err().into()
}

fn ex_result() -> ExecutorResult<UncommittedValidationResult<Changes>> {
    Ok(Uncommitted::new(
        ValidationResult {
            tx_status: vec![],
            events: vec![],
        },
        Default::default(),
    ))
}

fn execution_failure<T>() -> ExecutorResult<T> {
    Err(ExecutorError::BlockMismatch)
}

fn execution_failure_error() -> Error {
    Error::FailedExecution(ExecutorError::BlockMismatch)
}

fn executor<R>(result: R) -> MockValidator
where
    R: Fn() -> ExecutorResult<UncommittedValidationResult<Changes>> + Send + 'static,
{
    let mut executor = MockValidator::default();
    executor.expect_validate().return_once(move |_| result());

    executor
}

fn verification_failure<T>() -> anyhow::Result<T> {
    Err(anyhow!("Not verified"))
}

fn verification_failure_error() -> Error {
    Error::FailedVerification(verification_failure::<()>().unwrap_err())
}

fn verifier<R>(result: R) -> MockBlockVerifier
where
    R: Fn() -> anyhow::Result<()> + Send + 'static,
{
    let mut verifier = MockBlockVerifier::default();
    verifier
        .expect_verify_block_fields()
        .return_once(move |_, _| result());

    verifier
}

//////////////// SealedBlock, UnderlyingDB, ExecutionDB ///////////////
//////////////// //////////// Genesis Block /////////// ////////////////
#[test_case(
    genesis(0),
    underlying_db(ok(None), 1),
    db_transaction(ok(None), ok(true))
    => Ok(());
    "successfully imports genesis block when latest block not found"
)]
#[test_case(
    genesis(113),
    underlying_db(ok(None), 1),
    db_transaction(ok(None), ok(true))
    => Ok(());
    "successfully imports block at arbitrary height when executor db expects it and last block not found"
)]
#[test_case(
    genesis(0),
    underlying_db(storage_failure, 0),
    db_transaction(ok(Some(0)), ok(true))
    => Err(storage_failure_error());
    "fails to import genesis when underlying database fails"
)]
#[test_case(
    genesis(0),
    underlying_db(ok(Some(0)), 0),
    db_transaction(ok(Some(0)), ok(true))
    => Err(Error::InvalidUnderlyingDatabaseGenesisState);
    "fails to import genesis block when already exists"
)]
#[test_case(
    genesis(1),
    underlying_db(ok(None), 0),
    db_transaction(ok(Some(0)), ok(true))
    => Err(Error::InvalidDatabaseStateAfterExecution(None, Some(u32_to_merkle_root(0))));
    "fails to import genesis block when next height is not 0"
)]
#[test_case(
    genesis(0),
    underlying_db(ok(None), 0),
    db_transaction(ok(None), ok(false))
    => Err(Error::NotUnique(0u32.into()));
    "fails to import genesis block when block exists for height 0"
)]
#[tokio::test]
async fn commit_result_genesis(
    sealed_block: SealedBlock,
    underlying_db: impl Fn() -> MockDatabase,
    db_transaction: impl Fn() -> MockDatabaseTransaction + Sync + Send + 'static,
) -> Result<(), Error> {
    commit_result_assert(sealed_block, underlying_db(), db_transaction).await
}

//////////////////////////// PoA Block ////////////////////////////
#[test_case(
    poa_block(1),
    underlying_db(ok(Some(0)), 1),
    db_transaction(ok(Some(0)), ok(true))
    => Ok(());
    "successfully imports block at height 1 when latest block is genesis"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(112)), 1),
    db_transaction(ok(Some(112)), ok(true))
    => Ok(());
    "successfully imports block at arbitrary height when latest block height is one fewer and executor db expects it"
)]
#[test_case(
    poa_block(0),
    underlying_db(ok(Some(0)), 0),
    db_transaction(ok(Some(1)), ok(true))
    => Err(Error::ZeroNonGenericHeight);
    "fails to import PoA block with height 0"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(111)), 0),
    db_transaction(ok(Some(113)), ok(true))
    => Err(Error::IncorrectBlockHeight(112u32.into(), 113u32.into()));
    "fails to import block at height 113 when latest block height is 111"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(114)), 0),
    db_transaction(ok(Some(113)), ok(true))
    => Err(Error::IncorrectBlockHeight(115u32.into(), 113u32.into()));
    "fails to import block at height 113 when latest block height is 114"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(112)), 0),
    db_transaction(ok(Some(114)), ok(true))
    => Err(Error::InvalidDatabaseStateAfterExecution(Some(u32_to_merkle_root(112u32)), Some(u32_to_merkle_root(114u32))));
    "fails to import block 113 when executor db expects height 114"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(112)), 0),
    db_transaction(storage_failure, ok(true))
    => Err(storage_failure_error());
    "fails to import block when executor db fails to find latest block"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(112)), 0),
    db_transaction(ok(Some(112)), ok(false))
    => Err(Error::NotUnique(113u32.into()));
    "fails to import block when block exists"
)]
#[test_case(
    poa_block(113),
    underlying_db(ok(Some(112)), 0),
    db_transaction(ok(Some(112)), storage_failure)
    => Err(storage_failure_error());
    "fails to import block when executor db fails to find block"
)]
#[tokio::test]
async fn commit_result_and_execute_and_commit_poa<DbTransaction>(
    sealed_block: SealedBlock,
    underlying_db: impl Fn() -> MockDatabase,
    db_transaction: DbTransaction,
) -> Result<(), Error>
where
    DbTransaction: Sync + Send + 'static,
    DbTransaction: Fn() -> MockDatabaseTransaction,
    DbTransaction: Clone,
{
    // `execute_and_commit` and `commit_result` should have the same
    // validation rules(-> test cases) during committing the result.
    let db_transaction_1 = db_transaction.clone();
    let commit_result =
        commit_result_assert(sealed_block.clone(), underlying_db(), db_transaction_1)
            .await;
    let mut db = underlying_db();
    db.expect_storage_transaction()
        .returning(move |_| db_transaction());
    let execute_and_commit_result = execute_and_commit_assert(
        sealed_block,
        db,
        executor(ex_result),
        verifier(ok(())),
    )
    .await;
    assert_eq!(commit_result, execute_and_commit_result);
    commit_result
}

async fn commit_result_assert(
    sealed_block: SealedBlock,
    mut underlying_db: MockDatabase,
    db_transaction: impl Fn() -> MockDatabaseTransaction + Sync + Send + 'static,
) -> Result<(), Error> {
    underlying_db
        .expect_storage_transaction()
        .returning(move |_| db_transaction());
    let expected_to_broadcast = sealed_block.clone();
    let importer =
        Importer::default_config(underlying_db, executor(ex_result), verifier(ok(())));
    let uncommitted_result = UncommittedResult::new(
        ImportResult::new_from_local(sealed_block, vec![], vec![]),
        Default::default(),
    );

    let mut imported_blocks = importer.subscribe();
    let result = importer.commit_result(uncommitted_result).await;

    if result.is_ok() {
        let actual_sealed_block = imported_blocks.try_recv().unwrap();
        assert_eq!(actual_sealed_block.sealed_block, expected_to_broadcast);
        match imported_blocks.try_recv() {
            Err(err) => {
                assert_eq!(err, TryRecvError::Empty);
            }
            _ => {
                panic!("We should broadcast only one block");
            }
        }
    }

    result
}

async fn execute_and_commit_assert(
    sealed_block: SealedBlock,
    underlying_db: MockDatabase,
    executor: MockValidator,
    verifier: MockBlockVerifier,
) -> Result<(), Error> {
    let expected_to_broadcast = sealed_block.clone();
    let importer = Importer::default_config(underlying_db, executor, verifier);

    let mut imported_blocks = importer.subscribe();
    let result = importer.execute_and_commit(sealed_block).await;

    if result.is_ok() {
        let actual_sealed_block = imported_blocks.try_recv().unwrap();
        assert_eq!(actual_sealed_block.sealed_block, expected_to_broadcast);

        match imported_blocks.try_recv() {
            Err(err) => {
                assert_eq!(err, TryRecvError::Empty);
            }
            _ => {
                panic!("We should broadcast only one block");
            }
        }
    }

    result
}

#[tokio::test]
async fn commit_result_fail_when_locked() {
    let importer = Importer::default_config(
        MockDatabase::default(),
        executor(ex_result),
        verifier(ok(())),
    );
    let uncommitted_result =
        UncommittedResult::new(ImportResult::default(), Default::default());

    let _guard = importer.lock();
    assert_eq!(
        importer.commit_result(uncommitted_result).await,
        Err(Error::Semaphore(TryAcquireError::NoPermits))
    );
}

#[tokio::test]
async fn execute_and_commit_fail_when_locked() {
    let importer = Importer::default_config(
        MockDatabase::default(),
        MockValidator::default(),
        MockBlockVerifier::default(),
    );

    let _guard = importer.lock();
    assert_eq!(
        importer.execute_and_commit(Default::default()).await,
        Err(Error::Semaphore(TryAcquireError::NoPermits))
    );
}

#[tokio::test]
async fn commit_result__when_source_is_local_then_publishes_to_reconciliation_writer() {
    // given
    let sealed_block = poa_block(1);
    let mut database = underlying_db(ok(Some(0)), 1)();
    database
        .expect_storage_transaction()
        .returning(move |_| db_transaction(ok(Some(0)), ok(true))());
    let writer = FakeBlockReconciliationWriter::default();
    let writer_state = writer.clone();
    let importer = Importer::new(
        Default::default(),
        Default::default(),
        database,
        executor(ex_result),
        verifier(ok(())),
        writer,
    );
    let expected_published_block = sealed_block.clone();
    let uncommitted_result = UncommittedResult::new(
        ImportResult::new_from_local(sealed_block, vec![], vec![]),
        Default::default(),
    );

    // when
    let result = importer.commit_result(uncommitted_result).await;

    // then
    assert!(result.is_ok());
    assert_eq!(
        writer_state.published_blocks(),
        vec![expected_published_block]
    );
}

#[tokio::test]
async fn execute_and_commit__when_source_is_network_then_does_not_publish_to_reconciliation_writer()
 {
    // given
    let sealed_block = poa_block(1);
    let mut database = underlying_db(ok(Some(0)), 1)();
    database
        .expect_storage_transaction()
        .returning(move |_| db_transaction(ok(Some(0)), ok(true))());
    let writer = FakeBlockReconciliationWriter::default();
    let writer_state = writer.clone();
    let importer = Importer::new(
        Default::default(),
        Default::default(),
        database,
        executor(ex_result),
        verifier(ok(())),
        writer,
    );

    // when
    let result = importer.execute_and_commit(sealed_block).await;

    // then
    assert!(result.is_ok());
    assert_eq!(writer_state.published_blocks(), Vec::<SealedBlock>::new());
}

#[tokio::test]
async fn commit_result__when_publish_to_reconciliation_writer_fails_then_returns_error() {
    // given
    let sealed_block = poa_block(1);
    let mut database = underlying_db(ok(Some(0)), 0)();
    database
        .expect_storage_transaction()
        .returning(move |_| db_transaction(ok(Some(0)), ok(true))());
    let writer = FakeBlockReconciliationWriter::with_error("publish failure");
    let importer = Importer::new(
        Default::default(),
        Default::default(),
        database,
        executor(ex_result),
        verifier(ok(())),
        writer,
    );
    let uncommitted_result = UncommittedResult::new(
        ImportResult::new_from_local(sealed_block, vec![], vec![]),
        Default::default(),
    );

    // when
    let result = importer.commit_result(uncommitted_result).await;

    // then
    assert!(matches!(
        result,
        Err(Error::FailedBlockReconciliationWrite(_))
    ));
}

#[test]
fn one_lock_at_the_same_time() {
    let importer = Importer::default_config(
        MockDatabase::default(),
        MockValidator::default(),
        MockBlockVerifier::default(),
    );

    let _guard = importer.lock();
    assert_eq!(
        importer.lock().map(|_| ()),
        Err(Error::Semaphore(TryAcquireError::NoPermits))
    );
}

///////// New block, Block After Execution, Verification result, commits /////////
#[test_case(
    genesis(113), ex_result, ok(()), 0
    => Err(Error::ExecuteGenesis);
    "cannot execute genesis block"
)]
#[test_case(
    poa_block(1), ex_result, ok(()), 1
    => Ok(());
    "commits block 1"
)]
#[test_case(
    poa_block(113), ex_result, ok(()), 1
    => Ok(());
    "commits block 113"
)]
#[test_case(
    poa_block(113), execution_failure, ok(()), 0
    => Err(execution_failure_error());
    "commit fails if execution fails"
)]
#[test_case(
    poa_block(113), ex_result, verification_failure, 0
    => Err(verification_failure_error());
    "commit fails if verification fails"
)]
#[tokio::test]
async fn execute_and_commit_and_verify_and_execute_block_poa<V, P>(
    sealed_block: SealedBlock,
    block_after_execution: P,
    verifier_result: V,
    commits: usize,
) -> Result<(), Error>
where
    P: Fn() -> ExecutorResult<UncommittedValidationResult<Changes>>
        + Send
        + Clone
        + 'static,
    V: Fn() -> anyhow::Result<()> + Send + Clone + 'static,
{
    // `execute_and_commit` and `verify_and_execute_block` should have the same
    // validation rules(-> test cases) during verification.
    let verify_and_execute_result = verify_and_execute_assert(
        sealed_block.clone(),
        block_after_execution.clone(),
        verifier_result.clone(),
    )
    .await;

    // We tested commit part in the `commit_result_and_execute_and_commit_poa` so setup the
    // databases to always pass the committing part.
    let expected_height: u32 = (*sealed_block.entity.header().height()).into();
    let previous_height = expected_height.checked_sub(1).unwrap_or_default();
    let mut db = underlying_db(ok(Some(previous_height)), commits)();
    db.expect_storage_transaction()
        .returning(move |_| db_transaction(ok(Some(previous_height)), ok(true))());
    let execute_and_commit_result = execute_and_commit_assert(
        sealed_block,
        db,
        executor(block_after_execution),
        verifier(verifier_result),
    )
    .await;
    assert_eq!(verify_and_execute_result, execute_and_commit_result);
    execute_and_commit_result
}

async fn verify_and_execute_assert<P, V>(
    sealed_block: SealedBlock,
    block_after_execution: P,
    verifier_result: V,
) -> Result<(), Error>
where
    P: Fn() -> ExecutorResult<UncommittedValidationResult<Changes>> + Send + 'static,
    V: Fn() -> anyhow::Result<()> + Send + 'static,
{
    let importer = Importer::default_config(
        MockDatabase::default(),
        executor(block_after_execution),
        verifier(verifier_result),
    );

    importer
        .run_verify_and_execute_block(sealed_block)
        .await
        .map(|_| ())
}

#[tokio::test]
async fn verify_and_execute_allowed_when_locked() {
    let importer = Importer::default_config(
        MockDatabase::default(),
        executor(ex_result),
        verifier(ok(())),
    );

    let _guard = importer.lock();
    let result = importer.run_verify_and_execute_block(poa_block(13)).await;
    assert!(result.is_ok());
}