Skip to content

Commit c1662a8

Browse files
committed
Merge commit '503bb667fe279a7296b34a45303a4965ca323e95' into paradex_replay
2 parents 2d5df22 + 503bb66 commit c1662a8

File tree

8 files changed

+109
-27
lines changed

8 files changed

+109
-27
lines changed

.prettierignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,8 @@ orchestrator/build/
1414
orchestrator/node_modules/
1515
lib/
1616
s3/
17+
18+
*.rs
19+
*.toml
20+
Cargo.toml
21+
Cargo.lock

madara/crates/client/block_production/src/executor/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ pub enum ExecutorCommandError {
3838
pub enum ExecutorCommand {
3939
/// Force close the current block.
4040
CloseBlock(oneshot::Sender<Result<(), ExecutorCommandError>>),
41+
/// Reset executor state after a reorg. This reinitializes the state adapter from the current database state.
42+
ResetState(oneshot::Sender<Result<(), ExecutorCommandError>>),
4143
}
4244

4345
#[derive(Debug)]
@@ -54,6 +56,8 @@ pub enum ExecutorMessage {
5456
},
5557
BatchExecuted(BatchExecutionResult),
5658
EndBlock(Box<BlockExecutionSummary>),
59+
/// Notifies the task that executor state was reset after a reorg
60+
StateReset { latest_block_n: Option<u64> },
5761
}
5862

5963
#[derive(Default, Debug)]

madara/crates/client/block_production/src/executor/thread.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,45 @@ impl ExecutorThread {
336336
let _ = callback.send(Ok(()));
337337
Default::default()
338338
}
339+
super::ExecutorCommand::ResetState(callback) => {
340+
tracing::info!("🔄 Resetting executor state after reorg");
341+
// Reinitialize the state adapter from the current database state
342+
let new_state_adaptor = match mc_exec::LayeredStateAdapter::new(self.backend.clone()) {
343+
Ok(adaptor) => adaptor,
344+
Err(e) => {
345+
tracing::error!("Failed to reinitialize state adapter after reorg: {:#}", e);
346+
let _ = callback.send(Err(super::ExecutorCommandError::ChannelClosed));
347+
return Err(e.into());
348+
}
349+
};
350+
351+
let latest_block_n = new_state_adaptor.previous_block_n();
352+
tracing::info!("✅ State adapter reinitialized to block_n={}", new_state_adaptor.block_n());
353+
354+
// Reset the executor state to NewBlock with the fresh state adapter
355+
state = ExecutorThreadState::NewBlock(ExecutorStateNewBlock {
356+
state_adaptor: new_state_adaptor,
357+
consumed_l1_to_l2_nonces: HashSet::new(),
358+
});
359+
360+
// Clear any pending transactions by clearing both fields
361+
to_exec.txs.clear();
362+
to_exec.additional_info.clear();
363+
364+
// Reset block state flags
365+
block_empty = true;
366+
force_close = false;
367+
l2_gas_consumed_block = 0;
368+
369+
// Notify the main task that state was reset
370+
if self.replies_sender.blocking_send(super::ExecutorMessage::StateReset { latest_block_n }).is_err() {
371+
tracing::error!("Failed to send StateReset message to block production task");
372+
}
373+
374+
let _ = callback.send(Ok(()));
375+
// Continue the loop to wait for new transactions - don't return a batch
376+
continue;
377+
}
339378
},
340379
// Channel closed. Exit gracefully.
341380
WaitTxBatchOutcome::Exit => return Ok(()),

madara/crates/client/block_production/src/handle.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,15 @@ impl BlockProductionHandle {
9999
recv.await.map_err(|_| ExecutorCommandError::ChannelClosed)?
100100
}
101101

102+
/// Reset the executor state after a reorg. This reinitializes the state adapter from the current database state.
103+
pub async fn reset_state(&self) -> Result<(), ExecutorCommandError> {
104+
let (sender, recv) = oneshot::channel();
105+
self.executor_commands
106+
.send(ExecutorCommand::ResetState(sender))
107+
.map_err(|_| ExecutorCommandError::ChannelClosed)?;
108+
recv.await.map_err(|_| ExecutorCommandError::ChannelClosed)?
109+
}
110+
102111
/// Send a transaction through the bypass channel to bypass mempool and validation.
103112
pub async fn send_tx_raw(&self, tx: ValidatedTransaction) -> Result<(), ExecutorCommandError> {
104113
self.bypass_input.send(tx).await.map_err(|_| ExecutorCommandError::ChannelClosed)?;

madara/crates/client/block_production/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ pub use handle::BlockProductionHandle;
113113
pub enum BlockProductionStateNotification {
114114
ClosedBlock,
115115
BatchExecuted,
116+
StateReset,
116117
}
117118

118119
#[derive(Debug)]
@@ -351,6 +352,11 @@ impl BlockProductionTask {
351352
/// Handles the state machine and its transitions.
352353
async fn process_reply(&mut self, reply: ExecutorMessage) -> anyhow::Result<()> {
353354
match reply {
355+
ExecutorMessage::StateReset { latest_block_n } => {
356+
tracing::info!("🔄 Resetting block production task state after reorg to latest_block_n={:?}", latest_block_n);
357+
self.current_state = Some(TaskState::NotExecuting { latest_block_n });
358+
self.send_state_notification(BlockProductionStateNotification::StateReset);
359+
}
354360
ExecutorMessage::StartNewBlock { exec_ctx } => {
355361
tracing::debug!("Received ExecutorMessage::StartNewBlock block_n={}", exec_ctx.block_number);
356362
let current_state = self.current_state.take().context("No current state")?;

madara/crates/client/db/src/lib.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -379,21 +379,6 @@ impl<D: MadaraStorage> MadaraBackend<D> {
379379
Ok(())
380380
}
381381

382-
pub fn get_custom_header(&self) -> Option<CustomHeader> {
383-
self.get_custom_header_with_clear(false)
384-
}
385-
386-
pub fn get_custom_header_with_clear(&self, clear: bool) -> Option<CustomHeader> {
387-
let mut guard = self.custom_header.lock().expect("Poisoned lock");
388-
let result = guard.clone();
389-
390-
if clear {
391-
*guard = None;
392-
}
393-
394-
result
395-
}
396-
397382
pub fn set_custom_header(&self, custom_header: CustomHeader) {
398383
let mut guard = self.custom_header.lock().expect("Poisoned lock");
399384
*guard = Some(custom_header);
@@ -473,6 +458,21 @@ impl<D: MadaraStorageRead> MadaraBackend<D> {
473458
pub fn chain_config(&self) -> &Arc<ChainConfig> {
474459
&self.chain_config
475460
}
461+
462+
pub fn get_custom_header(&self) -> Option<CustomHeader> {
463+
self.get_custom_header_with_clear(false)
464+
}
465+
466+
pub fn get_custom_header_with_clear(&self, clear: bool) -> Option<CustomHeader> {
467+
let mut guard = self.custom_header.lock().expect("Poisoned lock");
468+
let result = guard.clone();
469+
470+
if clear {
471+
*guard = None;
472+
}
473+
474+
result
475+
}
476476
}
477477

478478
/// Structure holding exclusive access to write the blocks and the tip of the chain.

madara/crates/client/exec/src/layered_state_adapter.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,18 +45,22 @@ impl<D: MadaraStorageRead> LayeredStateAdapter<D> {
4545
let view = backend.view_on_latest_confirmed();
4646
let block_number = view.latest_block_n().map(|n| n + 1).unwrap_or(/* genesis */ 0);
4747

48-
let l1_gas_quote = backend
49-
.get_last_l1_gas_quote()
50-
.context("No L1 gas quote available. Ensure that the L1 gas quote is set before calculating gas prices.")?;
51-
52-
let gas_prices = if let Some(block) = view.block_view_on_latest_confirmed() {
53-
let block_info = block.get_block_info()?;
54-
let previous_strk_l2_gas_price = block_info.header.gas_prices.strk_l2_gas_price;
55-
let previous_l2_gas_used = block_info.total_l2_gas_used;
56-
57-
backend.calculate_gas_prices(&l1_gas_quote, previous_strk_l2_gas_price, previous_l2_gas_used)?
48+
let gas_prices = if let Some(custom_header) = backend.get_custom_header().filter(|h| h.block_n == block_number) {
49+
custom_header.gas_prices
5850
} else {
59-
backend.calculate_gas_prices(&l1_gas_quote, 0, 0)?
51+
let l1_gas_quote = backend
52+
.get_last_l1_gas_quote()
53+
.context("No L1 gas quote available. Ensure that the L1 gas quote is set before calculating gas prices.")?;
54+
55+
if let Some(block) = view.block_view_on_latest_confirmed() {
56+
let block_info = block.get_block_info()?;
57+
let previous_strk_l2_gas_price = block_info.header.gas_prices.strk_l2_gas_price;
58+
let previous_l2_gas_used = block_info.total_l2_gas_used;
59+
60+
backend.calculate_gas_prices(&l1_gas_quote, previous_strk_l2_gas_price, previous_l2_gas_used)?
61+
} else {
62+
backend.calculate_gas_prices(&l1_gas_quote, 0, 0)?
63+
}
6064
};
6165

6266
Ok(Self {

madara/crates/client/rpc/src/versions/admin/v0_1_0/methods/write.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use mp_rpc::v0_9_0::{
1111
ClassAndTxnHash, ContractAndTxnHash,
1212
};
1313
use mp_transactions::{L1HandlerTransactionResult, L1HandlerTransactionWithFee};
14-
14+
use mp_utils::service::MadaraServiceId;
1515
#[async_trait]
1616
impl MadaraWriteRpcApiV0_1_0Server for Starknet {
1717
/// Submit a new class v0 declaration transaction, bypassing mempool and all validation.
@@ -107,6 +107,21 @@ impl MadaraWriteRpcApiV0_1_0Server for Starknet {
107107
.map_err(StarknetRpcApiError::from)?;
108108
let backend_chain_tip = mc_db::ChainTip::from_storage(fresh_chain_tip);
109109
self.backend.chain_tip.send_replace(backend_chain_tip);
110+
111+
// Reset block production executor state if block production is enabled
112+
let bp_status = self.ctx.service_status(MadaraServiceId::BlockProduction);
113+
if matches!(bp_status, mp_utils::service::MadaraServiceStatus::On) {
114+
if let Some(block_prod_handle) = &self.block_prod_handle {
115+
tracing::debug!("revertTo: resetting block production state");
116+
block_prod_handle
117+
.reset_state()
118+
.await
119+
.context("Resetting block production executor state after reorg")
120+
.map_err(StarknetRpcApiError::from)?;
121+
tracing::debug!("revertTo: block production state reset complete");
122+
}
123+
}
124+
110125
Ok(())
111126
}
112127

0 commit comments

Comments
 (0)