Skip to content

Commit 2e05557

Browse files
committed
apollo_batcher: commitment manager uses apollo committer types
1 parent 6d87e2f commit 2e05557

File tree

5 files changed

+131
-72
lines changed

5 files changed

+131
-72
lines changed

crates/apollo_batcher/src/batcher.rs

Lines changed: 84 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ use apollo_batcher_types::batcher_types::{
2626
use apollo_batcher_types::errors::BatcherError;
2727
use apollo_class_manager_types::transaction_converter::TransactionConverter;
2828
use apollo_class_manager_types::SharedClassManagerClient;
29-
use apollo_committer_types::communication::SharedCommitterClient;
29+
use apollo_committer_types::committer_types::{CommitBlockResponse, RevertBlockResponse};
30+
use apollo_committer_types::communication::{CommitterClientResponse, SharedCommitterClient};
31+
use apollo_committer_types::errors::CommitterClientResult;
3032
use apollo_infra::component_definitions::{default_component_start_fn, ComponentStarter};
3133
use apollo_l1_provider_types::errors::{L1ProviderClientError, L1ProviderError};
3234
use apollo_l1_provider_types::{SessionState, SharedL1ProviderClient};
@@ -705,7 +707,7 @@ impl Batcher {
705707
.expect("The commitment offset unexpectedly doesn't match the given block height.");
706708

707709
// Write ready commitments to storage.
708-
self.write_commitment_results_to_storage().await?;
710+
self.handle_committer_results().await?;
709711

710712
LAST_SYNCED_BLOCK_HEIGHT.set_lossy(block_number.0);
711713
SYNCED_TRANSACTIONS.increment(
@@ -770,7 +772,7 @@ impl Batcher {
770772
.expect("The commitment offset unexpectedly doesn't match the given block height.");
771773

772774
// Write ready commitments to storage.
773-
self.write_commitment_results_to_storage().await?;
775+
self.handle_committer_results().await?;
774776

775777
let execution_infos = block_execution_artifacts
776778
.execution_data
@@ -1152,66 +1154,95 @@ impl Batcher {
11521154
}
11531155

11541156
/// Writes the ready commitment results to storage.
1155-
async fn write_commitment_results_to_storage(&mut self) -> BatcherResult<()> {
1157+
async fn handle_committer_results(&mut self) -> BatcherResult<()> {
11561158
let commitment_results = self.commitment_manager.get_commitment_results().await;
11571159
for commitment_task_output in commitment_results.into_iter() {
1158-
let height = commitment_task_output.height;
1159-
1160-
// Decide whether to finalize the block hash based on the config.
1161-
let should_finalize_block_hash =
1162-
match self.config.first_block_with_partial_block_hash.as_ref() {
1163-
Some(FirstBlockWithPartialBlockHash { block_number, .. }) => {
1164-
height >= *block_number
1165-
}
1166-
None => true,
1167-
};
1168-
1169-
// Get the final commitment.
1170-
let FinalBlockCommitment { height, block_hash, global_root } =
1171-
ApolloCommitmentManager::final_commitment_output(
1172-
self.storage_reader.clone(),
1173-
commitment_task_output,
1174-
should_finalize_block_hash,
1175-
)
1176-
.map_err(|err| {
1177-
error!("Failed to get the final commitment output for height {height}: {err}");
1178-
BatcherError::InternalError
1179-
})?;
1180-
1181-
// Verify the first new block hash matches the configured block hash.
1182-
if let Some(FirstBlockWithPartialBlockHash {
1183-
block_number,
1184-
block_hash: expected_block_hash,
1185-
..
1186-
}) = self.config.first_block_with_partial_block_hash.as_ref()
1187-
{
1188-
if height == *block_number {
1189-
assert_eq!(
1190-
*expected_block_hash,
1191-
block_hash.expect(
1192-
"The block hash of the first new block should be finalized and \
1193-
therefore set."
1194-
),
1195-
"The calculated block hash of the first new block ({block_hash:?}) does \
1196-
not match the configured block hash ({expected_block_hash:?})"
1197-
);
1160+
match commitment_task_output.committer_response {
1161+
CommitterClientResponse::CommitBlock(commit_response) => {
1162+
self.write_commitment_result_to_storage(
1163+
commitment_task_output.height,
1164+
commit_response,
1165+
)
1166+
.await?;
1167+
}
1168+
CommitterClientResponse::RevertBlock(revert_response) => {
1169+
self.handle_revert_result(commitment_task_output.height, revert_response)
1170+
.await?;
11981171
}
11991172
}
1173+
}
1174+
Ok(())
1175+
}
12001176

1201-
// Write the block hash and global root to storage.
1202-
self.storage_writer
1203-
.set_global_root_and_block_hash(height, global_root, block_hash)
1204-
.map_err(|err| {
1205-
error!(
1206-
"Failed to set global root and block hash in storage for {height}: {err}"
1207-
);
1208-
BatcherError::InternalError
1209-
})?;
1177+
async fn write_commitment_result_to_storage(
1178+
&mut self,
1179+
height: BlockNumber,
1180+
commit_response_result: CommitterClientResult<CommitBlockResponse>,
1181+
) -> BatcherResult<()> {
1182+
// TODO: Handle commit block error.
1183+
let commit_response = commit_response_result.expect("Commit block error.");
1184+
1185+
// Decide whether to finalize the block hash based on the config.
1186+
let should_finalize_block_hash =
1187+
match self.config.first_block_with_partial_block_hash.as_ref() {
1188+
Some(FirstBlockWithPartialBlockHash { block_number, .. }) => {
1189+
height >= *block_number
1190+
}
1191+
None => true,
1192+
};
1193+
1194+
// Get the final commitment.
1195+
let FinalBlockCommitment { height, block_hash, global_root } =
1196+
ApolloCommitmentManager::final_commitment_output(
1197+
self.storage_reader.clone(),
1198+
commit_response,
1199+
height,
1200+
should_finalize_block_hash,
1201+
)
1202+
.map_err(|err| {
1203+
error!("Failed to get the final commitment output for height {height}: {err}");
1204+
BatcherError::InternalError
1205+
})?;
1206+
1207+
// Verify the first new block hash matches the configured block hash.
1208+
if let Some(FirstBlockWithPartialBlockHash {
1209+
block_number,
1210+
block_hash: expected_block_hash,
1211+
..
1212+
}) = self.config.first_block_with_partial_block_hash.as_ref()
1213+
{
1214+
if height == *block_number {
1215+
assert_eq!(
1216+
*expected_block_hash,
1217+
block_hash.expect(
1218+
"The block hash of the first new block should be finalized and therefore \
1219+
set."
1220+
),
1221+
"The calculated block hash of the first new block ({block_hash:?}) does not \
1222+
match the configured block hash ({expected_block_hash:?})"
1223+
);
1224+
}
12101225
}
12111226

1227+
// Write the block hash and global root to storage.
1228+
self.storage_writer
1229+
.set_global_root_and_block_hash(height, global_root, block_hash)
1230+
.map_err(|err| {
1231+
error!("Failed to set global root and block hash in storage for {height}: {err}");
1232+
BatcherError::InternalError
1233+
})?;
1234+
12121235
Ok(())
12131236
}
12141237

1238+
async fn handle_revert_result(
1239+
&mut self,
1240+
_height: BlockNumber,
1241+
_revert_response: CommitterClientResult<RevertBlockResponse>,
1242+
) -> BatcherResult<()> {
1243+
unimplemented!()
1244+
}
1245+
12151246
pub fn get_block_hash(&self, block_number: BlockNumber) -> BatcherResult<BlockHash> {
12161247
self.storage_reader
12171248
.get_block_hash(block_number)

crates/apollo_batcher/src/commitment_manager/commitment_manager_impl.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
use std::sync::Arc;
44

55
use apollo_batcher_config::config::BatcherConfig;
6-
use apollo_committer_types::communication::SharedCommitterClient;
6+
use apollo_committer_types::committer_types::{CommitBlockRequest, CommitBlockResponse};
7+
use apollo_committer_types::communication::{CommitterRequest, SharedCommitterClient};
78
use starknet_api::block::BlockNumber;
89
use starknet_api::block_hash::block_hash_calculator::{
910
calculate_block_hash,
@@ -110,7 +111,11 @@ impl<S: StateCommitterTrait> CommitmentManager<S> {
110111
});
111112
}
112113
let commitment_task_input =
113-
CommitmentTaskInput { height, state_diff, state_diff_commitment };
114+
CommitmentTaskInput(CommitterRequest::CommitBlock(CommitBlockRequest {
115+
height,
116+
state_diff,
117+
state_diff_commitment,
118+
}));
114119
let error_message = format!(
115120
"Failed to send commitment task to state committer. Block: {height}, state diff \
116121
commitment: {state_diff_commitment:?}",
@@ -262,13 +267,14 @@ impl<S: StateCommitterTrait> CommitmentManager<S> {
262267
// TODO(Rotem): Test this function.
263268
pub(crate) fn final_commitment_output<R: BatcherStorageReader + ?Sized>(
264269
storage_reader: Arc<R>,
265-
CommitmentTaskOutput { height, global_root }: CommitmentTaskOutput,
270+
CommitBlockResponse { state_root }: CommitBlockResponse,
271+
height: BlockNumber,
266272
should_finalize_block_hash: bool,
267273
) -> CommitmentManagerResult<FinalBlockCommitment> {
268274
match should_finalize_block_hash {
269275
false => {
270276
info!("Finalized commitment for block {height} without calculating block hash.");
271-
Ok(FinalBlockCommitment { height, block_hash: None, global_root })
277+
Ok(FinalBlockCommitment { height, block_hash: None, global_root: state_root })
272278
}
273279
true => {
274280
info!("Finalizing commitment for block {height} with calculating block hash.");
@@ -283,8 +289,12 @@ impl<S: StateCommitterTrait> CommitmentManager<S> {
283289
let partial_block_hash_components = partial_block_hash_components
284290
.ok_or(CommitmentManagerError::MissingPartialBlockHashComponents(height))?;
285291
let block_hash =
286-
calculate_block_hash(&partial_block_hash_components, global_root, parent_hash)?;
287-
Ok(FinalBlockCommitment { height, block_hash: Some(block_hash), global_root })
292+
calculate_block_hash(&partial_block_hash_components, state_root, parent_hash)?;
293+
Ok(FinalBlockCommitment {
294+
height,
295+
block_hash: Some(block_hash),
296+
global_root: state_root,
297+
})
288298
}
289299
}
290300
}

crates/apollo_batcher/src/commitment_manager/types.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
#![allow(dead_code)]
2+
use apollo_committer_types::communication::{CommitterClientResponse, CommitterRequest};
23
use starknet_api::block::{BlockHash, BlockNumber};
3-
use starknet_api::core::{GlobalRoot, StateDiffCommitment};
4-
use starknet_api::state::ThinStateDiff;
4+
use starknet_api::core::GlobalRoot;
55

66
/// Input for commitment tasks.
7-
pub(crate) struct CommitmentTaskInput {
8-
pub(crate) state_diff: ThinStateDiff,
9-
pub(crate) height: BlockNumber,
10-
// Field is optional because for old blocks, the state diff commitment might not be available.
11-
pub(crate) state_diff_commitment: Option<StateDiffCommitment>,
12-
}
7+
pub(crate) struct CommitmentTaskInput(pub(crate) CommitterRequest);
138

149
/// Output of commitment tasks.
15-
#[cfg_attr(test, derive(Default))]
1610
pub(crate) struct CommitmentTaskOutput {
17-
pub(crate) global_root: GlobalRoot,
11+
pub(crate) committer_response: CommitterClientResponse,
1812
pub(crate) height: BlockNumber,
1913
}
2014

crates/apollo_batcher/src/test_utils.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ use std::sync::Arc;
55
use apollo_batcher_config::config::{BatcherConfig, FirstBlockWithPartialBlockHash};
66
use apollo_batcher_types::batcher_types::{ProposalId, ProposeBlockInput};
77
use apollo_class_manager_types::{EmptyClassManagerClient, SharedClassManagerClient};
8-
use apollo_committer_types::communication::{MockCommitterClient, SharedCommitterClient};
8+
use apollo_committer_types::committer_types::CommitBlockResponse;
9+
use apollo_committer_types::communication::{
10+
CommitterClientResponse,
11+
MockCommitterClient,
12+
SharedCommitterClient,
13+
};
914
use apollo_l1_provider_types::MockL1ProviderClient;
1015
use apollo_mempool_types::communication::MockMempoolClient;
1116
use apollo_mempool_types::mempool_types::CommitBlockArgs;
@@ -340,8 +345,12 @@ impl MockStateCommitter {
340345
) {
341346
while mock_task_receiver.recv().await.is_some() {
342347
let task = tasks_receiver.try_recv().unwrap();
343-
let result =
344-
CommitmentTaskOutput { global_root: GlobalRoot::default(), height: task.height };
348+
let result = CommitmentTaskOutput {
349+
committer_response: CommitterClientResponse::CommitBlock(Ok(CommitBlockResponse {
350+
state_root: GlobalRoot::default(),
351+
})),
352+
height: task.0.height(),
353+
};
345354
results_sender.try_send(result).unwrap();
346355
}
347356
}

crates/apollo_committer_types/src/communication.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use async_trait::async_trait;
1010
#[cfg(any(feature = "testing", test))]
1111
use mockall::automock;
1212
use serde::{Deserialize, Serialize};
13+
use starknet_api::block::BlockNumber;
1314
use strum::{EnumVariantNames, VariantNames};
1415
use strum_macros::{AsRefStr, EnumDiscriminants, EnumIter, IntoStaticStr};
1516

@@ -58,6 +59,15 @@ impl_debug_for_infra_requests_and_responses!(CommitterRequest);
5859
impl_labeled_request!(CommitterRequest, CommitterRequestLabelValue);
5960
impl PrioritizedRequest for CommitterRequest {}
6061

62+
impl CommitterRequest {
63+
pub fn height(&self) -> BlockNumber {
64+
match self {
65+
CommitterRequest::CommitBlock(request) => request.height,
66+
CommitterRequest::RevertBlock(request) => request.height,
67+
}
68+
}
69+
}
70+
6171
#[derive(Clone, Serialize, Deserialize, AsRefStr)]
6272
pub enum CommitterResponse {
6373
CommitBlock(CommitterResult<CommitBlockResponse>),
@@ -71,6 +81,11 @@ generate_permutation_labels! {
7181
(LABEL_NAME_REQUEST_VARIANT, CommitterRequestLabelValue),
7282
}
7383

84+
pub enum CommitterClientResponse {
85+
CommitBlock(CommitterClientResult<CommitBlockResponse>),
86+
RevertBlock(CommitterClientResult<RevertBlockResponse>),
87+
}
88+
7489
#[async_trait]
7590
impl<ComponentClientType> CommitterClient for ComponentClientType
7691
where

0 commit comments

Comments
 (0)