Skip to content

Commit

Permalink
[test] Improve bitcoin block tester
Browse files Browse the repository at this point in the history
  • Loading branch information
jolestar committed Aug 21, 2024
1 parent 8e5ae9d commit 94c01d4
Show file tree
Hide file tree
Showing 9 changed files with 117 additions and 46 deletions.
37 changes: 34 additions & 3 deletions crates/rooch-framework-tests/src/binding_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ use move_core_types::vm_status::KeptVMStatus;
use moveos_config::DataDirPath;
use moveos_store::MoveOSStore;
use moveos_types::function_return_value::FunctionResult;
use moveos_types::h256::H256;
use moveos_types::module_binding::MoveFunctionCaller;
use moveos_types::moveos_std::event::Event;
use moveos_types::moveos_std::object::ObjectMeta;
use moveos_types::moveos_std::tx_context::TxContext;
use moveos_types::state::{ObjectChange, StateChangeSet};
use moveos_types::state_resolver::{RootObjectResolver, StateReaderExt};
use moveos_types::state::{FieldKey, ObjectChange, ObjectState, StateChangeSet};
use moveos_types::state_resolver::{
RootObjectResolver, StateKV, StateReaderExt, StateResolver, StatelessResolver,
};
use moveos_types::transaction::{FunctionCall, VerifiedMoveOSTransaction};
use rooch_config::RoochOpt;
use rooch_db::RoochDB;
Expand Down Expand Up @@ -52,6 +56,7 @@ pub struct RustBindingTest {
root: ObjectMeta,
rooch_db: RoochDB,
pub registry_service: RegistryService,
events: Vec<Event>,
}

impl RustBindingTest {
Expand Down Expand Up @@ -105,6 +110,7 @@ impl RustBindingTest {
reader_executor,
rooch_db,
registry_service,
events: vec![],
})
}

Expand Down Expand Up @@ -207,7 +213,7 @@ impl RustBindingTest {
) -> Result<ExecuteTransactionResult> {
let result = self.executor.execute(tx)?;
self.root = result.transaction_info.root_metadata();

self.events.extend(result.output.events.clone());
self.reader_executor
.refresh_state(self.root.clone(), false)?;
Ok(result)
Expand Down Expand Up @@ -237,6 +243,10 @@ impl RustBindingTest {
.map(|account| account.value.sequence_number)
.unwrap_or(0))
}

pub fn events(&self) -> &Vec<Event> {
&self.events
}
}

impl MoveFunctionCaller for RustBindingTest {
Expand All @@ -253,3 +263,24 @@ impl MoveFunctionCaller for RustBindingTest {
Ok(result)
}
}

impl StateResolver for RustBindingTest {
fn root(&self) -> &ObjectMeta {
&self.root
}
}

impl StatelessResolver for RustBindingTest {
fn get_field_at(&self, state_root: H256, key: &FieldKey) -> Result<Option<ObjectState>> {
self.resolver().get_field_at(state_root, key)
}

fn list_fields_at(
&self,
state_root: H256,
cursor: Option<FieldKey>,
limit: usize,
) -> Result<Vec<StateKV>> {
self.resolver().list_fields_at(state_root, cursor, limit)
}
}
38 changes: 32 additions & 6 deletions crates/rooch-framework-tests/src/bitcoin_block_tester.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@ use moveos_types::{
timestamp::Timestamp,
},
state::{MoveState, MoveType, ObjectChange, ObjectState},
state_resolver::StateResolver,
};
use rooch_relayer::actor::bitcoin_client_proxy::BitcoinClientProxy;
use rooch_types::{
bitcoin::utxo::{BitcoinUTXOStore, UTXO},
bitcoin::{
ord::InscriptionID,
utxo::{BitcoinUTXOStore, UTXO},
},
genesis_config,
into_address::IntoAddress,
rooch_network::{BuiltinChainID, RoochNetwork},
Expand Down Expand Up @@ -65,6 +69,11 @@ impl BitcoinBlockTester {
//TODO verify inscription in state with ord rpc result.
Ok(())
}

pub fn get_inscription(&self, inscription_id: &InscriptionID) -> Result<Option<ObjectState>> {
let object_id = inscription_id.object_id();
self.binding_test.get_object(&object_id)
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -96,6 +105,7 @@ impl BitcoinTesterGenesis {
pub struct TesterGenesisBuilder {
bitcoin_client: BitcoinClientProxy,
blocks: Vec<(usize, Block)>,
block_txids: HashSet<Txid>,
utxo_store_change: ObjectChange,
}

Expand All @@ -104,22 +114,31 @@ impl TesterGenesisBuilder {
Ok(Self {
bitcoin_client,
blocks: vec![],
block_txids: HashSet::new(),
utxo_store_change: ObjectChange::meta(BitcoinUTXOStore::genesis_object().metadata),
})
}

pub async fn add_block(mut self, block_hash: BlockHash) -> Result<Self> {
//TODO support multiple blocks
ensure!(
self.blocks.is_empty(),
"GenesisBuilder can only add one block"
);
let block = self.bitcoin_client.get_block(block_hash).await?;
let block_header_result = self
.bitcoin_client
.get_block_header_info(block_hash)
.await?;
debug!("Add block: {:?}", block_header_result);
if !self.blocks.is_empty() {
let last_block = self.blocks.last().unwrap();
ensure!(
last_block.0 < block_header_result.height,
"Block height should be incremental from {} to {}",
last_block.0,
block_header_result.height
);
}
for tx in &block.txdata {
self.block_txids.insert(tx.txid());
}

let depdent_txids = block
.txdata
.iter()
Expand All @@ -136,6 +155,10 @@ impl TesterGenesisBuilder {
if txid == Txid::all_zeros() {
continue;
}
// Skip if tx already in block
if self.block_txids.contains(&txid) {
continue;
}
debug!("Get tx: {:?}", txid);
let tx = self.bitcoin_client.get_raw_transaction(txid).await?;
depdent_txs.insert(txid, tx);
Expand All @@ -146,6 +169,9 @@ impl TesterGenesisBuilder {
if input.previous_output.txid == Txid::all_zeros() {
continue;
}
if self.block_txids.contains(&input.previous_output.txid) {
continue;
}
let pre_tx = depdent_txs
.get(&input.previous_output.txid)
.ok_or_else(|| {
Expand Down
18 changes: 9 additions & 9 deletions crates/rooch-framework-tests/src/tests/bitcoin_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,16 @@ fn check_utxo(txs: Vec<Transaction>, binding_test: &binding_test::RustBindingTes
assert_eq!(utxo_object.value.value, tx_out.value.to_sat());
}

let ord_module = binding_test.as_module_binding::<rooch_types::bitcoin::ord::OrdModule>();

let inscriptions = txs
.iter()
.flat_map(|tx| {
let txid = tx.txid();
bitcoin_move::natives::ord::from_transaction(tx)
let rooch_btc_tx = rooch_types::bitcoin::types::Transaction::from(tx.clone());
ord_module
.from_transaction(&rooch_btc_tx, vec![], 0, 0)
.unwrap()
.into_iter()
.enumerate()
.map(move |(idx, i)| (txid, idx, i))
Expand All @@ -152,11 +157,9 @@ fn check_utxo(txs: Vec<Transaction>, binding_test: &binding_test::RustBindingTes
for (txid, index, inscription) in inscriptions {
let txid_address = txid.into_address();
let index = index as u32;
debug!(
"check inscription: txid: {}, index: {}",
txid_address, index
);
let inscription_id = InscriptionID::new(txid_address, index);
debug!("check inscription: {:?}", inscription_id);

let object_id = ord::derive_inscription_id(&inscription_id);
let inscription_state = moveos_resolver
.get_states(AccessPath::object(object_id))
Expand All @@ -173,10 +176,7 @@ fn check_utxo(txs: Vec<Transaction>, binding_test: &binding_test::RustBindingTes
let inscription_object = inscription_state.into_object::<Inscription>().unwrap();
assert_eq!(inscription_object.value.txid, txid.into_address());
assert_eq!(inscription_object.value.index, index);
assert_eq!(
inscription_object.value.body,
inscription.payload.body.unwrap_or_default()
);
assert_eq!(inscription_object.value.body, inscription.body,);
}
}

Expand Down
36 changes: 36 additions & 0 deletions crates/rooch-framework-tests/src/tests/bitcoin_tester_test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use std::str::FromStr;

use rooch_types::bitcoin::ord::{Inscription, InscriptionID};
use tracing::{debug, warn};

use crate::bitcoin_block_tester::BitcoinBlockTester;

// This test for testing BitcoinBlockTester
Expand All @@ -12,3 +17,34 @@ async fn test_block_100000() {
tester.verify_utxo().unwrap();
tester.verify_inscriptions().unwrap();
}

#[tokio::test]
async fn test_block_790964() {
let _ = tracing_subscriber::fmt::try_init();

if cfg!(debug_assertions) {
warn!("test_block_790964 is ignored in debug mode, please run it in release mode");
return;
}

let mut tester = BitcoinBlockTester::new(790964).unwrap();
tester.execute().unwrap();
tester.verify_utxo().unwrap();
tester.verify_inscriptions().unwrap();
let inscription_id = InscriptionID::from_str(
"4b8111663106c242da8580ba38c36f261287b9c35b1aa5974f4c14306905e720i0",
)
.unwrap();
let inscription_opt = tester.get_inscription(&inscription_id).unwrap();
assert!(inscription_opt.is_some());
let inscription_obj = inscription_opt.unwrap();
let inscription = inscription_obj.value_as::<Inscription>().unwrap();
debug!("Inscription: {:?}", inscription);
assert_eq!(inscription.id(), inscription_id);
// Because we do not execute bitcoin block from ordinals genesis, so the inscription number and sequence number are not the same as the real inscription.
// let expected_inscription_number = 8706753u32;
// let expected_sequence_number = 8709019u32;
// assert_eq!(inscription.inscription_number, expected_inscription_number);
// assert_eq!(inscription.sequence_number, expected_sequence_number);
assert_eq!(inscription.offset, 0u64);
}
5 changes: 1 addition & 4 deletions crates/rooch-framework-tests/src/tests/brc20_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ fn decode_tx(btx_tx_hex: &str) {
output.script_pubkey.p2wpkh_script_code()
);
}
let inscriptions = bitcoin_move::natives::ord::from_transaction(&btc_tx);
for (i, inscription) in inscriptions.iter().enumerate() {
debug!("{}. inscription: {:?}", i, inscription);
}

//let binding_test = binding_test::RustBindingTest::new().unwrap();
//let brc20_module = binding_test.as_module_binding::<rooch_types::bitcoin::brc20::BRC20Module>();
//let move_btc_tx: rooch_types::bitcoin::types::Transaction = btc_tx.into();
Expand Down
23 changes: 3 additions & 20 deletions crates/rooch-framework-tests/src/tests/ord_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,36 +30,19 @@ fn decode_inscription(
output.script_pubkey.p2wpkh_script_code()
);
}
let inscriptions = bitcoin_move::natives::ord::from_transaction(&btc_tx);

let ord_module = binding_test.as_module_binding::<rooch_types::bitcoin::ord::OrdModule>();
let move_btc_tx: rooch_types::bitcoin::types::Transaction =
rooch_types::bitcoin::types::Transaction::from(btc_tx);

let inscriptions_from_move = ord_module
ord_module
.from_transaction(
&move_btc_tx,
input_utxo_values,
next_inscription_number,
next_sequence_number,
)
.unwrap();

for (i, (inscription, inscription_from_move)) in inscriptions
.into_iter()
.zip(inscriptions_from_move.clone())
.enumerate()
{
debug!(
"{}. inscription: {:?}, inscription_from_move:{:?}",
i, inscription, inscription_from_move
);
assert_eq!(
inscription.payload.body.unwrap_or_default(),
inscription_from_move.body
);
}
inscriptions_from_move
.unwrap()
}

#[tokio::test]
Expand All @@ -74,7 +57,7 @@ async fn test_8706753() {
);
let input_utxo_values = vec![3318u64];
let next_inscription_number = 8706753;
let next_sequence_number = 8706753;
let next_sequence_number = 8709019;
let inscribe_tx_id = btc_tx.txid();
let mut inscriptions = decode_inscription(
&mut binding_test,
Expand Down
Binary file not shown.
4 changes: 1 addition & 3 deletions crates/rooch-genesis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ include_dir = { workspace = true }


move-core-types = { workspace = true }
move-vm-runtime = { workspace = true }


move-vm-runtime = { workspace = true, features = ["stacktrace", "debugging", "testing"] }
moveos-types = { workspace = true }
moveos = { workspace = true }
moveos-store = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion moveos/moveos-verifier/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ move-binary-format = { workspace = true }
move-package = { workspace = true }
move-compiler = { workspace = true }
move-command-line-common = { workspace = true }
move-vm-runtime = { workspace = true }
move-vm-runtime = { workspace = true, features = ["stacktrace", "debugging", "testing"] }
move-vm-types = { workspace = true }
move-symbol-pool = { workspace = true }
move-ir-types = { workspace = true }
Expand Down

0 comments on commit 94c01d4

Please sign in to comment.