ab_client_api/lib.rs
1//! Client API
2
3use ab_aligned_buffer::SharedAlignedBuffer;
4use ab_core_primitives::address::Address;
5use ab_core_primitives::block::owned::{GenericOwnedBlock, OwnedBeaconChainBlock};
6use ab_core_primitives::block::{BlockNumber, BlockRoot};
7use ab_core_primitives::segments::{
8 LocalSegmentIndex, SegmentHeader, SegmentIndex, SegmentRoot, SuperSegment, SuperSegmentHeader,
9 SuperSegmentIndex,
10};
11use ab_core_primitives::shard::ShardIndex;
12use ab_core_primitives::trees::BlockMerkleMountainRange;
13use std::io;
14use triomphe::Arc;
15
16/// State of a contract slot
17#[derive(Debug, Clone)]
18pub struct ContractSlotState {
19 /// Owner of the slot
20 pub owner: Address,
21 /// Contract that manages the slot
22 pub contract: Address,
23 /// Slot contents
24 pub contents: SharedAlignedBuffer,
25}
26
27/// Additional details about a block
28#[derive(Debug, Clone)]
29pub struct BlockDetails {
30 /// Merkle Mountain Range with block
31 pub mmr_with_block: Arc<BlockMerkleMountainRange>,
32 /// System contracts state after block
33 pub system_contract_states: Arc<[ContractSlotState]>,
34}
35
36/// Information about a block persisted with [`ChainInfoWrite::persist_block()`]
37#[derive(Debug, Copy, Clone)]
38pub struct PersistedBlockInfo {
39 /// Whether the block became the new best block
40 pub is_new_best: bool,
41}
42
43// TODO: Probably move it elsewhere
44/// Origin
45#[derive(Debug, Clone)]
46pub enum BlockOrigin {
47 // TODO: Take advantage of this in block import
48 /// Created locally by block builder
49 LocalBlockBuilder {
50 /// Additional details about a block
51 block_details: BlockDetails,
52 },
53 /// Received during the sync process
54 Sync,
55 /// Broadcast on the network during normal operation (not sync)
56 Broadcast,
57}
58
59/// Intermediate or leaf shard segment root information
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct ShardSegmentRoot {
62 /// Shard index
63 pub shard_index: ShardIndex,
64 /// Local segment index
65 pub segment_index: LocalSegmentIndex,
66 /// Segment root
67 pub segment_root: SegmentRoot,
68}
69
70/// Error for [`ChainInfo::block()`]
71#[derive(Debug, thiserror::Error)]
72pub enum ReadBlockError {
73 /// Unknown block root
74 #[error("Unknown block root")]
75 UnknownBlockRoot,
76 /// Failed to decode the block
77 #[error("Failed to decode the block")]
78 FailedToDecode,
79 /// Storage item read error
80 #[error("Storage item read error")]
81 StorageItemReadError {
82 /// Low-level error
83 #[from]
84 error: io::Error,
85 },
86}
87
88/// Error for [`ChainInfoWrite::persist_block()`]
89#[derive(Debug, thiserror::Error)]
90pub enum PersistBlockError {
91 /// Block is already known
92 #[error("Block is already known")]
93 AlreadyKnown,
94 /// Missing parent
95 #[error("Missing parent")]
96 MissingParent,
97 /// Block is outside the acceptable range
98 #[error("Block is outside the acceptable range")]
99 OutsideAcceptableRange,
100 /// Persisting is not possible anymore
101 #[error("Persisting is not possible anymore")]
102 Unavailable,
103}
104
105/// Error for [`ChainInfoWrite::persist_segment_headers()`]
106#[derive(Debug, thiserror::Error)]
107pub enum PersistSegmentHeadersError {
108 /// Segment index must strictly follow the last segment index, can't store segment header
109 #[error(
110 "Segment index {local_segment_index} must strictly follow last segment index \
111 {last_local_segment_index}, can't store segment header"
112 )]
113 MustFollowLastSegmentIndex {
114 /// Segment index that was attempted to be inserted
115 local_segment_index: LocalSegmentIndex,
116 /// Last segment index
117 last_local_segment_index: LocalSegmentIndex,
118 },
119 /// The first segment index must be zero
120 #[error("First segment index must be zero, found {local_segment_index}")]
121 FirstSegmentIndexZero {
122 /// Segment index that was attempted to be inserted
123 local_segment_index: LocalSegmentIndex,
124 },
125 /// Persisting is not possible anymore
126 #[error("Persisting is not possible anymore")]
127 Unavailable,
128}
129
130/// Error for [`BeaconChainInfo::shard_segment_roots()`]
131#[derive(Debug, thiserror::Error)]
132pub enum ShardSegmentRootsError {
133 /// Block missing
134 #[error("Block {block_number} is missing")]
135 BlockMissing {
136 /// The block number that is missing in the database
137 block_number: BlockNumber,
138 },
139}
140
141/// Error for [`BeaconChainInfoWrite::persist_super_segments()`]
142#[derive(Debug, thiserror::Error)]
143pub enum PersistSuperSegmentsError {
144 /// Super segment index must strictly follow the last super segment index, can't store super
145 /// segment
146 #[error(
147 "Super segment index {super_segment_index} must strictly follow last super segment index \
148 {last_super_segment_index}, can't store super segment"
149 )]
150 MustFollowLastSegmentIndex {
151 /// Super segment index that was attempted to be inserted
152 super_segment_index: SuperSegmentIndex,
153 /// Last super segment index
154 last_super_segment_index: SuperSegmentIndex,
155 },
156 /// The first super segment index must be zero
157 #[error("First super segment index must be zero, found {super_segment_index}")]
158 FirstSegmentIndexZero {
159 /// Super segment index that was attempted to be inserted
160 super_segment_index: SuperSegmentIndex,
161 },
162 /// Persisting is not possible anymore
163 #[error("Persisting is not possible anymore")]
164 Unavailable,
165}
166
167// TODO: Split this into different more narrow traits
168/// Chain info.
169///
170/// NOTE:
171/// <div class="warning">
172/// Blocks or their parts returned from these APIs are reference-counted and cheap to clone.
173/// However, it is not expected that they will be retained in memory for a long time. Blocks and
174/// headers will not be pruned until their reference count goes down to one. This is imported when
175/// there is an ongoing block import happening and its parent must exist until the import
176/// finishes. Forks that can't become a part of the best chain anymore are the exception (see
177/// `ConsensusConstants::block_confirmation_depth`), importing their blocks fails instead.
178/// </div>
179pub trait ChainInfo<Block>: Clone + Send + Sync + 'static
180where
181 Block: GenericOwnedBlock,
182{
183 /// Best block root
184 fn best_root(&self) -> BlockRoot;
185
186 // TODO: Uncomment if/when necessary
187 // /// Find root of ancestor block number for descendant block root
188 // fn ancestor_root(
189 // &self,
190 // ancestor_block_number: BlockNumber,
191 // descendant_block_root: &BlockRoot,
192 // ) -> Option<BlockRoot>;
193
194 /// Best block header
195 fn best_header(&self) -> Block::Header;
196
197 /// Returns the best block header like [`Self::best_header()`] with additional block details
198 fn best_header_with_details(&self) -> (Block::Header, BlockDetails);
199
200 /// Get the header of the block at `ancestor_block_number` on the chain ending at
201 /// `descendant_block_root`.
202 ///
203 /// If `ancestor_block_number` is the descendant's own number, the descendant's header is
204 /// returned. Returns `None` if `ancestor_block_number` is higher than the descendant's number
205 /// or if either block is not available.
206 fn ancestor_header(
207 &self,
208 ancestor_block_number: BlockNumber,
209 descendant_block_root: &BlockRoot,
210 ) -> Option<Block::Header>;
211
212 /// Block header
213 fn header(&self, block_root: &BlockRoot) -> Option<Block::Header>;
214
215 /// Returns a block header like [`Self::header()`] with additional block details
216 fn header_with_details(&self, block_root: &BlockRoot) -> Option<(Block::Header, BlockDetails)>;
217
218 fn block(
219 &self,
220 block_root: &BlockRoot,
221 ) -> impl Future<Output = Result<Block, ReadBlockError>> + Send;
222
223 /// Returns the last observed local segment header of this shard
224 fn last_segment_header(&self) -> Option<SegmentHeader>;
225
226 /// Get a single segment header
227 fn get_segment_header(&self, segment_index: LocalSegmentIndex) -> Option<SegmentHeader>;
228
229 /// Get segment headers that are expected to be included at specified block number
230 fn segment_headers_for_block(&self, block_number: BlockNumber) -> Vec<SegmentHeader>;
231}
232
233/// [`ChainInfo`] extension for writing information
234pub trait ChainInfoWrite<Block>: ChainInfo<Block>
235where
236 Block: GenericOwnedBlock,
237{
238 /// Persist newly imported block
239 fn persist_block(
240 &self,
241 block: Block,
242 block_details: BlockDetails,
243 ) -> impl Future<Output = Result<PersistedBlockInfo, PersistBlockError>> + Send;
244
245 /// Persist segment headers.
246 ///
247 /// Multiple can be inserted for efficiency purposes.
248 fn persist_segment_headers(
249 &self,
250 segment_headers: Vec<SegmentHeader>,
251 ) -> impl Future<Output = Result<(), PersistSegmentHeadersError>> + Send;
252}
253
254/// Beacon chain info
255pub trait BeaconChainInfo: ChainInfo<OwnedBeaconChainBlock> {
256 /// Returns intermediate and leaf shard segment roots included in the block at
257 /// `ancestor_block_number` on the chain ending at `descendant_block_root`.
258 ///
259 /// If `ancestor_block_number` is the descendant's own number, the descendant's shard segment
260 /// roots are returned.
261 fn shard_segment_roots(
262 &self,
263 ancestor_block_number: BlockNumber,
264 descendant_block_root: &BlockRoot,
265 ) -> Result<Arc<[ShardSegmentRoot]>, ShardSegmentRootsError>;
266
267 /// Returns the last observed super segment header
268 fn last_super_segment_header(&self) -> Option<SuperSegmentHeader>;
269
270 /// Returns the previous super segment header for the block built with the specified target
271 /// block number.
272 ///
273 /// `None` is returned for blocks <= 1.
274 fn previous_super_segment_header(
275 &self,
276 block_number: BlockNumber,
277 ) -> Option<SuperSegmentHeader>;
278
279 /// Get a single super segment header
280 fn get_super_segment_header(
281 &self,
282 super_segment_index: SuperSegmentIndex,
283 ) -> Option<SuperSegmentHeader>;
284
285 /// Get a single super segment header for a segment index
286 fn get_super_segment_header_for_segment_index(
287 &self,
288 segment_index: SegmentIndex,
289 ) -> Option<SuperSegmentHeader>;
290
291 /// Returns the highest local segment index of a shard (the beacon chain included) that was
292 /// included in super segments.
293 ///
294 /// `None` is returned if no super segment included a segment of the shard yet.
295 fn shard_max_local_segment_index(&self, shard_index: ShardIndex) -> Option<LocalSegmentIndex>;
296}
297
298/// [`BeaconChainInfo`] extension for writing information
299pub trait BeaconChainInfoWrite: BeaconChainInfo + ChainInfoWrite<OwnedBeaconChainBlock> {
300 /// Persist super segments.
301 ///
302 /// Returns `Ok(true)` if at least one super segment was inserted, `Ok(false)` if all of them
303 /// were already present.
304 fn persist_super_segments(
305 &self,
306 super_segments: &[SuperSegment],
307 ) -> impl Future<Output = Result<bool, PersistSuperSegmentsError>> + Send;
308}
309
310/// Chain sync status
311pub trait ChainSyncStatus: Clone + Send + Sync + 'static {
312 /// The block number that the sync process is targeting right now.
313 ///
314 /// Can be zero if not syncing actively.
315 fn target_block_number(&self) -> BlockNumber;
316
317 /// Returns `true` if the chain is currently syncing
318 fn is_syncing(&self) -> bool;
319
320 /// Returns `true` if the node is currently offline
321 fn is_offline(&self) -> bool;
322}