Skip to content

Commit

Permalink
reader, state: remove rollupparams to use RelevantTxType
Browse files Browse the repository at this point in the history
  • Loading branch information
voidash committed Sep 18, 2024
1 parent 03b6d04 commit d696e1d
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 78 deletions.
16 changes: 10 additions & 6 deletions crates/btcio/src/reader/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct DepositInfo {
/// outpoint where amount is present
pub deposit_outpoint: u32,

/// evm address
/// EE address
pub address: Vec<u8>,
}

Expand All @@ -46,21 +46,28 @@ pub struct DepositTxConfig {
}

impl DepositTxConfig {
pub fn new(params: &RollupParams) -> Self {
pub fn from_params(params: &RollupParams) -> Self {
Self {
magic_bytes: params.rollup_name.clone().into_bytes().to_vec(),
address_length: params.deposit_address_length,
deposit_quantity: params.deposit_quantity,
}
}

Check warning on line 55 in crates/btcio/src/reader/deposit.rs

View check run for this annotation

Codecov / codecov/patch

crates/btcio/src/reader/deposit.rs#L49-L55

Added lines #L49 - L55 were not covered by tests

pub fn new(magic_bytes: &[u8], addr_len: u8, amount: u64) -> Self {
Self {
magic_bytes: magic_bytes.to_vec(),
address_length: addr_len,
deposit_quantity: amount,
}
}

Check warning on line 63 in crates/btcio/src/reader/deposit.rs

View check run for this annotation

Codecov / codecov/patch

crates/btcio/src/reader/deposit.rs#L57-L63

Added lines #L57 - L63 were not covered by tests
}

/// Extracts the DepositInfo from the Deposit Transaction
pub fn extract_deposit_info(
tx: &Transaction,
config: &DepositTxConfig,
) -> Result<DepositInfo, DepositParseError> {
println!("the transaction is {:?}", tx);
for output in tx.output.iter() {
let mut instructions = output.script_pubkey.instructions();

Expand All @@ -71,7 +78,6 @@ pub fn extract_deposit_info(

// magic bytes
if let Some(Ok(Instruction::PushBytes(magic_bytes))) = instructions.next() {
println!("{:?}", String::from_utf8(magic_bytes.as_bytes().to_vec()));
if magic_bytes.as_bytes() != config.magic_bytes {
return Err(DepositParseError::MagicBytesMismatch(
magic_bytes.as_bytes().to_vec(),
Expand Down Expand Up @@ -195,8 +201,6 @@ mod tests {

let out = extract_deposit_info(&test_transaction, &get_deposit_tx_config());

println!("{:?}", out);

assert!(out.is_ok());
let out = out.unwrap();

Expand Down
57 changes: 13 additions & 44 deletions crates/btcio/src/reader/filter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use alpen_express_primitives::params::RollupParams;
use bitcoin::{Address, Block, Transaction};

use super::deposit::{extract_deposit_info, DepositTxConfig};
Expand All @@ -12,31 +11,27 @@ pub enum RelevantTxType {
/// Inscription transactions with given Rollup name. This will be parsed by
/// [`InscriptionParser`] which dictates the structure of inscription.
RollupInscription(RollupName),
// Add other relevant conditions as needed
Deposit,
/// Deposit transaction
Deposit(RollupName, AddressLength, Amount),
}

type RollupName = String;
type AddressLength = u8;
type Amount = u64;

/// Filter all the relevant [`Transaction`]s in a block based on given [`RelevantTxType`]s
pub fn filter_relevant_txs(
block: &Block,
relevent_types: &[RelevantTxType],
params: &RollupParams,
) -> Vec<u32> {
println!("the block tx is {:?}", block.txdata);

pub fn filter_relevant_txs(block: &Block, relevent_types: &[RelevantTxType]) -> Vec<u32> {
block
.txdata
.iter()
.enumerate()
.filter(|(_, tx)| is_relevant(tx, relevent_types, params))
.filter(|(_, tx)| is_relevant(tx, relevent_types))
.map(|(i, _)| i as u32)
.collect()
}

/// Determines if a [`Transaction`] is relevant based on given [`RelevantTxType`]s
fn is_relevant(tx: &Transaction, relevant_types: &[RelevantTxType], params: &RollupParams) -> bool {
fn is_relevant(tx: &Transaction, relevant_types: &[RelevantTxType]) -> bool {
relevant_types.iter().any(|rel_type| match rel_type {
RelevantTxType::SpentToAddress(address) => tx
.output
Expand All @@ -56,10 +51,9 @@ fn is_relevant(tx: &Transaction, relevant_types: &[RelevantTxType], params: &Rol
.is_some()
}
},
RelevantTxType::Deposit => {
let config = DepositTxConfig::new(params);
RelevantTxType::Deposit(rollup_name, addr_len, amt) => {
let config = DepositTxConfig::new(rollup_name.as_bytes(), *addr_len, *amt);
let deposit_info = extract_deposit_info(tx, &config);
println!("{:?}", deposit_info);

deposit_info.is_ok()

Check warning on line 58 in crates/btcio/src/reader/filter.rs

View check run for this annotation

Codecov / codecov/patch

crates/btcio/src/reader/filter.rs#L54-L58

Added lines #L54 - L58 were not covered by tests
}
Expand All @@ -70,7 +64,6 @@ fn is_relevant(tx: &Transaction, relevant_types: &[RelevantTxType], params: &Rol
mod test {
use std::str::FromStr;

use alpen_test_utils::l2::gen_params;
use bitcoin::{
absolute::{Height, LockTime},
block::{Header, Version as BVersion},
Expand Down Expand Up @@ -137,13 +130,8 @@ mod test {
let tx1 = create_test_tx(vec![create_test_txout(100, &address)]);
let tx2 = create_test_tx(vec![create_test_txout(100, &parse_addr(OTHER_ADDR))]);
let block = create_test_block(vec![tx1, tx2]);
let params = gen_params();

let result = filter_relevant_txs(
&block,
&[RelevantTxType::SpentToAddress(address)],
params.rollup(),
);
let result = filter_relevant_txs(&block, &[RelevantTxType::SpentToAddress(address)]);
assert_eq!(result, vec![0]); // Only tx1 matches
}

Expand Down Expand Up @@ -183,25 +171,18 @@ mod test {
let rollup_name = "TestRollup".to_string();
let tx = create_inscription_tx(rollup_name.clone());
let block = create_test_block(vec![tx]);
let params = gen_params();
let result = filter_relevant_txs(
&block,
&[RelevantTxType::RollupInscription(rollup_name)],
params.rollup(),
);
let result = filter_relevant_txs(&block, &[RelevantTxType::RollupInscription(rollup_name)]);
assert_eq!(result, vec![0], "Should filter valid rollup name");

// Test with invalid name
let rollup_name = "TestRollup".to_string();
let tx = create_inscription_tx(rollup_name.clone());
let block = create_test_block(vec![tx]);
let params = gen_params();
let result = filter_relevant_txs(
&block,
&[RelevantTxType::RollupInscription(
"invalid_name".to_string(),
)],
params.rollup(),
);
assert!(result.is_empty(), "Should filter out invalid name");
}
Expand All @@ -212,25 +193,18 @@ mod test {
let tx1 = create_test_tx(vec![create_test_txout(1000, &parse_addr(OTHER_ADDR))]);
let tx2 = create_test_tx(vec![create_test_txout(10000, &parse_addr(OTHER_ADDR))]);
let block = create_test_block(vec![tx1, tx2]);
let params = gen_params();

let result = filter_relevant_txs(
&block,
&[RelevantTxType::SpentToAddress(address)],
params.rollup(),
);
let result = filter_relevant_txs(&block, &[RelevantTxType::SpentToAddress(address)]);
assert!(result.is_empty()); // No transactions match
}

#[test]
fn test_filter_relevant_txs_empty_block() {
let block = create_test_block(vec![]);
let params = gen_params();

let result = filter_relevant_txs(
&block,
&[RelevantTxType::SpentToAddress(parse_addr(RELEVANT_ADDR))],
params.rollup(),
);
assert!(result.is_empty()); // No transactions match
}
Expand All @@ -242,13 +216,8 @@ mod test {
let tx2 = create_test_tx(vec![create_test_txout(100, &parse_addr(OTHER_ADDR))]);
let tx3 = create_test_tx(vec![create_test_txout(1000, &address)]);
let block = create_test_block(vec![tx1, tx2, tx3]);
let params = gen_params();

let result = filter_relevant_txs(
&block,
&[RelevantTxType::SpentToAddress(address)],
params.rollup(),
);
let result = filter_relevant_txs(&block, &[RelevantTxType::SpentToAddress(address)]);
assert_eq!(result, vec![0, 2]); // First and third txs match
}
}
20 changes: 9 additions & 11 deletions crates/btcio/src/reader/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
};

use alpen_express_db::traits::Database;
use alpen_express_primitives::params::{Params, RollupParams};
use alpen_express_primitives::params::Params;
use alpen_express_status::StatusTx;
use anyhow::bail;
use bitcoin::BlockHash;
Expand Down Expand Up @@ -84,7 +84,6 @@ async fn do_reader_task<D: Database + 'static>(
&relevant_tx_types,
&mut state,
&mut status_updates,
params.rollup(),
)
.instrument(poll_span)
.await
Expand Down Expand Up @@ -123,9 +122,14 @@ fn derive_relevant_tx_types<D: Database + 'static>(
) -> anyhow::Result<Vec<RelevantTxType>> {
// TODO: Figure out how to do it from chainstate provider
// For now we'll just go with filtering Inscription transactions
let rollup = params.rollup();
Ok(vec![
RelevantTxType::RollupInscription(params.rollup().rollup_name.clone()),
RelevantTxType::Deposit,
RelevantTxType::RollupInscription(rollup.rollup_name.clone()),
RelevantTxType::Deposit(
rollup.rollup_name.clone(),
rollup.deposit_address_length,
rollup.deposit_quantity,
),
])

Check warning on line 133 in crates/btcio/src/reader/query.rs

View check run for this annotation

Codecov / codecov/patch

crates/btcio/src/reader/query.rs#L125-L133

Added lines #L125 - L133 were not covered by tests
}

Expand Down Expand Up @@ -168,7 +172,6 @@ async fn poll_for_new_blocks(
relevant_tx_types: &[RelevantTxType],
state: &mut ReaderState,
status_updates: &mut Vec<L1StatusUpdate>,
params: &RollupParams,
) -> anyhow::Result<()> {
let chain_info = client.get_blockchain_info().await?;
status_updates.push(L1StatusUpdate::RpcConnected(true));
Expand Down Expand Up @@ -203,8 +206,6 @@ async fn poll_for_new_blocks(

// Now process each block we missed.
let scan_start_height = state.next_height();
println!("the scan height is {}", scan_start_height);
println!("the client height is {}", client_height);
for fetch_height in scan_start_height..=client_height {
let l1blkid = match fetch_and_process_block(
fetch_height,
Expand All @@ -213,7 +214,6 @@ async fn poll_for_new_blocks(
state,
status_updates,
relevant_tx_types,
params,
)
.await
{
Expand Down Expand Up @@ -258,13 +258,11 @@ async fn fetch_and_process_block(
state: &mut ReaderState,
status_updates: &mut Vec<L1StatusUpdate>,
relevant_tx_types: &[RelevantTxType],
params: &RollupParams,
) -> anyhow::Result<BlockHash> {
let block = client.get_block_at(height).await?;
let txs = block.txdata.len();

let filtered_txs = filter_relevant_txs(&block, relevant_tx_types, params);
println!("we have the filtered transaction as {:?}", filtered_txs);
let filtered_txs = filter_relevant_txs(&block, relevant_tx_types);
let block_data = BlockData::new(height, block, filtered_txs);
let l1blkid = block_data.block().block_hash();
trace!(%l1blkid, %height, %txs, "fetched block from client");
Expand Down
2 changes: 1 addition & 1 deletion crates/chaintsn/src/transition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ fn process_deposit_transaction(
let raw_tx = tx.tx().tx_data();
let constructed_tx = bitcoin::consensus::deserialize::<Transaction>(raw_tx).unwrap();
// convert raw data to DepositTx which is wrapper for Deposit Transaction
let deposit_tx_config = DepositTxConfig::new(params);
let deposit_tx_config = DepositTxConfig::from_params(params);
let deposit_info = extract_deposit_info(&constructed_tx, &deposit_tx_config).ok();

Check warning on line 163 in crates/chaintsn/src/transition.rs

View check run for this annotation

Codecov / codecov/patch

crates/chaintsn/src/transition.rs#L152-L163

Added lines #L152 - L163 were not covered by tests

if let Some(info) = deposit_info {
Expand Down
15 changes: 1 addition & 14 deletions crates/consensus-logic/src/duty/block_assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,6 @@ fn prepare_l1_segment(
for (h, _b) in unacc_blocks {
let rec = load_header_record(h, l1_prov)?;
let deposit_update_tx = extract_deposit_update_tx(h, l1_prov, params)?;
if deposit_update_tx.is_empty() {
println!("got ourselves a deposit tx {:?}", deposit_update_tx);
}
payloads.push(L1HeaderPayload::new_bare(h, rec, &deposit_update_tx));

Check warning on line 164 in crates/consensus-logic/src/duty/block_assembly.rs

View check run for this annotation

Codecov / codecov/patch

crates/consensus-logic/src/duty/block_assembly.rs#L163-L164

Added lines #L163 - L164 were not covered by tests
}

Expand All @@ -183,8 +180,6 @@ fn prepare_l1_segment(
// at a reorg exactly on the transition block
trace!("computing pivot");

println!("{:?}", unacc_blocks);
println!("{:?}", maturing_blocks);
let Some((pivot_h, _pivot_id)) = find_pivot_block_height(&unacc_blocks, &maturing_blocks)
else {
// Then we're really screwed.
Expand All @@ -201,11 +196,7 @@ fn prepare_l1_segment(
let mut payloads = Vec::new();
for (h, _b) in fresh_blocks {
let rec = load_header_record(*h, l1_prov)?;
println!("working for the height {}", h);
let deposit_update_tx = extract_deposit_update_tx(*h, l1_prov, params)?;
if deposit_update_tx.is_empty() {
println!("got ourselves a deposit tx {:?}", deposit_update_tx);
}
payloads.push(L1HeaderPayload::new_bare(*h, rec, &deposit_update_tx));

Check warning on line 200 in crates/consensus-logic/src/duty/block_assembly.rs

View check run for this annotation

Codecov / codecov/patch

crates/consensus-logic/src/duty/block_assembly.rs#L199-L200

Added lines #L199 - L200 were not covered by tests
}

Expand Down Expand Up @@ -233,8 +224,6 @@ fn extract_deposit_update_tx(
.get_block_txs(h)?
.ok_or(Error::MissingL1BlockHeight(h))?;

Check warning on line 225 in crates/consensus-logic/src/duty/block_assembly.rs

View check run for this annotation

Codecov / codecov/patch

crates/consensus-logic/src/duty/block_assembly.rs#L218-L225

Added lines #L218 - L225 were not covered by tests

println!("got tx ref {:?}", relevant_tx_ref);

let mut deposit_update_tx = Vec::new();
for tx_ref in relevant_tx_ref {
let tx = l1_prov.get_tx(tx_ref)?.ok_or(Error::MissingL1Tx)?;
Expand All @@ -243,9 +232,7 @@ fn extract_deposit_update_tx(
let txn = bitcoin::consensus::deserialize::<Transaction>(tx.tx_data())
.map_err(|e| Error::TxDeserializationFailed(h))?;

Check warning on line 233 in crates/consensus-logic/src/duty/block_assembly.rs

View check run for this annotation

Codecov / codecov/patch

crates/consensus-logic/src/duty/block_assembly.rs#L232-L233

Added lines #L232 - L233 were not covered by tests

println!("got txn {:?}", txn);

let deposit_tx_config: DepositTxConfig = DepositTxConfig::new(params.rollup());
let deposit_tx_config: DepositTxConfig = DepositTxConfig::from_params(params.rollup());
let deposit_parser = extract_deposit_info(&txn, &deposit_tx_config).ok();

if deposit_parser.is_some() {
Expand Down
2 changes: 1 addition & 1 deletion crates/db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ mocks = ["mockall"]
stubs = []

[dev-dependencies]
serde_json = { workspace = true }
alpen-test-utils = { workspace = true }
serde_json = { workspace = true }
2 changes: 1 addition & 1 deletion crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ alpen-test-utils = { workspace = true }

[features]
default = ["std", "rand"]
std = ["dep:secp256k1"]
rand = ["std", "dep:rand"]
std = ["dep:secp256k1"]

0 comments on commit d696e1d

Please sign in to comment.