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
use std::collections::HashSet;
// Copyright 2021-2023 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use std::rc::Rc;

use cid::Cid;
use fvm_ipld_encoding::ipld_block::IpldBlock;

use super::Result;
use crate::syscall_error;

/// A registry of open blocks (per-kernel). Think "file descriptor" table. At the moment, there's no
/// way to close/remove a block from this table.
#[derive(Default)]
pub struct BlockRegistry {
    blocks: Vec<Block>,
    reachable: HashSet<Cid>,
}

/// Blocks in the block registry are addressed by an ordinal, starting from 1 (`FIRST_ID`).
/// The zero value is reserved to mean "no data", such as when actor invocations
/// receive or return no data.
pub type BlockId = u32;

const FIRST_ID: BlockId = 1;
const MAX_BLOCKS: u32 = i32::MAX as u32; // TODO(M2): Limit

#[derive(Debug, Copy, Clone)]
pub struct BlockStat {
    pub codec: u64,
    pub size: u32,
}

#[derive(Debug, Clone)]
pub struct Block(Rc<BlockInner>);
#[derive(Debug)]
struct BlockInner {
    codec: u64,
    data: Box<[u8]>,
    links: Box<[Cid]>,
}

impl Block {
    pub fn new(codec: u64, data: impl Into<Box<[u8]>>, links: impl Into<Box<[Cid]>>) -> Self {
        // This requires an extra allocation (ew) but no extra copy on send.
        // The extra allocation is basically nothing.
        Self(Rc::new(BlockInner {
            codec,
            data: data.into(),
            links: links.into(),
        }))
    }

    #[inline(always)]
    pub fn codec(&self) -> u64 {
        self.0.codec
    }

    #[inline(always)]
    pub fn links(&self) -> &[Cid] {
        &self.0.links
    }

    #[inline(always)]
    pub fn data(&self) -> &[u8] {
        &self.0.data
    }

    #[inline(always)]
    pub fn size(&self) -> u32 {
        self.0.data.len() as u32
    }

    #[inline(always)]
    pub fn stat(&self) -> BlockStat {
        BlockStat {
            codec: self.codec(),
            size: self.size(),
        }
    }
}

impl From<&Block> for IpldBlock {
    fn from(b: &Block) -> Self {
        IpldBlock {
            codec: b.0.codec,
            data: Vec::from(&*b.0.data),
        }
    }
}

impl BlockRegistry {
    pub(crate) fn new() -> Self {
        Self::default()
    }
}

impl BlockRegistry {
    /// Adds a new block to the registry, marking all children as reachable, returning a handle to
    /// refer to it. Use this when adding a block known to be reachable.
    pub fn put_reachable(&mut self, block: Block) -> Result<BlockId> {
        self.put_inner(block, false)
    }

    /// Adds a new block to the registry, checking that all children are currently reachable,
    /// returning a handle to refer to it. Use this when creating a _new_ block.
    //
    //  Returns a `NotFound` error if `block` references any unreachable CIDs.
    pub fn put_check_reachable(&mut self, block: Block) -> Result<BlockId> {
        self.put_inner(block, true)
    }

    /// Mark a cid as reachable. Call this when a new block is linked into the state.
    pub fn mark_reachable(&mut self, k: &Cid) {
        self.reachable.insert(*k);
    }

    /// Check if a block is reachable. Call this before attempting to read the block from the
    /// datastore.
    pub fn is_reachable(&self, k: &Cid) -> bool {
        // NOTE: do not implicitly treat inline blocks (identity-hashed CIDs) as "reachable" as they
        // may contain links to _unreachable_ children.
        self.reachable.contains(k)
    }

    /// Adds a new block to the registry, and returns a handle to refer to it.
    fn put_inner(&mut self, block: Block, check_reachable: bool) -> Result<BlockId> {
        if self.is_full() {
            return Err(syscall_error!(LimitExceeded; "too many blocks").into());
        }

        // We expect the caller to have already charged for gas.
        if check_reachable {
            if let Some(k) = block.links().iter().find(|k| !self.is_reachable(k)) {
                return Err(syscall_error!(NotFound; "cannot put block: {k} not reachable").into());
            }
        } else {
            for k in block.links() {
                self.mark_reachable(k)
            }
        }

        let id = FIRST_ID + self.blocks.len() as u32;
        self.blocks.push(block);
        Ok(id)
    }

    /// Gets the block associated with a block handle.
    pub fn get(&self, id: BlockId) -> Result<&Block> {
        if id < FIRST_ID {
            return Err(syscall_error!(InvalidHandle; "invalid block handle {id}").into());
        }
        id.try_into()
            .ok()
            .and_then(|idx: usize| self.blocks.get(idx - FIRST_ID as usize))
            .ok_or(syscall_error!(InvalidHandle; "invalid block handle {id}").into())
    }

    /// Returns the size & codec of the specified block.
    pub fn stat(&self, id: BlockId) -> Result<BlockStat> {
        if id < FIRST_ID {
            return Err(syscall_error!(InvalidHandle; "invalid block handle {id}").into());
        }
        id.try_into()
            .ok()
            .and_then(|idx: usize| self.blocks.get(idx - FIRST_ID as usize))
            .ok_or(syscall_error!(InvalidHandle; "invalid block handle {id}").into())
            .map(|b| BlockStat {
                codec: b.codec(),
                size: b.size(),
            })
    }

    pub fn is_full(&self) -> bool {
        self.blocks.len() as u32 == MAX_BLOCKS
    }
}