Skip to content

Commit 000ade7

Browse files
committed
refactor
1 parent 9a3339a commit 000ade7

File tree

8 files changed

+126
-111
lines changed

8 files changed

+126
-111
lines changed

crates/chain-orchestrator/src/event.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,6 @@ pub enum ChainOrchestratorEvent {
6161
/// An L2 block has been committed returning the [`L2BlockInfoWithL1Messages`] and an
6262
/// optional [`BatchInfo`] if the block is associated with a committed batch.
6363
L2ChainCommitted(L2BlockInfoWithL1Messages, Option<BatchInfo>, bool),
64+
/// An L2 consolidated block has been committed returning the [`L2BlockInfoWithL1Messages`].
65+
L2ConsolidatedBlockCommitted(L2BlockInfoWithL1Messages),
6466
}

crates/chain-orchestrator/src/lib.rs

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ impl<
202202
let database = ctx.database.clone();
203203
let block_info: L2BlockInfoWithL1Messages = (&block_with_peer.block).into();
204204
Self::do_handle_block_from_peer(ctx, block_with_peer).await?;
205-
database.insert_block(block_info.clone(), None).await?;
205+
database.update_l1_messages_with_l2_block(block_info.clone()).await?;
206206
Ok(ChainOrchestratorEvent::L2ChainCommitted(block_info, None, true))
207207
}
208208

@@ -412,12 +412,32 @@ impl<
412412
}
413413
}
414414

415-
/// Inserts an L2 block in the database.
416-
pub fn consolidate_l2_blocks(
415+
/// Persist L1 consolidate blocks in the database.
416+
pub fn persist_l1_consolidated_blocks(
417417
&mut self,
418-
block_info: Vec<L2BlockInfoWithL1Messages>,
419-
batch_info: Option<BatchInfo>,
418+
block_infos: Vec<L2BlockInfoWithL1Messages>,
419+
batch_info: BatchInfo,
420420
) {
421+
let database = self.database.clone();
422+
let fut = self.handle_metered(
423+
ChainOrchestratorItem::InsertConsolidatedL2Blocks,
424+
Box::pin(async move {
425+
let head = block_infos.last().expect("block info must not be empty").clone();
426+
for block in block_infos {
427+
database.insert_block(block, batch_info).await?;
428+
}
429+
Result::<_, ChainOrchestratorError>::Ok(Some(
430+
ChainOrchestratorEvent::L2ConsolidatedBlockCommitted(head),
431+
))
432+
}),
433+
);
434+
435+
self.pending_futures.push_back(ChainOrchestratorFuture::HandleDerivedBlock(fut));
436+
self.waker.wake();
437+
}
438+
439+
/// Consolidates L2 blocks from the network which have been validated
440+
pub fn consolidate_validated_l2_blocks(&mut self, block_info: Vec<L2BlockInfoWithL1Messages>) {
421441
let database = self.database.clone();
422442
let l1_synced = self.l1_synced;
423443
let optimistic_mode = self.optimistic_mode.clone();
@@ -449,10 +469,10 @@ impl<
449469

450470
// Insert the blocks into the database.
451471
let head = block_info.last().expect("block info must not be empty").clone();
452-
database.insert_blocks(block_info, batch_info).await?;
472+
database.update_l1_messages_from_l2_blocks(block_info).await?;
453473

454474
Result::<_, ChainOrchestratorError>::Ok(Some(
455-
ChainOrchestratorEvent::L2ChainCommitted(head, batch_info, consolidated),
475+
ChainOrchestratorEvent::L2ChainCommitted(head, None, consolidated),
456476
))
457477
}),
458478
);
@@ -962,7 +982,7 @@ mod test {
962982
/// A headers+bodies client that stores the headers and bodies in memory, with an artificial
963983
/// soft bodies response limit that is set to 20 by default.
964984
///
965-
/// This full block client can be [Cloned] and shared between multiple tasks.
985+
/// This full block client can be [Clone]d and shared between multiple tasks.
966986
#[derive(Clone, Debug)]
967987
struct TestScrollFullBlockClient {
968988
headers: Arc<Mutex<HashMap<B256, Header>>>,
@@ -1230,13 +1250,13 @@ mod test {
12301250
l1_messages: vec![],
12311251
};
12321252

1233-
chain_orchestrator.consolidate_l2_blocks(vec![block_1.clone()], Some(batch_1_info));
1253+
chain_orchestrator.persist_l1_consolidated_blocks(vec![block_1.clone()], batch_1_info);
12341254
chain_orchestrator.next().await.unwrap().unwrap();
12351255

1236-
chain_orchestrator.consolidate_l2_blocks(vec![block_2.clone()], Some(batch_2_info));
1256+
chain_orchestrator.persist_l1_consolidated_blocks(vec![block_2.clone()], batch_2_info);
12371257
chain_orchestrator.next().await.unwrap().unwrap();
12381258

1239-
chain_orchestrator.consolidate_l2_blocks(vec![block_3.clone()], Some(batch_2_info));
1259+
chain_orchestrator.persist_l1_consolidated_blocks(vec![block_3.clone()], batch_2_info);
12401260
chain_orchestrator.next().await.unwrap().unwrap();
12411261

12421262
// Now simulate a batch revert by submitting a new batch with index 101
@@ -1513,7 +1533,12 @@ mod test {
15131533
} else {
15141534
None
15151535
};
1516-
indexer.consolidate_l2_blocks(vec![l2_block.clone()], batch_info);
1536+
if let Some(batch_info) = batch_info {
1537+
indexer.persist_l1_consolidated_blocks(vec![l2_block.clone()], batch_info);
1538+
} else {
1539+
indexer.consolidate_validated_l2_blocks(vec![l2_block.clone()]);
1540+
}
1541+
15171542
indexer.next().await.unwrap().unwrap();
15181543
blocks.push(l2_block);
15191544
}

crates/chain-orchestrator/src/metrics.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use strum::EnumIter;
77
pub enum ChainOrchestratorItem {
88
/// Handle a block received from the network.
99
NewBlock,
10+
/// Insert consolidated L2 blocks into the database.
11+
InsertConsolidatedL2Blocks,
1012
/// L2 block.
1113
InsertL2Block,
1214
/// L1 reorg.
@@ -26,6 +28,7 @@ impl ChainOrchestratorItem {
2628
pub const fn as_str(&self) -> &'static str {
2729
match self {
2830
Self::NewBlock => "new_block",
31+
Self::InsertConsolidatedL2Blocks => "insert_consolidated_l2_blocks",
2932
Self::InsertL2Block => "l2_block",
3033
Self::L1Reorg => "l1_reorg",
3134
Self::L1Finalization => "l1_finalization",

crates/database/db/src/db.rs

Lines changed: 15 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ mod test {
168168
},
169169
l1_messages: vec![],
170170
};
171-
db.insert_block(block_info, batch_info.into()).await.unwrap();
171+
db.insert_block(block_info, batch_info).await.unwrap();
172172
block_number += 1;
173173
}
174174

@@ -212,7 +212,7 @@ mod test {
212212
},
213213
l1_messages: vec![],
214214
};
215-
db.insert_block(block_info, first_batch_info.into()).await.unwrap();
215+
db.insert_block(block_info, first_batch_info).await.unwrap();
216216
block_number += 1;
217217
}
218218

@@ -402,7 +402,7 @@ mod test {
402402
let block_info = BlockInfo { number: i, hash: B256::arbitrary(&mut u).unwrap() };
403403
let l2_block = L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] };
404404
block_infos.push(block_info);
405-
db.insert_block(l2_block, Some(batch_info)).await.unwrap();
405+
db.insert_block(l2_block, batch_info).await.unwrap();
406406
}
407407

408408
// Test getting existing blocks
@@ -443,23 +443,14 @@ mod test {
443443

444444
db.insert_block(
445445
L2BlockInfoWithL1Messages { block_info: safe_block_1, l1_messages: vec![] },
446-
Some(batch_info),
446+
batch_info,
447447
)
448448
.await
449449
.unwrap();
450450

451451
db.insert_block(
452452
L2BlockInfoWithL1Messages { block_info: safe_block_2, l1_messages: vec![] },
453-
Some(batch_info),
454-
)
455-
.await
456-
.unwrap();
457-
458-
// Insert block without batch info (unsafe block)
459-
let unsafe_block = BlockInfo { number: 202, hash: B256::arbitrary(&mut u).unwrap() };
460-
db.insert_block(
461-
L2BlockInfoWithL1Messages { block_info: unsafe_block, l1_messages: vec![] },
462-
None,
453+
batch_info,
463454
)
464455
.await
465456
.unwrap();
@@ -486,7 +477,7 @@ mod test {
486477

487478
db.insert_block(
488479
L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] },
489-
Some(batch_info),
480+
batch_info,
490481
)
491482
.await
492483
.unwrap();
@@ -537,15 +528,7 @@ mod test {
537528
let block_info = BlockInfo { number: 500 + i, hash: B256::arbitrary(&mut u).unwrap() };
538529
let l2_block = L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] };
539530

540-
db.insert_block(l2_block, Some(batch_info)).await.unwrap();
541-
}
542-
543-
// Insert some blocks without batch index (should not be deleted)
544-
for i in 0..3 {
545-
let block_info = BlockInfo { number: 600 + i, hash: B256::arbitrary(&mut u).unwrap() };
546-
let l2_block = L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] };
547-
548-
db.insert_block(l2_block, None).await.unwrap();
531+
db.insert_block(l2_block, batch_info).await.unwrap();
549532
}
550533

551534
// Delete L2 blocks with batch index > 105
@@ -601,7 +584,8 @@ mod test {
601584
L2BlockInfoWithL1Messages { block_info, l1_messages: l1_message_hashes.clone() };
602585

603586
// Insert block
604-
db.insert_block(l2_block, Some(batch_info)).await.unwrap();
587+
db.insert_block(l2_block.clone(), batch_info).await.unwrap();
588+
db.update_l1_messages_with_l2_block(l2_block).await.unwrap();
605589

606590
// Verify block was inserted
607591
let retrieved_block = db.get_l2_block_info_by_number(500).await.unwrap();
@@ -637,7 +621,7 @@ mod test {
637621
let block_info = BlockInfo { number: 600, hash: B256::arbitrary(&mut u).unwrap() };
638622
let l2_block = L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] };
639623

640-
db.insert_block(l2_block, Some(batch_info_1)).await.unwrap();
624+
db.insert_block(l2_block, batch_info_1).await.unwrap();
641625

642626
// Verify initial insertion
643627
let retrieved_block = db.get_l2_block_info_by_number(600).await.unwrap();
@@ -650,15 +634,15 @@ mod test {
650634
.await
651635
.unwrap()
652636
.unwrap();
653-
let (initial_block_info, initial_batch_info): (BlockInfo, Option<BatchInfo>) =
637+
let (initial_block_info, initial_batch_info): (BlockInfo, BatchInfo) =
654638
initial_l2_block_model.into();
655639
assert_eq!(initial_block_info, block_info);
656-
assert_eq!(initial_batch_info, Some(batch_info_1));
640+
assert_eq!(initial_batch_info, batch_info_1);
657641

658642
// Update the same block with different batch info (upsert)
659643
let updated_l2_block = L2BlockInfoWithL1Messages { block_info, l1_messages: vec![] };
660644

661-
db.insert_block(updated_l2_block, Some(batch_info_2)).await.unwrap();
645+
db.insert_block(updated_l2_block, batch_info_2).await.unwrap();
662646

663647
// Verify the block still exists and was updated
664648
let retrieved_block = db.get_l2_block_info_by_number(600).await.unwrap().unwrap();
@@ -671,9 +655,9 @@ mod test {
671655
.await
672656
.unwrap()
673657
.unwrap();
674-
let (updated_block_info, updated_batch_info): (BlockInfo, Option<BatchInfo>) =
658+
let (updated_block_info, updated_batch_info): (BlockInfo, BatchInfo) =
675659
updated_l2_block_model.into();
676660
assert_eq!(updated_block_info, block_info);
677-
assert_eq!(updated_batch_info, Some(batch_info_2));
661+
assert_eq!(updated_batch_info, batch_info_2);
678662
}
679663
}

crates/database/db/src/models/l2_block.rs

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,17 @@ pub struct Model {
99
#[sea_orm(primary_key)]
1010
block_number: i64,
1111
block_hash: Vec<u8>,
12-
batch_index: Option<i64>,
13-
batch_hash: Option<Vec<u8>>,
12+
batch_index: i64,
13+
batch_hash: Vec<u8>,
1414
}
1515

1616
impl Model {
1717
pub(crate) fn block_info(&self) -> BlockInfo {
1818
BlockInfo { number: self.block_number as u64, hash: B256::from_slice(&self.block_hash) }
1919
}
2020

21-
pub(crate) fn batch_info(&self) -> Option<BatchInfo> {
22-
self.batch_hash.as_ref().map(|hash| BatchInfo {
23-
index: self.batch_index.expect("batch index must be present if batch hash is present")
24-
as u64,
25-
hash: B256::from_slice(hash),
26-
})
21+
pub(crate) fn batch_info(&self) -> BatchInfo {
22+
BatchInfo { index: self.batch_index as u64, hash: B256::from_slice(&self.batch_hash) }
2723
}
2824
}
2925

@@ -50,32 +46,32 @@ impl Related<super::batch_commit::Entity> for Entity {
5046
/// The active model behavior for the batch input model.
5147
impl ActiveModelBehavior for ActiveModel {}
5248

53-
impl From<(BlockInfo, Option<BatchInfo>)> for ActiveModel {
54-
fn from((block_info, batch_info): (BlockInfo, Option<BatchInfo>)) -> Self {
49+
impl From<(BlockInfo, BatchInfo)> for ActiveModel {
50+
fn from((block_info, batch_info): (BlockInfo, BatchInfo)) -> Self {
5551
Self {
5652
block_number: ActiveValue::Set(
5753
block_info.number.try_into().expect("block number should fit in i64"),
5854
),
5955
block_hash: ActiveValue::Set(block_info.hash.to_vec()),
6056
batch_index: ActiveValue::Set(
61-
batch_info.map(|x| x.index.try_into().expect("index should fit in i64")),
57+
batch_info.index.try_into().expect("index should fit in i64"),
6258
),
63-
batch_hash: ActiveValue::Set(batch_info.map(|x| x.hash.to_vec())),
59+
batch_hash: ActiveValue::Set(batch_info.hash.to_vec()),
6460
}
6561
}
6662
}
6763

68-
impl From<Model> for (BlockInfo, Option<BatchInfo>) {
64+
impl From<Model> for (BlockInfo, BatchInfo) {
6965
fn from(value: Model) -> Self {
7066
(
7167
BlockInfo {
7268
number: value.block_number as u64,
7369
hash: B256::from_slice(&value.block_hash),
7470
},
75-
value.batch_hash.map(|b| BatchInfo {
76-
index: value.batch_index.unwrap() as u64,
77-
hash: B256::from_slice(&b),
78-
}),
71+
BatchInfo {
72+
index: value.batch_index as u64,
73+
hash: B256::from_slice(&value.batch_hash),
74+
},
7975
)
8076
}
8177
}

0 commit comments

Comments
 (0)