lssa/indexer/core/src/lib.rs

345 lines
12 KiB
Rust
Raw Normal View History

2026-02-12 14:27:36 +02:00
use std::collections::VecDeque;
2026-01-27 09:46:31 +02:00
use anyhow::Result;
2026-02-11 16:24:46 +02:00
use bedrock_client::{BedrockClient, HeaderId};
2026-02-10 14:03:56 +02:00
use common::block::{Block, HashableBlockData};
2026-02-03 11:36:07 +02:00
// ToDo: Remove after testnet
2026-02-10 14:03:56 +02:00
use common::{HashType, PINATA_BASE58};
2026-02-18 14:58:33 +02:00
use log::{debug, error, info};
2026-01-27 08:13:53 +02:00
use logos_blockchain_core::mantle::{
2026-01-12 15:51:24 +02:00
Op, SignedMantleTx,
2026-02-17 10:46:51 +02:00
ops::channel::{ChannelId, inscribe::InscriptionOp},
2026-01-12 15:51:24 +02:00
};
2026-01-09 15:10:38 +02:00
2026-02-03 11:36:07 +02:00
use crate::{block_store::IndexerStore, config::IndexerConfig};
2026-01-12 15:51:24 +02:00
2026-02-03 11:36:07 +02:00
pub mod block_store;
2026-01-12 15:51:24 +02:00
pub mod config;
2026-01-13 15:11:51 +02:00
pub mod state;
2026-01-12 15:51:24 +02:00
2026-01-30 21:37:27 +03:00
#[derive(Clone)]
2026-01-09 15:10:38 +02:00
pub struct IndexerCore {
2026-02-03 11:36:07 +02:00
pub bedrock_client: BedrockClient,
pub config: IndexerConfig,
pub store: IndexerStore,
2026-01-09 15:10:38 +02:00
}
2026-02-23 11:39:04 +02:00
#[derive(Clone)]
/// This struct represents one L1 block data fetched from backfilling
pub struct BackfillBlockData {
l2_blocks: Vec<Block>,
l1_header: HeaderId,
}
#[derive(Clone)]
/// This struct represents data fetched fom backfilling in one iteration
pub struct BackfillData {
block_data: VecDeque<BackfillBlockData>,
curr_fin_l1_lib_header: HeaderId,
}
2026-01-09 15:10:38 +02:00
impl IndexerCore {
pub fn new(config: IndexerConfig) -> Result<Self> {
2026-02-10 14:03:56 +02:00
let hashable_data = HashableBlockData {
block_id: 1,
transactions: vec![],
prev_block_hash: HashType([0; 32]),
timestamp: 0,
};
2026-02-03 11:36:07 +02:00
2026-02-18 14:58:33 +02:00
// Genesis creation is fine as it is,
// because it will be overwritten by sequencer.
// Therefore:
// ToDo: remove key from indexer config, use some default.
2026-02-10 14:03:56 +02:00
let signing_key = nssa::PrivateKey::try_new(config.signing_key).unwrap();
let channel_genesis_msg_id = [0; 32];
let start_block = hashable_data.into_pending_block(&signing_key, channel_genesis_msg_id);
2026-02-03 11:36:07 +02:00
2026-02-18 14:58:33 +02:00
// This is a troubling moment, because changes in key protocol can
// affect this. And indexer can not reliably ask this data from sequencer
// because indexer must be independent from it.
// ToDo: move initial state generation into common and use the same method
// for indexer and sequencer. This way both services buit at same version
// could be in sync.
2026-02-03 11:36:07 +02:00
let initial_commitments: Vec<nssa_core::Commitment> = config
.initial_commitments
.iter()
.map(|init_comm_data| {
let npk = &init_comm_data.npk;
let mut acc = init_comm_data.account.clone();
acc.program_owner = nssa::program::Program::authenticated_transfer_program().id();
nssa_core::Commitment::new(npk, &acc)
})
.collect();
let init_accs: Vec<(nssa::AccountId, u128)> = config
.initial_accounts
.iter()
.map(|acc_data| (acc_data.account_id, acc_data.balance))
2026-02-03 11:36:07 +02:00
.collect();
let mut state = nssa::V02State::new_with_genesis_accounts(&init_accs, &initial_commitments);
// ToDo: Remove after testnet
state.add_pinata_program(PINATA_BASE58.parse().unwrap());
2026-02-13 13:59:06 +02:00
let home = config.home.join("rocksdb");
2026-02-03 11:36:07 +02:00
2026-01-12 15:51:24 +02:00
Ok(Self {
2026-01-22 14:44:48 +02:00
bedrock_client: BedrockClient::new(
config.bedrock_client_config.backoff,
2026-01-27 09:46:31 +02:00
config.bedrock_client_config.addr.clone(),
2026-02-10 15:54:57 +02:00
config.bedrock_client_config.auth.clone(),
2026-01-22 14:44:48 +02:00
)?,
2026-01-12 15:51:24 +02:00
config,
2026-02-03 11:36:07 +02:00
store: IndexerStore::open_db_with_genesis(&home, Some((start_block, state)))?,
2026-01-12 15:51:24 +02:00
})
2026-01-09 15:10:38 +02:00
}
2026-01-12 15:51:24 +02:00
2026-01-31 01:39:59 +03:00
pub async fn subscribe_parse_block_stream(&self) -> impl futures::Stream<Item = Result<Block>> {
2026-01-30 21:37:27 +03:00
async_stream::stream! {
2026-02-18 14:58:33 +02:00
info!("Searching for initial header");
2026-02-12 14:27:36 +02:00
2026-02-18 14:58:33 +02:00
let last_l1_lib_header = self.store.last_observed_l1_lib_header()?;
let mut prev_last_l1_lib_header = match last_l1_lib_header {
Some(last_l1_lib_header) => {
info!("Last l1 lib header found: {last_l1_lib_header}");
last_l1_lib_header
2026-02-12 14:27:36 +02:00
},
None => {
2026-02-18 14:58:33 +02:00
info!("Last l1 lib header not found in DB");
2026-02-12 14:27:36 +02:00
info!("Searching for the start of a channel");
2026-02-23 11:39:04 +02:00
let BackfillData {
block_data: start_buff,
curr_fin_l1_lib_header: last_l1_lib_header,
} = self.search_for_channel_start().await?;
2026-01-30 21:37:27 +03:00
2026-02-23 11:39:04 +02:00
for BackfillBlockData {
l2_blocks: l2_block_vec,
l1_header,
} in start_buff {
2026-02-18 14:58:33 +02:00
for l2_block in l2_block_vec {
self.store.put_block(l2_block.clone(), l1_header)?;
2026-02-12 14:27:36 +02:00
yield Ok(l2_block);
}
}
2026-02-18 14:58:33 +02:00
last_l1_lib_header
2026-02-12 14:27:36 +02:00
},
};
2026-02-18 14:58:33 +02:00
info!("Searching for initial header finished");
2026-02-12 14:27:36 +02:00
2026-02-18 14:58:33 +02:00
info!("Starting backfilling from {prev_last_l1_lib_header}");
2026-02-12 14:27:36 +02:00
2026-02-18 14:58:33 +02:00
loop {
2026-02-23 11:39:04 +02:00
let BackfillData {
block_data: buff,
curr_fin_l1_lib_header,
} = self
.backfill_to_last_l1_lib_header_id(prev_last_l1_lib_header, &self.config.channel_id)
.await
.inspect_err(|err| error!("Failed to backfill to last l1 lib header id with err {err:#?}"))?;
prev_last_l1_lib_header = curr_fin_l1_lib_header;
for BackfillBlockData {
l2_blocks: l2_block_vec,
l1_header: header,
} in buff {
2026-02-18 14:58:33 +02:00
for l2_block in l2_block_vec {
self.store.put_block(l2_block.clone(), header)?;
2026-01-15 15:44:48 +02:00
2026-02-03 11:36:07 +02:00
yield Ok(l2_block);
2026-01-16 16:15:21 +02:00
}
2026-01-12 15:51:24 +02:00
}
2026-02-03 11:36:07 +02:00
}
2026-01-16 16:15:21 +02:00
}
2026-01-12 15:51:24 +02:00
}
2026-02-11 16:24:46 +02:00
2026-02-18 14:58:33 +02:00
async fn get_lib(&self) -> Result<HeaderId> {
Ok(self.bedrock_client.get_consensus_info().await?.lib)
2026-02-17 10:46:51 +02:00
}
2026-02-18 14:58:33 +02:00
async fn get_next_lib(&self, prev_lib: HeaderId) -> Result<HeaderId> {
2026-02-17 10:46:51 +02:00
loop {
2026-02-18 14:58:33 +02:00
let next_lib = self.get_lib().await?;
if next_lib != prev_lib {
break Ok(next_lib);
2026-02-17 10:46:51 +02:00
} else {
2026-02-18 14:58:33 +02:00
info!(
"Wait {}ms to not spam the node",
self.config.consensus_info_polling_interval_millis
);
tokio::time::sleep(std::time::Duration::from_millis(
self.config.consensus_info_polling_interval_millis,
))
.await;
2026-02-17 10:46:51 +02:00
}
}
2026-02-11 16:24:46 +02:00
}
2026-02-18 14:58:33 +02:00
/// WARNING: depending on channel state,
2026-02-16 17:54:54 +02:00
/// may take indefinite amount of time
2026-02-23 11:39:04 +02:00
pub async fn search_for_channel_start(&self) -> Result<BackfillData> {
2026-02-18 14:58:33 +02:00
let mut curr_last_l1_lib_header = self.get_lib().await?;
let mut backfill_start = curr_last_l1_lib_header;
2026-02-16 17:54:54 +02:00
// ToDo: How to get root?
2026-02-18 14:58:33 +02:00
let mut backfill_limit = HeaderId::from([0; 32]);
2026-02-12 14:27:36 +02:00
// ToDo: Not scalable, initial buffer should be stored in DB to not run out of memory
// Don't want to complicate DB even more right now.
2026-02-16 17:54:54 +02:00
let mut block_buffer = VecDeque::new();
2026-02-11 16:24:46 +02:00
2026-02-16 17:54:54 +02:00
'outer: loop {
2026-02-18 14:58:33 +02:00
let mut cycle_header = curr_last_l1_lib_header;
2026-02-17 10:46:51 +02:00
2026-02-16 17:54:54 +02:00
loop {
2026-02-18 14:58:33 +02:00
let cycle_block =
2026-02-17 10:46:51 +02:00
if let Some(block) = self.bedrock_client.get_block_by_id(cycle_header).await? {
block
} else {
2026-02-18 14:58:33 +02:00
// First run can reach root easily
// so here we are optimistic about L1
// failing to get parent.
2026-02-17 10:46:51 +02:00
break;
};
2026-02-16 17:54:54 +02:00
2026-02-18 14:58:33 +02:00
// It would be better to have id, but block does not have it, so slot will do.
2026-02-16 17:54:54 +02:00
info!(
2026-02-18 14:58:33 +02:00
"INITIAL SEARCH: Observed L1 block at slot {}",
cycle_block.header().slot().into_inner()
2026-02-16 17:54:54 +02:00
);
2026-02-18 14:58:33 +02:00
debug!(
"INITIAL SEARCH: This block header is {}",
cycle_block.header().id()
2026-02-16 17:54:54 +02:00
);
2026-02-18 14:58:33 +02:00
debug!(
"INITIAL SEARCH: This block parent is {}",
cycle_block.header().parent()
2026-02-16 17:54:54 +02:00
);
2026-02-18 14:58:33 +02:00
let (l2_block_vec, l1_header) =
parse_block_owned(&cycle_block, &self.config.channel_id);
info!("Parsed {} L2 blocks", l2_block_vec.len());
if !l2_block_vec.is_empty() {
2026-02-23 11:39:04 +02:00
block_buffer.push_front(BackfillBlockData {
l2_blocks: l2_block_vec.clone(),
l1_header,
});
2026-02-18 14:58:33 +02:00
}
if let Some(first_l2_block) = l2_block_vec.first() {
if first_l2_block.header.block_id == 1 {
info!("INITIAL_SEARCH: Found channel start");
break 'outer;
}
2026-02-16 17:54:54 +02:00
} else {
// Step back to parent
2026-02-18 14:58:33 +02:00
let parent = cycle_block.header().parent();
2026-02-16 17:54:54 +02:00
2026-02-18 14:58:33 +02:00
if parent == backfill_limit {
2026-02-16 17:54:54 +02:00
break;
2026-02-11 16:24:46 +02:00
}
2026-02-16 17:54:54 +02:00
2026-02-17 10:46:51 +02:00
cycle_header = parent;
2026-02-16 17:54:54 +02:00
};
}
2026-02-18 14:58:33 +02:00
info!("INITIAL_SEARCH: Reached backfill limit, refetching last l1 lib header");
2026-02-16 17:54:54 +02:00
block_buffer.clear();
2026-02-18 14:58:33 +02:00
backfill_limit = backfill_start;
curr_last_l1_lib_header = self.get_next_lib(curr_last_l1_lib_header).await?;
backfill_start = curr_last_l1_lib_header;
2026-02-12 14:27:36 +02:00
}
2026-02-23 11:39:04 +02:00
Ok(BackfillData {
block_data: block_buffer,
curr_fin_l1_lib_header: backfill_limit,
})
2026-02-12 14:27:36 +02:00
}
2026-02-18 14:58:33 +02:00
pub async fn backfill_to_last_l1_lib_header_id(
2026-02-12 14:27:36 +02:00
&self,
2026-02-18 14:58:33 +02:00
last_fin_l1_lib_header: HeaderId,
channel_id: &ChannelId,
2026-02-23 11:39:04 +02:00
) -> Result<BackfillData> {
2026-02-18 14:58:33 +02:00
let curr_fin_l1_lib_header = self.get_next_lib(last_fin_l1_lib_header).await?;
2026-02-12 14:27:36 +02:00
// ToDo: Not scalable, buffer should be stored in DB to not run out of memory
// Don't want to complicate DB even more right now.
let mut block_buffer = VecDeque::new();
2026-02-18 14:58:33 +02:00
let mut cycle_header = curr_fin_l1_lib_header;
2026-02-12 14:27:36 +02:00
loop {
2026-02-18 14:58:33 +02:00
let Some(cycle_block) = self.bedrock_client.get_block_by_id(cycle_header).await? else {
return Err(anyhow::anyhow!("Parent not found"));
2026-02-12 14:27:36 +02:00
};
2026-02-18 14:58:33 +02:00
if cycle_block.header().id() == last_fin_l1_lib_header {
2026-02-12 14:27:36 +02:00
break;
} else {
// Step back to parent
2026-02-18 14:58:33 +02:00
cycle_header = cycle_block.header().parent();
2026-02-12 14:27:36 +02:00
}
2026-02-18 14:58:33 +02:00
// It would be better to have id, but block does not have it, so slot will do.
info!(
"Observed L1 block at slot {}",
cycle_block.header().slot().into_inner()
);
let (l2_block_vec, l1_header) = parse_block_owned(&cycle_block, channel_id);
info!("Parsed {} L2 blocks", l2_block_vec.len());
if !l2_block_vec.is_empty() {
2026-02-23 11:39:04 +02:00
block_buffer.push_front(BackfillBlockData {
l2_blocks: l2_block_vec,
l1_header,
});
2026-02-18 14:58:33 +02:00
}
2026-02-12 14:27:36 +02:00
}
2026-02-11 16:24:46 +02:00
2026-02-23 11:39:04 +02:00
Ok(BackfillData {
block_data: block_buffer,
curr_fin_l1_lib_header,
})
2026-02-11 16:24:46 +02:00
}
2026-01-12 15:51:24 +02:00
}
2026-02-18 14:58:33 +02:00
fn parse_block_owned(
l1_block: &bedrock_client::Block<SignedMantleTx>,
2026-01-12 15:51:24 +02:00
decoded_channel_id: &ChannelId,
2026-02-18 14:58:33 +02:00
) -> (Vec<Block>, HeaderId) {
(
l1_block
.transactions()
.flat_map(|tx| {
tx.mantle_tx.ops.iter().filter_map(|op| match op {
Op::ChannelInscribe(InscriptionOp {
channel_id,
inscription,
..
}) if channel_id == decoded_channel_id => {
borsh::from_slice::<Block>(inscription)
.inspect_err(|err| {
error!("Failed to deserialize our inscription with err: {err:#?}")
})
.ok()
}
_ => None,
})
})
.collect(),
l1_block.header().id(),
)
2026-02-04 14:57:38 +02:00
}