1#[cfg(test)]
2mod tests;
3
4use crate::importing_blocks::{ImportingBlockHandle, ImportingBlocks, ParentBlockImportStatus};
5use crate::{BlockImport, BlockImportError, BlockImportedNotification};
6use ab_client_api::{
7 BeaconChainInfoWrite, BlockDetails, BlockOrigin, ChainInfo, PersistSuperSegmentsError,
8};
9use ab_client_block_verification::{BlockVerification, BlockVerificationError};
10use ab_client_consensus_common::BlockImportingNotification;
11use ab_client_consensus_common::consensus_parameters::{
12 DeriveConsensusParametersChainInfo, DeriveConsensusParametersConsensusInfo,
13 ShardMembershipEntropySourceChainInfo,
14};
15use ab_client_consensus_common::state::GlobalState;
16use ab_core_primitives::block::header::owned::OwnedBeaconChainHeader;
17use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
18use ab_core_primitives::block::{BlockNumber, BlockRoot};
19use ab_core_primitives::hashes::Blake3Hash;
20use ab_core_primitives::pot::PotOutput;
21use ab_core_primitives::segments::SuperSegment;
22use ab_proof_of_space::Table;
23use async_lock::Mutex as AsyncMutex;
24use futures::channel::mpsc;
25use futures::prelude::*;
26use send_future::SendFuture;
27use std::marker::PhantomData;
28use std::slice;
29use tracing::{info, warn};
30use triomphe::Arc;
31
32#[derive(Debug, thiserror::Error)]
34pub enum BeaconChainBlockImportError {
35 #[error("Block verification error: {error}")]
37 VerificationError {
38 #[from]
40 error: BlockVerificationError,
41 },
42 #[error("Failed to persist a new super segment: {error}")]
44 PersistSuperSegments {
45 #[from]
47 error: PersistSuperSegmentsError,
48 },
49}
50
51impl From<BeaconChainBlockImportError> for BlockImportError {
52 #[inline(always)]
53 fn from(error: BeaconChainBlockImportError) -> Self {
54 Self::Custom {
55 error: error.into(),
56 }
57 }
58}
59
60#[derive(Debug)]
63struct VerificationChainInfo<'a, CI> {
64 chain_info: &'a CI,
65 importing_blocks: &'a ImportingBlocks<OwnedBeaconChainHeader>,
66}
67
68impl<CI> DeriveConsensusParametersChainInfo for VerificationChainInfo<'_, CI>
69where
70 CI: ChainInfo<OwnedBeaconChainBlock>,
71{
72 fn ancestor_header_consensus_info(
73 &self,
74 ancestor_block_number: BlockNumber,
75 descendant_block_root: &BlockRoot,
76 ) -> Option<DeriveConsensusParametersConsensusInfo> {
77 let header = self.ancestor_header(ancestor_block_number, descendant_block_root)?;
78
79 Some(DeriveConsensusParametersConsensusInfo::from_consensus_info(
80 header.header().consensus_info,
81 ))
82 }
83}
84
85impl<CI> ShardMembershipEntropySourceChainInfo for VerificationChainInfo<'_, CI>
86where
87 CI: ChainInfo<OwnedBeaconChainBlock>,
88{
89 fn ancestor_header_proof_of_time(
90 &self,
91 ancestor_block_number: BlockNumber,
92 descendant_block_root: &BlockRoot,
93 ) -> Option<PotOutput> {
94 let header = self.ancestor_header(ancestor_block_number, descendant_block_root)?;
95
96 Some(header.header().consensus_info.proof_of_time)
97 }
98}
99
100impl<CI> VerificationChainInfo<'_, CI>
101where
102 CI: ChainInfo<OwnedBeaconChainBlock>,
103{
104 fn ancestor_header(
111 &self,
112 ancestor_block_number: BlockNumber,
113 descendant_block_root: &BlockRoot,
114 ) -> Option<OwnedBeaconChainHeader> {
115 if let Some(header) = self
118 .chain_info
119 .ancestor_header(ancestor_block_number, descendant_block_root)
120 {
121 return Some(header);
122 }
123
124 let mut block_root = *descendant_block_root;
127 while let Some(importing_entry) = self.importing_blocks.get(&block_root) {
128 let header = importing_entry.header().header();
129
130 if header.prefix.number == ancestor_block_number {
131 return Some(importing_entry.header().clone());
132 }
133
134 block_root = header.prefix.parent_root;
135 }
136
137 self.chain_info
141 .ancestor_header(ancestor_block_number, &block_root)
142 }
143}
144
145#[derive(Debug)]
146pub struct BeaconChainBlockImport<PosTable, CI, BV> {
147 chain_info: CI,
148 block_verification: BV,
149 importing_blocks: ImportingBlocks<OwnedBeaconChainHeader>,
150 block_importing_notification_sender: mpsc::Sender<BlockImportingNotification>,
151 super_segments_sender: AsyncMutex<mpsc::Sender<SuperSegment>>,
152 block_import_notification_sender:
153 AsyncMutex<mpsc::Sender<BlockImportedNotification<OwnedBeaconChainBlock>>>,
154 _pos_table: PhantomData<PosTable>,
155}
156
157impl<PosTable, CI, BV> BlockImport<OwnedBeaconChainBlock>
158 for BeaconChainBlockImport<PosTable, CI, BV>
159where
160 PosTable: Table,
161 CI: BeaconChainInfoWrite,
162 BV: BlockVerification<OwnedBeaconChainBlock, Option<SuperSegment>>,
163{
164 fn import(
165 &self,
166 block: OwnedBeaconChainBlock,
167 origin: BlockOrigin,
168 ) -> Result<impl Future<Output = Result<(), BlockImportError>> + Send, BlockImportError> {
169 let parent_root = &block.header.header().prefix.parent_root;
170
171 let (parent_header, parent_block_mmr, parent_block_import_status) =
172 if let Some((parent_header, parent_block_details)) =
173 self.chain_info.header_with_details(parent_root)
174 {
175 (
176 parent_header,
177 parent_block_details.mmr_with_block,
178 ParentBlockImportStatus::Imported {
179 system_contract_states: parent_block_details.system_contract_states,
180 },
181 )
182 } else if let Some(importing_entry) = self.importing_blocks.get(parent_root) {
183 (
184 importing_entry.header().clone(),
185 Arc::clone(importing_entry.mmr()),
186 ParentBlockImportStatus::Importing {
187 entry: importing_entry,
188 },
189 )
190 } else {
191 return Err(BlockImportError::UnknownParentBlock {
192 block_root: *parent_root,
193 });
194 };
195
196 let parent_block_mmr_root = Blake3Hash::from(
197 parent_block_mmr
198 .root()
199 .ok_or(BlockImportError::ParentBlockMmrInvalid)?,
200 );
201 let mut block_mmr = *parent_block_mmr;
202
203 if !block_mmr.add_leaf(&block.header.root()) {
204 return Err(BlockImportError::CantExtendMmr);
205 }
206
207 let importing_handle = self
208 .importing_blocks
209 .insert(block.header.clone(), Arc::new(block_mmr))
210 .ok_or(BlockImportError::AlreadyImporting)?;
211
212 if self.chain_info.header(&block.header.root()).is_some() {
213 return Err(BlockImportError::AlreadyImported);
214 }
215
216 Ok(self.import(
217 parent_header,
218 parent_block_mmr_root,
219 block,
220 origin,
221 importing_handle,
222 parent_block_import_status,
223 ))
224 }
225}
226
227impl<PosTable, CI, BV> BeaconChainBlockImport<PosTable, CI, BV>
228where
229 PosTable: Table,
230 CI: BeaconChainInfoWrite,
231 BV: BlockVerification<OwnedBeaconChainBlock, Option<SuperSegment>>,
232{
233 #[inline(always)]
235 pub fn new(
236 chain_info: CI,
237 block_verification: BV,
238 block_importing_notification_sender: mpsc::Sender<BlockImportingNotification>,
239 super_segments_sender: mpsc::Sender<SuperSegment>,
240 block_import_notification_sender: mpsc::Sender<
241 BlockImportedNotification<OwnedBeaconChainBlock>,
242 >,
243 ) -> Self {
244 Self {
245 chain_info,
246 block_verification,
247 importing_blocks: ImportingBlocks::new(),
248 block_importing_notification_sender,
249 super_segments_sender: AsyncMutex::new(super_segments_sender),
250 block_import_notification_sender: AsyncMutex::new(block_import_notification_sender),
251 _pos_table: PhantomData,
252 }
253 }
254
255 async fn import(
256 &self,
257 parent_header: OwnedBeaconChainHeader,
258 parent_block_mmr_root: Blake3Hash,
259 block: OwnedBeaconChainBlock,
260 origin: BlockOrigin,
261 importing_handle: ImportingBlockHandle<OwnedBeaconChainHeader>,
262 parent_block_import_status: ParentBlockImportStatus<OwnedBeaconChainHeader>,
263 ) -> Result<(), BlockImportError> {
264 let parent_header = parent_header.header();
265 let header = block.header.header();
266
267 #[expect(
268 clippy::rest_pattern_accessible_field,
269 reason = "Do not care about fields"
270 )]
271 let log_block_import = match origin {
272 BlockOrigin::LocalBlockBuilder { .. } => true,
273 BlockOrigin::Sync => false,
274 BlockOrigin::Broadcast => true,
275 };
276
277 self.block_verification
280 .verify_concurrent(
281 parent_header,
282 &parent_block_mmr_root,
283 &block,
284 &origin,
285 &VerificationChainInfo {
286 chain_info: &self.chain_info,
287 importing_blocks: &self.importing_blocks,
288 },
289 )
290 .send()
291 .await
292 .map_err(BeaconChainBlockImportError::from)?;
293
294 let Some(system_contract_states) = parent_block_import_status.wait().await else {
295 return Err(BlockImportError::ParentBlockImportFailed);
296 };
297
298 let maybe_super_segment = self
301 .block_verification
302 .verify_sequential(parent_header, &block, &origin)
303 .send()
304 .await
305 .map_err(BeaconChainBlockImportError::from)?;
306
307 let global_state = GlobalState::new(&system_contract_states);
308
309 let state_root = global_state.root();
312
313 if header.result.state_root != state_root {
314 return Err(BlockImportError::InvalidStateRoot {
315 expected: state_root,
316 actual: header.result.state_root,
317 });
318 }
319
320 let system_contract_states = global_state.to_system_contract_states();
321
322 let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(0);
323 if let Err(error) = self
324 .block_importing_notification_sender
325 .clone()
326 .send(BlockImportingNotification {
327 block_number: header.prefix.number,
328 acknowledgement_sender,
329 })
330 .await
331 {
332 warn!(%error, "Failed to send block importing notification");
333 }
334
335 while acknowledgement_receiver.next().await.is_some() {
336 }
338
339 let number = header.prefix.number;
340 let root = *header.root();
341
342 if let Some(super_segment) = maybe_super_segment {
343 let mut super_segment_sender = self.super_segments_sender.lock().await;
344 if self
345 .chain_info
346 .persist_super_segments(slice::from_ref(&super_segment))
347 .await
348 .map_err(|error| BeaconChainBlockImportError::PersistSuperSegments { error })?
349 && let Err(error) = super_segment_sender.send(super_segment).await
350 {
351 warn!(%error, "Failed to send a super segment notification");
352 }
353 }
354
355 let mut block_import_notification_sender =
358 self.block_import_notification_sender.lock().await;
359
360 let persisted_block_info = self
361 .chain_info
362 .persist_block(
363 block.clone(),
364 BlockDetails {
365 mmr_with_block: Arc::clone(importing_handle.mmr()),
366 system_contract_states: Arc::clone(&system_contract_states),
367 },
368 )
369 .await?;
370
371 importing_handle.set_success(system_contract_states);
372
373 if let Err(error) = block_import_notification_sender
374 .send(BlockImportedNotification {
375 block,
376 is_new_best: persisted_block_info.is_new_best,
377 })
378 .await
379 {
380 warn!(
381 %error,
382 block_number = %number,
383 block_root = %root,
384 "Failed to send block import notification"
385 );
386 }
387
388 if log_block_import {
389 info!(
390 %number,
391 %root,
392 "🏆 Imported block",
393 );
394 }
395
396 Ok(())
397 }
398}