Skip to content

Commit

Permalink
feat: unitest for omnilock success
Browse files Browse the repository at this point in the history
  • Loading branch information
driftluo committed Apr 9, 2024
1 parent 62baa72 commit 2554656
Show file tree
Hide file tree
Showing 17 changed files with 165 additions and 78 deletions.
16 changes: 12 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
[package]
name = "ckb-sdk"
version = "3.1.1"
authors = [ "Linfeng Qian <[email protected]>", "Nervos Core Dev <[email protected]>" ]
authors = [
"Linfeng Qian <[email protected]>",
"Nervos Core Dev <[email protected]>",
]
edition = "2018"
license = "MIT"
description = "Rust SDK for CKB"
Expand All @@ -17,7 +20,10 @@ anyhow = "1.0.63"
bech32 = "0.8.1"
derive-getters = "0.2.1"
log = "0.4.6"
reqwest = { version = "0.11", default-features = false, features = [ "json", "blocking" ] }
reqwest = { version = "0.11", default-features = false, features = [
"json",
"blocking",
] }
secp256k1 = { version = "0.24", features = ["recovery"] }
tokio-util = { version = "0.7.7", features = ["codec"] }
tokio = { version = "1" }
Expand Down Expand Up @@ -50,14 +56,16 @@ sparse-merkle-tree = "0.6.1"
lazy_static = "1.3.0"

[features]
default = ["default-tls"]
default = ["default-tls", "test", "rand"]
default-tls = ["reqwest/default-tls"]
native-tls-vendored = ["reqwest/native-tls-vendored"]
rustls-tls = ["reqwest/rustls-tls"]
test = []

[dev-dependencies]
clap = { version = "=4.4.18", features = [ "derive" ] } # TODO clap v4.5 requires rustc v1.74.0+
clap = { version = "=4.4.18", features = [
"derive",
] } # TODO clap v4.5 requires rustc v1.74.0+
httpmock = "0.6"
async-global-executor = "2.3.1"
hex = "0.4"
Binary file modified src/test-data/omni_lock
Binary file not shown.
7 changes: 5 additions & 2 deletions src/test_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ impl Context {
/// with secp256k1_data and map the script id to dep_group cell_dep. The
/// contracts can only be referenced by data hash and with
/// hash_type="data1".
pub fn new(block: &BlockView, contracts: Vec<(&[u8], bool)>) -> Context {
pub fn new(block: &BlockView, contracts: Vec<(&[u8], bool)>) -> (Context, Vec<OutPoint>) {
let block_number: u64 = block.number();
assert_eq!(block_number, 0);
let cell_dep_resolver = DefaultCellDepResolver::from_genesis(block).expect("genesis info");
Expand Down Expand Up @@ -126,11 +126,14 @@ impl Context {
}
}

let mut contract_outpoints = Vec::with_capacity(contracts.len());

if !contracts.is_empty() {
let secp_data_out_point = OutPoint::new(block.transaction(0).unwrap().hash(), 3);
for (bin, is_lock) in contracts {
let data_hash = H256::from(blake2b_256(bin));
let out_point = ctx.deploy_cell(Bytes::from(bin.to_vec()));
contract_outpoints.push(out_point.clone());
if is_lock {
let out_points: OutPointVec =
vec![secp_data_out_point.clone(), out_point].pack();
Expand All @@ -145,7 +148,7 @@ impl Context {
}
}
ctx.add_header(block.header());
ctx
(ctx, contract_outpoints)
}

/// Adds or updates a live cell in the set.
Expand Down
11 changes: 7 additions & 4 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use ckb_types::{
bytes::Bytes,
core::{BlockView, ScriptHashType},
h160, h256,
packed::Script,
packed::{OutPoint, Script},
prelude::*,
H160, H256,
};
Expand Down Expand Up @@ -111,13 +111,16 @@ fn build_omnilock_script(cfg: &OmniLockConfig) -> Script {
.build()
}

fn init_context(contracts: Vec<(&[u8], bool)>, live_cells: Vec<(Script, Option<u64>)>) -> Context {
fn init_context(
contracts: Vec<(&[u8], bool)>,
live_cells: Vec<(Script, Option<u64>)>,
) -> (Context, Vec<OutPoint>) {
// ckb-cli --url https://testnet.ckb.dev rpc get_block_by_number --number 0 --output-format json --raw-data > genensis_block.json
let genesis_block: json_types::BlockView = serde_json::from_str(GENESIS_JSON).unwrap();
let genesis_block: BlockView = genesis_block.into();
let mut ctx = Context::new(&genesis_block, contracts);
let (mut ctx, outpoints) = Context::new(&genesis_block, contracts);
for (lock, capacity_opt) in live_cells {
ctx.add_simple_live_cell(random_out_point(), lock, capacity_opt);
}
ctx
(ctx, outpoints)
}
62 changes: 55 additions & 7 deletions src/tests/transaction/omnilock.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
use ckb_crypto::secp::{Pubkey, SECP256K1};
use ckb_types::{packed::CellOutput, prelude::*};
use ckb_hash::blake2b_256;
use ckb_types::{
core::DepType,
packed::{CellOutput, OutPoint},
prelude::*,
H256,
};

use crate::{
constants::ONE_CKB,
Expand All @@ -9,7 +15,13 @@ use crate::{
},
transaction::{
builder::{CkbTransactionBuilder, SimpleTransactionBuilder},
handler::{omnilock::OmnilockScriptContext, HandlerContexts},
handler::{
multisig::Secp256k1Blake160MultisigAllScriptHandler,
omnilock::{OmnilockScriptContext, OmnilockScriptHandler},
sighash::Secp256k1Blake160SighashAllScriptHandler,
typeid::TypeIdHandler,
HandlerContexts,
},
input::InputIterator,
signer::{SignContexts, TransactionSigner},
TransactionBuilderConfiguration,
Expand All @@ -19,8 +31,40 @@ use crate::{
NetworkInfo,
};

fn test_omnilock_config(omnilock_outpoint: OutPoint) -> TransactionBuilderConfiguration {
let network_info = NetworkInfo::testnet();
let mut configuration =
TransactionBuilderConfiguration::new_with_empty_handlers(network_info.clone());
let mut omni_lock_handler = OmnilockScriptHandler::new_with_network(&network_info).unwrap();

omni_lock_handler.set_lock_script_id(crate::ScriptId::new_data1(H256::from(blake2b_256(
OMNILOCK_BIN,
))));
omni_lock_handler.set_cell_deps(vec![
crate::transaction::handler::cell_dep!(
"0xf8de3bb47d055cdf460d93a2a6e1b05f7432f9777c8c474abf4eec1d4aee5d37",
0u32,
DepType::DepGroup
),
ckb_types::packed::CellDep::new_builder()
.out_point(omnilock_outpoint)
.dep_type(DepType::Code.into())
.build(),
]);

configuration.register_script_handler(Box::new(
Secp256k1Blake160SighashAllScriptHandler::new_with_network(&network_info).unwrap(),
));
configuration.register_script_handler(Box::new(
Secp256k1Blake160MultisigAllScriptHandler::new_with_network(&network_info).unwrap(),
));
configuration.register_script_handler(Box::new(TypeIdHandler));
configuration.register_script_handler(Box::new(omni_lock_handler));

configuration
}

#[test]
#[ignore]
fn test_transfer_from_omnilock_ethereum() {
let network_info = NetworkInfo::testnet();
let account0_key = secp256k1::SecretKey::from_slice(ACCOUNT0_KEY.as_bytes()).unwrap();
Expand All @@ -30,7 +74,7 @@ fn test_transfer_from_omnilock_ethereum() {
let sender = build_omnilock_script(&cfg);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx = init_context(
let (ctx, mut outpoints) = init_context(
vec![(OMNILOCK_BIN, true)],
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand All @@ -39,8 +83,7 @@ fn test_transfer_from_omnilock_ethereum() {
],
);

let configuration =
TransactionBuilderConfiguration::new_with_network(network_info.clone()).unwrap();
let configuration = test_omnilock_config(outpoints.pop().unwrap());

let iterator = InputIterator::new_with_cell_collector(
vec![sender.clone()],
Expand All @@ -65,6 +108,11 @@ fn test_transfer_from_omnilock_ethereum() {
println!("tx: {}", serde_json::to_string_pretty(&json_tx).unwrap());

TransactionSigner::new(&network_info)
// use unitest lock to verify
.insert_unlocker(
crate::ScriptId::new_data1(H256::from(blake2b_256(OMNILOCK_BIN))),
crate::transaction::signer::omnilock::OmnilockSigner {},
)
.sign_transaction(
&mut tx_with_groups,
&SignContexts::new_omnilock(vec![account0_key], cfg),
Expand All @@ -78,7 +126,7 @@ fn test_transfer_from_omnilock_ethereum() {
let script_groups = tx_with_groups.script_groups.clone();
assert_eq!(script_groups.len(), 1);
assert_eq!(tx.header_deps().len(), 0);
assert_eq!(tx.cell_deps().len(), 1);
assert_eq!(tx.cell_deps().len(), 2);
assert_eq!(tx.inputs().len(), 2);
for out_point in tx.input_pts_iter() {
assert_eq!(ctx.get_input(&out_point).unwrap().0.lock(), sender);
Expand Down
2 changes: 1 addition & 1 deletion src/tests/transaction/sighash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
fn test_transfer_from_sighash() {
let sender = build_sighash_script(ACCOUNT1_ARG);
let receiver = build_sighash_script(ACCOUNT2_ARG);
let ctx = init_context(
let (ctx, _) = init_context(
Vec::new(),
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down
2 changes: 1 addition & 1 deletion src/tests/transaction/typeid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
#[test]
fn test_deploy_id() {
let sender = build_sighash_script(ACCOUNT1_ARG);
let ctx = init_context(Vec::new(), vec![(sender.clone(), Some(10_0000 * ONE_CKB))]);
let (ctx, _) = init_context(Vec::new(), vec![(sender.clone(), Some(10_0000 * ONE_CKB))]);

let network_info = NetworkInfo::testnet();
let type_script =
Expand Down
2 changes: 1 addition & 1 deletion src/tests/tx_builder/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn test_transfer_to_acp() {
.hash_type(ScriptHashType::Data1.into())
.args(Bytes::from(ACCOUNT2_ARG.0.to_vec()).pack())
.build();
let ctx = init_context(
let (ctx, _) = init_context(
vec![(ACP_BIN, true)],
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down
4 changes: 2 additions & 2 deletions src/tests/tx_builder/cheque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn test_cheque_claim() {
.hash_type(ScriptHashType::Data1.into())
.args(Bytes::from(vec![9u8; 32]).pack())
.build();
let mut ctx = init_context(
let (mut ctx, _) = init_context(
vec![(CHEQUE_BIN, true), (SUDT_BIN, false)],
vec![
(receiver.clone(), Some(100 * ONE_CKB)),
Expand Down Expand Up @@ -156,7 +156,7 @@ fn test_cheque_withdraw() {
.hash_type(ScriptHashType::Data1.into())
.args(Bytes::from(vec![9u8; 32]).pack())
.build();
let mut ctx = init_context(
let (mut ctx, _) = init_context(
vec![(CHEQUE_BIN, true), (SUDT_BIN, false)],
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down
67 changes: 41 additions & 26 deletions src/tests/tx_builder/cycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,13 @@ fn test_change_enough(loops: u64) {
let sender = build_script(loops);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx: &'static Context = Box::leak(Box::new(init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB))],
)));
let ctx: &'static Context = Box::leak(Box::new(
init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB))],
)
.0,
));

let output = CellOutput::new_builder()
.capacity((140 * ONE_CKB).pack())
Expand Down Expand Up @@ -145,10 +148,13 @@ fn vsize_big_and_fee_enough() {
let sender = build_script(loops);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx: &'static Context = Box::leak(Box::new(init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB + 123_456))],
)));
let ctx: &'static Context = Box::leak(Box::new(
init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB + 123_456))],
)
.0,
));

let output = CellOutput::new_builder()
.capacity((200 * ONE_CKB).pack())
Expand Down Expand Up @@ -191,10 +197,13 @@ fn vsize_big_and_fee_not_enough() {
let sender = build_script(loops);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx: &'static Context = Box::leak(Box::new(init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB + 456))],
)));
let ctx: &'static Context = Box::leak(Box::new(
init_context(
vec![(CYCLE_BIN, true)],
vec![(sender.clone(), Some(200 * ONE_CKB + 456))],
)
.0,
));

let output = CellOutput::new_builder()
.capacity((200 * ONE_CKB).pack())
Expand Down Expand Up @@ -224,13 +233,16 @@ fn vsize_big_and_can_find_more_capacity() {
let sender = build_script(loops);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx: &'static Context = Box::leak(Box::new(init_context(
vec![(CYCLE_BIN, true)],
vec![
(sender.clone(), Some(200 * ONE_CKB + 286)), // 286 is fee calculated from tx_size
(sender.clone(), Some(70 * ONE_CKB)),
],
)));
let ctx: &'static Context = Box::leak(Box::new(
init_context(
vec![(CYCLE_BIN, true)],
vec![
(sender.clone(), Some(200 * ONE_CKB + 286)), // 286 is fee calculated from tx_size
(sender.clone(), Some(70 * ONE_CKB)),
],
)
.0,
));

let output = CellOutput::new_builder()
.capacity((200 * ONE_CKB).pack())
Expand Down Expand Up @@ -314,13 +326,16 @@ fn vsize_big_and_cannot_find_more_capacity() {
let sender = build_script(loops);
let receiver = build_sighash_script(ACCOUNT2_ARG);

let ctx: &'static Context = Box::leak(Box::new(init_context(
vec![(CYCLE_BIN, true)],
vec![
(sender.clone(), Some(200 * ONE_CKB + 286)), // 286 is fee calculated from tx_size
(sender.clone(), Some(49 * ONE_CKB)),
],
)));
let ctx: &'static Context = Box::leak(Box::new(
init_context(
vec![(CYCLE_BIN, true)],
vec![
(sender.clone(), Some(200 * ONE_CKB + 286)), // 286 is fee calculated from tx_size
(sender.clone(), Some(49 * ONE_CKB)),
],
)
.0,
));

let output = CellOutput::new_builder()
.capacity((200 * ONE_CKB).pack())
Expand Down
6 changes: 3 additions & 3 deletions src/tests/tx_builder/dao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::test_util::random_out_point;
#[test]
fn test_dao_deposit() {
let sender = build_sighash_script(ACCOUNT1_ARG);
let ctx = init_context(
let (ctx, _) = init_context(
Vec::new(),
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down Expand Up @@ -95,7 +95,7 @@ fn test_dao_deposit() {
#[test]
fn test_dao_prepare() {
let sender = build_sighash_script(ACCOUNT1_ARG);
let mut ctx = init_context(
let (mut ctx, _) = init_context(
Vec::new(),
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down Expand Up @@ -184,7 +184,7 @@ fn test_dao_prepare() {
#[test]
fn test_dao_withdraw() {
let sender = build_sighash_script(ACCOUNT1_ARG);
let mut ctx = init_context(
let (mut ctx, _) = init_context(
Vec::new(),
vec![
(sender.clone(), Some(100 * ONE_CKB)),
Expand Down
Loading

0 comments on commit 2554656

Please sign in to comment.