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
use crate::graphql_api::ports::DatabasePort;
use fuel_core_storage::{
    iter::{
        BoxedIter,
        IntoBoxedIter,
        IterDirection,
    },
    not_found,
    tables::{
        FuelBlocks,
        SealedBlockConsensus,
    },
    Result as StorageResult,
    StorageAsRef,
};
use fuel_core_types::{
    blockchain::{
        block::CompressedBlock,
        consensus::Consensus,
        primitives::BlockId,
    },
    fuel_types::BlockHeight,
};

pub trait SimpleBlockData: Send + Sync {
    fn block(&self, id: &BlockId) -> StorageResult<CompressedBlock>;
}

impl<D: DatabasePort + ?Sized> SimpleBlockData for D {
    fn block(&self, id: &BlockId) -> StorageResult<CompressedBlock> {
        let block = self
            .storage::<FuelBlocks>()
            .get(id)?
            .ok_or_else(|| not_found!(FuelBlocks))?
            .into_owned();

        Ok(block)
    }
}

pub trait BlockQueryData: Send + Sync + SimpleBlockData {
    fn block_id(&self, height: &BlockHeight) -> StorageResult<BlockId>;

    fn latest_block_id(&self) -> StorageResult<BlockId>;

    fn latest_block_height(&self) -> StorageResult<BlockHeight>;

    fn latest_block(&self) -> StorageResult<CompressedBlock>;

    fn compressed_blocks(
        &self,
        start: Option<BlockHeight>,
        direction: IterDirection,
    ) -> BoxedIter<StorageResult<CompressedBlock>>;

    fn consensus(&self, id: &BlockId) -> StorageResult<Consensus>;
}

impl<D: DatabasePort + ?Sized> BlockQueryData for D {
    fn block_id(&self, height: &BlockHeight) -> StorageResult<BlockId> {
        self.block_id(height)
    }

    fn latest_block_id(&self) -> StorageResult<BlockId> {
        self.ids_of_latest_block().map(|(_, id)| id)
    }

    fn latest_block_height(&self) -> StorageResult<BlockHeight> {
        self.ids_of_latest_block().map(|(height, _)| height)
    }

    fn latest_block(&self) -> StorageResult<CompressedBlock> {
        self.latest_block_id().and_then(|id| self.block(&id))
    }

    fn compressed_blocks(
        &self,
        start: Option<BlockHeight>,
        direction: IterDirection,
    ) -> BoxedIter<StorageResult<CompressedBlock>> {
        self.blocks_ids(start.map(Into::into), direction)
            .map(|result| {
                result.and_then(|(_, id)| {
                    let block = self.block(&id)?;

                    Ok(block)
                })
            })
            .into_boxed()
    }

    fn consensus(&self, id: &BlockId) -> StorageResult<Consensus> {
        self.storage::<SealedBlockConsensus>()
            .get(id)
            .map(|c| c.map(|c| c.into_owned()))?
            .ok_or(not_found!(SealedBlockConsensus))
    }
}