diff --git a/Cargo.lock b/Cargo.lock index 6adb7b2697..660966e311 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1031,6 +1031,7 @@ dependencies = [ "ckb-store", "ckb-sync", "ckb-tx-pool", + "ckb-types", "ckb-verification", "ckb-verification-traits", ] diff --git a/Makefile b/Makefile index 966a1090a8..7882a0524b 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .DEFAULT_GOAL:=help SHELL = /bin/sh MOLC := moleculec -MOLC_VERSION := 0.8.0 +MOLC_VERSION := 0.7.5 VERBOSE := $(if ${CI},--verbose,) CLIPPY_OPTS := -D warnings -D clippy::clone_on_ref_ptr -D clippy::redundant_clone -D clippy::enum_glob_use -D clippy::fallible_impl_from \ -A clippy::mutable_key_type -A clippy::upper_case_acronyms -A clippy::needless_return diff --git a/benches/benches/benchmarks/overall.rs b/benches/benches/benchmarks/overall.rs index 921bf85804..103cab0893 100644 --- a/benches/benches/benchmarks/overall.rs +++ b/benches/benches/benchmarks/overall.rs @@ -34,11 +34,11 @@ const SIZES: &[usize] = &[2usize]; fn block_assembler_config() -> BlockAssemblerConfig { let (_, _, secp_script) = secp_cell(); - let args = JsonBytes::from_bytes(secp_script.args().into()); + let args = JsonBytes::from_bytes(secp_script.args().unpack()); let hash_type = ScriptHashType::try_from(secp_script.hash_type()).expect("checked data"); BlockAssemblerConfig { - code_hash: secp_script.code_hash().into(), + code_hash: secp_script.code_hash().unpack(), hash_type: hash_type.into(), args, message: Default::default(), @@ -92,21 +92,21 @@ pub fn setup_chain(txs_size: usize) -> (Shared, ChainController) { .map(|i| { let data = Bytes::from(i.to_le_bytes().to_vec()); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(secp_script.clone()) .build(); TransactionBuilder::default() .input(CellInput::new(OutPoint::null(), 0)) .output(output.clone()) .output(output) - .output_data(&data) - .output_data(&data) + .output_data(data.pack()) + .output_data(data.pack()) .build() }) .collect(); let genesis_block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .dao(dao) .transaction(tx) .transactions(transactions) @@ -207,7 +207,7 @@ fn bench(c: &mut Criterion) { let raw_header = raw_block.header().raw(); let header = Header::new_builder() .raw(raw_header) - .nonce(random::()) + .nonce(random::().pack()) .build(); let block = raw_block.as_builder().header(header).build().into_view(); diff --git a/benches/benches/benchmarks/resolve.rs b/benches/benches/benchmarks/resolve.rs index a250781623..37ec9d11c3 100644 --- a/benches/benches/benchmarks/resolve.rs +++ b/benches/benches/benchmarks/resolve.rs @@ -33,29 +33,32 @@ const DEFAULT_CODE_HASH: H256 = fn script() -> Script { Script::new_builder() - .code_hash(DEFAULT_CODE_HASH) - .args(Bytes::from(PUBKEY_HASH.as_bytes())) - .hash_type(ScriptHashType::Type) + .code_hash(DEFAULT_CODE_HASH.pack()) + .args(Bytes::from(PUBKEY_HASH.as_bytes()).pack()) + .hash_type(ScriptHashType::Type.into()) .build() } fn cell_dep(genesis: &BlockView) -> CellDep { let tx_hash = genesis.transaction(1).unwrap().hash(); - let out_point = OutPoint::new_builder().tx_hash(tx_hash).index(0u32).build(); + let out_point = OutPoint::new_builder() + .tx_hash(tx_hash) + .index(0u32.pack()) + .build(); CellDep::new_builder() .out_point(out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build() } fn block_assembler_config() -> BlockAssemblerConfig { let secp_script = script(); - let args = JsonBytes::from_bytes(secp_script.args().into()); + let args = JsonBytes::from_bytes(secp_script.args().unpack()); let hash_type = ScriptHashType::try_from(secp_script.hash_type()).expect("checked data"); BlockAssemblerConfig { - code_hash: secp_script.code_hash().into(), + code_hash: secp_script.code_hash().unpack(), hash_type: hash_type.into(), args, message: Default::default(), diff --git a/benches/benches/benchmarks/util.rs b/benches/benches/benchmarks/util.rs index 9a5afc336d..a9f64d0a50 100644 --- a/benches/benches/benchmarks/util.rs +++ b/benches/benches/benchmarks/util.rs @@ -49,18 +49,18 @@ pub fn new_always_success_chain(txs_size: usize, chains_num: usize) -> Chains { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(data) + .output_data(data.pack()) .build() }) .collect(); let genesis_block = BlockBuilder::default() .dao(dao) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .transaction(tx) .transactions(transactions) .build(); @@ -92,7 +92,7 @@ pub fn create_always_success_tx() -> TransactionView { .witness(script.clone().into_witness()) .input(CellInput::new(OutPoint::null(), 0)) .output(always_success_cell.clone()) - .output_data(always_success_cell_data) + .output_data(always_success_cell_data.pack()) .build() } @@ -110,11 +110,11 @@ pub fn create_always_success_cellbase(shared: &Shared, parent: &HeaderView) -> T builder .output( CellOutput::new_builder() - .capacity(capacity) + .capacity(capacity.pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build() } } @@ -185,11 +185,11 @@ pub fn gen_always_success_block( .transactions(transactions) .proposals(proposals) .parent_hash(p_block.hash()) - .number(number) - .timestamp(timestamp) - .compact_target(epoch.compact_target()) - .epoch(epoch.number_with_fraction(number)) - .nonce(random::()) + .number(number.pack()) + .timestamp(timestamp.pack()) + .compact_target(epoch.compact_target().pack()) + .epoch(epoch.number_with_fraction(number).pack()) + .nonce(random::().pack()) .dao(dao) .build(); @@ -208,7 +208,7 @@ lazy_static! { let data: Bytes = raw_data.to_vec().into(); let cell = CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); (cell, data) }; @@ -219,13 +219,13 @@ lazy_static! { let data: Bytes = raw_data.to_vec().into(); let cell = CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); let script = Script::new_builder() .code_hash(CellOutput::calc_data_hash(&data)) - .args(Bytes::from(PUBKEY_HASH.as_bytes())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(PUBKEY_HASH.as_bytes()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); (cell, data, script) @@ -244,7 +244,7 @@ pub fn create_secp_tx() -> TransactionView { let (ref secp_data_cell, ref secp_data_cell_data) = secp_data_cell(); let (ref secp_cell, ref secp_cell_data, ref script) = secp_cell(); let outputs = vec![secp_data_cell.clone(), secp_cell.clone()]; - let outputs_data = vec![secp_data_cell_data.into(), secp_cell_data.into()]; + let outputs_data = vec![secp_data_cell_data.pack(), secp_cell_data.pack()]; TransactionBuilder::default() .witness(script.clone().into_witness()) .input(CellInput::new(OutPoint::null(), 0)) @@ -263,21 +263,21 @@ pub fn new_secp_chain(txs_size: usize, chains_num: usize) -> Chains { .map(|i| { let data = Bytes::from(i.to_le_bytes().to_vec()); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(secp_script.clone()) .build(); TransactionBuilder::default() .input(CellInput::new(OutPoint::null(), 0)) .output(output.clone()) .output(output) - .output_data(&data) - .output_data(&data) + .output_data(data.pack()) + .output_data(data.pack()) .build() }) .collect(); let genesis_block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .dao(dao) .transaction(tx) .transactions(transactions) @@ -318,11 +318,11 @@ pub fn create_secp_cellbase(shared: &Shared, parent: &HeaderView) -> Transaction builder .output( CellOutput::new_builder() - .capacity(capacity) + .capacity(capacity.pack()) .lock(secp_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build() } } @@ -395,11 +395,11 @@ pub fn gen_secp_block( .transactions(transactions) .proposals(proposals) .parent_hash(p_block.hash()) - .number(number) - .timestamp(timestamp) - .compact_target(epoch.compact_target()) - .epoch(epoch.number_with_fraction(number)) - .nonce(random::()) + .number(number.pack()) + .timestamp(timestamp.pack()) + .compact_target(epoch.compact_target().pack()) + .epoch(epoch.number_with_fraction(number).pack()) + .nonce(random::().pack()) .dao(dao) .build(); @@ -412,11 +412,11 @@ fn create_transaction(parent_hash: &Byte32, lock: Script, dep: OutPoint) -> Tran TransactionBuilder::default() .output( CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(lock) .build(), ) - .output_data(data) + .output_data(data.pack()) .input(CellInput::new(OutPoint::new(parent_hash.to_owned(), 0), 0)) .cell_dep(CellDep::new_builder().out_point(dep).build()) .build() @@ -431,7 +431,7 @@ pub fn create_2out_transaction( let cell_inputs = inputs.into_iter().map(|pts| CellInput::new(pts, 0)); let cell_output = CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(lock) .build(); @@ -440,15 +440,15 @@ pub fn create_2out_transaction( let raw = TransactionBuilder::default() .output(cell_output.clone()) .output(cell_output) - .output_data(&data) - .output_data(&data) + .output_data(data.pack()) + .output_data(data.pack()) .inputs(cell_inputs) .cell_deps(cell_deps) .build(); let privkey: Privkey = PRIVKEY.into(); let witness: WitnessArgs = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len: u64 = witness.as_bytes().len() as u64; let non_sig_witnesses = vec![Bytes::new(); inputs_count - 1]; @@ -470,10 +470,10 @@ pub fn create_2out_transaction( .expect("sign tx") .serialize() .into(); - let witness = witness.as_builder().lock(Some(sig)).build(); + let witness = witness.as_builder().lock(Some(sig).pack()).build(); - let mut witnesses = vec![witness.as_bytes().into()]; - witnesses.extend(non_sig_witnesses.into_iter().map(|w| w.into())); + let mut witnesses = vec![witness.as_bytes().pack()]; + witnesses.extend(non_sig_witnesses.into_iter().map(|w| w.pack())); raw.as_advanced_builder().set_witnesses(witnesses).build() } diff --git a/block-filter/src/filter.rs b/block-filter/src/filter.rs index 1d744ee04b..65fd9fca40 100644 --- a/block-filter/src/filter.rs +++ b/block-filter/src/filter.rs @@ -6,6 +6,7 @@ use ckb_store::{ChainDB, ChainStore}; use ckb_types::{ core::HeaderView, packed::{Byte32, CellOutput, OutPoint}, + prelude::*, utilities::{build_filter_data, FilterDataProvider}, }; @@ -25,7 +26,7 @@ impl<'a> FilterDataProvider for WrappedChainDB<'a> { fn cell(&self, out_point: &OutPoint) -> Option { self.inner .get_transaction(&out_point.tx_hash()) - .and_then(|(tx, _)| tx.outputs().get(out_point.index().into())) + .and_then(|(tx, _)| tx.outputs().get(out_point.index().unpack())) } } @@ -157,7 +158,7 @@ impl BlockFilter { db_transaction .insert_block_filter( &header.hash(), - &filter_data.as_slice().into(), + &filter_data.pack(), &parent_block_filter_hash, ) .expect("insert_block_filter should be ok"); diff --git a/chain/src/init_load_unverified.rs b/chain/src/init_load_unverified.rs index 11283fe17c..30b0247cdb 100644 --- a/chain/src/init_load_unverified.rs +++ b/chain/src/init_load_unverified.rs @@ -9,7 +9,7 @@ use ckb_stop_handler::has_received_stop_signal; use ckb_store::ChainStore; use ckb_types::core::{BlockNumber, BlockView}; use ckb_types::packed; -use ckb_types::prelude::{Entity, FromSliceShouldBeOk, Reader}; +use ckb_types::prelude::{Entity, FromSliceShouldBeOk, Pack, Reader}; use std::cmp; use std::sync::atomic::AtomicBool; use std::sync::Arc; @@ -34,7 +34,7 @@ impl InitLoadUnverified { } fn find_unverified_block_hashes(&self, check_unverified_number: u64) -> Vec { - let pack_number: packed::Uint64 = check_unverified_number.into(); + let pack_number: packed::Uint64 = check_unverified_number.pack(); let prefix = pack_number.as_slice(); // If a block has `COLUMN_NUMBER_HASH` but not `BlockExt`, diff --git a/chain/src/lib.rs b/chain/src/lib.rs index 7d4cae3d55..34b61ef562 100644 --- a/chain/src/lib.rs +++ b/chain/src/lib.rs @@ -28,6 +28,7 @@ pub mod verify; pub use chain_controller::ChainController; use ckb_logger::{error, info}; use ckb_store::{ChainDB, ChainStore}; +use ckb_types::prelude::{Pack, Unpack}; use ckb_types::{BlockNumberAndHash, H256}; pub use init::start_chain_services; @@ -88,11 +89,11 @@ impl From for LonelyBlockHash { switch, verify_callback, } = val; - let block_hash_h256: H256 = block.hash().into(); + let block_hash_h256: H256 = block.hash().unpack(); let block_number: BlockNumber = block.number(); - let parent_hash_h256: H256 = block.parent_hash().into(); - let block_hash = block_hash_h256.into(); - let parent_hash = parent_hash_h256.into(); + let parent_hash_h256: H256 = block.parent_hash().unpack(); + let block_hash = block_hash_h256.pack(); + let parent_hash = parent_hash_h256.pack(); let epoch_number: EpochNumber = block.epoch().number(); diff --git a/chain/src/tests/basic.rs b/chain/src/tests/basic.rs index 0b3a0fe886..b1d2947a82 100644 --- a/chain/src/tests/basic.rs +++ b/chain/src/tests/basic.rs @@ -10,6 +10,7 @@ use ckb_test_chain_utils::{ create_transaction, create_transaction_with_out_point, dao_data, MockChain, MockStore, }; use ckb_types::core::error::OutPointError; +use ckb_types::prelude::*; use ckb_types::{ bytes::Bytes, core::{ @@ -21,7 +22,6 @@ use ckb_types::{ utilities::{compact_to_difficulty, difficulty_to_compact}, U256, }; -use ckb_types::{packed, prelude::*}; use ckb_verification_traits::Switch; use std::sync::Arc; @@ -65,11 +65,11 @@ fn process_genesis_block() { .input(CellInput::new(OutPoint::null(), 0)) .outputs(vec![ CellOutputBuilder::default() - .capacity(capacity_bytes!(100_000_000)) + .capacity(capacity_bytes!(100_000_000).pack()) .build(); 100 ]) - .outputs_data(vec![packed::Bytes::default(); 100]) + .outputs_data(vec![Bytes::new(); 100].pack()) .build(); let always_success_tx = create_always_success_tx(); @@ -78,7 +78,7 @@ fn process_genesis_block() { let genesis_block = BlockBuilder::default() .transaction(tx.clone()) .transaction(always_success_tx.clone()) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .dao(dao.clone()) .build(); @@ -104,7 +104,7 @@ fn process_genesis_block() { .transaction(tx) .transaction(always_success_tx) // Difficulty is changed here - .compact_target(difficulty_to_compact(U256::from(999u64))) + .compact_target(difficulty_to_compact(U256::from(999u64)).pack()) .dao(dao) .build(); let result = chain_controller.blocking_process_block(Arc::new(different_genesis_block)); @@ -119,13 +119,11 @@ fn test_genesis_transaction_spend() { .input(CellInput::new(OutPoint::null(), 0)) .outputs(vec![ CellOutputBuilder::default() - .capacity(capacity_bytes!(100_000_000)) + .capacity(capacity_bytes!(100_000_000).pack()) .build(); 100 ]) - .outputs_data(Into::::into( - vec![Bytes::new(); 100].as_slice(), - )) + .outputs_data(vec![Bytes::new(); 100].pack()) .build(); let always_success_tx = create_always_success_tx(); @@ -138,7 +136,7 @@ fn test_genesis_transaction_spend() { let genesis_block = BlockBuilder::default() .transaction(tx) .transaction(always_success_tx) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .dao(dao) .build(); @@ -431,14 +429,12 @@ fn test_genesis_transaction_fetch() { .input(CellInput::new(OutPoint::null(), 0)) .outputs(vec![ CellOutputBuilder::default() - .capacity(capacity_bytes!(100_000_000)) + .capacity(capacity_bytes!(100_000_000).pack()) .lock(Script::default()) .build(); 100 ]) - .outputs_data(Into::::into( - vec![Bytes::new(); 100].as_slice(), - )) + .outputs_data(vec![Bytes::new(); 100].pack()) .build(); let dao = genesis_dao_data(vec![&tx]).unwrap(); @@ -446,7 +442,7 @@ fn test_genesis_transaction_fetch() { let genesis_block = BlockBuilder::default() .dao(dao) .transaction(tx) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .build(); let consensus = ConsensusBuilder::default() @@ -578,10 +574,10 @@ fn prepare_context_chain( let new_block = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .timestamp(parent.timestamp() + timestep) - .compact_target(epoch.compact_target()) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .timestamp((parent.timestamp() + timestep).pack()) + .compact_target(epoch.compact_target().pack()) .transactions(transactions) .dao(dao) .build(); @@ -618,10 +614,10 @@ fn prepare_context_chain( let new_block = BlockBuilder::default() .parent_hash(parent.hash()) .uncles(uncles) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .timestamp(parent.timestamp() + timestep) - .compact_target(epoch.compact_target()) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .timestamp((parent.timestamp() + timestep).pack()) + .compact_target(epoch.compact_target().pack()) .transactions(transactions) .dao(dao) .build(); @@ -644,7 +640,7 @@ fn test_epoch_hash_rate_dampening() { .build(); let dao = genesis_dao_data(vec![&cellbase]).unwrap(); let genesis_block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .transaction(cellbase) .dao(dao) .build(); @@ -737,7 +733,7 @@ fn test_orphan_rate_estimation_overflow() { let dao = genesis_dao_data(vec![&cellbase]).unwrap(); let genesis_block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .transaction(cellbase) .dao(dao) .build(); @@ -791,7 +787,7 @@ fn test_next_epoch_ext() { .build(); let dao = genesis_dao_data(vec![&cellbase]).unwrap(); let genesis_block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .transaction(cellbase) .dao(dao) .build(); diff --git a/chain/src/tests/block_assembler.rs b/chain/src/tests/block_assembler.rs index bc3627cbd3..caf0eb84ca 100644 --- a/chain/src/tests/block_assembler.rs +++ b/chain/src/tests/block_assembler.rs @@ -14,7 +14,7 @@ use ckb_types::{ TransactionBuilder, TransactionView, }, h256, - packed::{self, Block, CellInput, CellOutput, CellOutputBuilder, CellbaseWitness, OutPoint}, + packed::{Block, CellInput, CellOutput, CellOutputBuilder, CellbaseWitness, OutPoint}, prelude::*, }; use ckb_verification::{BlockVerifier, HeaderVerifier}; @@ -104,18 +104,18 @@ fn gen_block(parent_header: &HeaderView, nonce: u128, epoch: &EpochExt) -> Block let dao = genesis_dao_data(vec![&cellbase]).unwrap(); let header = HeaderBuilder::default() .parent_hash(parent_header.hash()) - .timestamp(parent_header.timestamp() + 10) - .number(number) - .epoch(epoch.number_with_fraction(number)) - .compact_target(epoch.compact_target()) - .nonce(nonce) + .timestamp((parent_header.timestamp() + 10).pack()) + .number(number.pack()) + .epoch(epoch.number_with_fraction(number).pack()) + .compact_target(epoch.compact_target().pack()) + .nonce(nonce.pack()) .dao(dao) .build(); BlockBuilder::default() .header(header) .transaction(cellbase) - .proposal([1; 10]) + .proposal([1; 10].pack()) .build_unchecked() } @@ -124,10 +124,10 @@ fn create_cellbase(number: BlockNumber, epoch: &EpochExt) -> TransactionView { .input(CellInput::new_cellbase_input(number)) .output( CellOutput::new_builder() - .capacity(epoch.block_reward(number).unwrap()) + .capacity(epoch.block_reward(number).unwrap().pack()) .build(), ) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build() } @@ -234,7 +234,7 @@ fn test_prepare_uncles() { .unwrap() .unwrap() } - assert_eq!(block_template.uncles[0].hash, block0_0.hash().into()); + assert_eq!(block_template.uncles[0].hash, block0_0.hash().unpack()); let epoch = shared .consensus() @@ -258,7 +258,7 @@ fn test_prepare_uncles() { .unwrap() } // block number 4, epoch 0, uncles should retained - assert_eq!(block_template.uncles[0].hash, block0_0.hash().into()); + assert_eq!(block_template.uncles[0].hash, block0_0.hash().unpack()); let epoch = shared .consensus() @@ -383,12 +383,12 @@ fn build_tx(parent_tx: &TransactionView, inputs: &[u32], outputs_len: usize) -> (0..outputs_len) .map(|_| { CellOutputBuilder::default() - .capacity(per_output_capacity) + .capacity(per_output_capacity.pack()) .build() }) .collect::>(), ) - .outputs_data((0..outputs_len).map(|_| Bytes::new().into())) + .outputs_data((0..outputs_len).map(|_| Bytes::new().pack())) .build() } diff --git a/chain/src/tests/cell.rs b/chain/src/tests/cell.rs index fc9438c542..3d9c2fd5b9 100644 --- a/chain/src/tests/cell.rs +++ b/chain/src/tests/cell.rs @@ -35,8 +35,12 @@ pub(crate) fn create_cellbase( builder.build() } else { builder - .output(CellOutputBuilder::default().capacity(capacity).build()) - .output_data(Bytes::new()) + .output( + CellOutputBuilder::default() + .capacity(capacity.pack()) + .build(), + ) + .output_data(Bytes::new().pack()) .build() } } @@ -62,10 +66,10 @@ pub(crate) fn gen_block( let block = BlockBuilder::default() .parent_hash(parent_header.hash()) - .timestamp(parent_header.timestamp() + 20_000) - .number(number) - .compact_target(epoch.compact_target()) - .epoch(epoch.number_with_fraction(number)) + .timestamp((parent_header.timestamp() + 20_000).pack()) + .number(number.pack()) + .compact_target(epoch.compact_target().pack()) + .epoch(epoch.number_with_fraction(number).pack()) .transactions(txs) .build(); @@ -79,16 +83,16 @@ pub(crate) fn create_transaction(parent: &TransactionView, index: u32) -> Transa .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .build(), ) .input(CellInput::new(OutPoint::new(parent.hash(), index), 0)) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build() } @@ -100,11 +104,11 @@ fn test_block_cells_update() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -112,7 +116,7 @@ fn test_block_cells_update() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/delay_verify.rs b/chain/src/tests/delay_verify.rs index b30e9b79b2..bd36fa558f 100644 --- a/chain/src/tests/delay_verify.rs +++ b/chain/src/tests/delay_verify.rs @@ -6,6 +6,7 @@ use ckb_test_chain_utils::{ create_transaction_with_out_point, dao_data, MockChain, MockStore, }; use ckb_types::core::error::OutPointError; +use ckb_types::prelude::*; use ckb_types::{core::BlockBuilder, packed::OutPoint}; use ckb_verification_traits::Switch; use std::sync::Arc; @@ -286,9 +287,9 @@ fn test_full_dead_transaction() { let block = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transaction(cellbase_tx) .build(); @@ -326,9 +327,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .proposals(vec![tx1.proposal_short_id()]) @@ -347,9 +348,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() @@ -364,9 +365,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() @@ -406,9 +407,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .proposals(vec![tx2.proposal_short_id(), tx3.proposal_short_id()]) @@ -428,9 +429,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() @@ -447,9 +448,9 @@ fn test_full_dead_transaction() { BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() @@ -478,9 +479,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .proposals(vec![tx2.proposal_short_id(), tx3.proposal_short_id()]) .transactions(transactions) @@ -500,9 +501,9 @@ fn test_full_dead_transaction() { ); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() @@ -519,9 +520,9 @@ fn test_full_dead_transaction() { BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(compact_target - 1) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target((compact_target - 1).pack()) .dao(dao) .transactions(transactions) .build() diff --git a/chain/src/tests/dep_cell.rs b/chain/src/tests/dep_cell.rs index ff3572e692..64e3fbe7d4 100644 --- a/chain/src/tests/dep_cell.rs +++ b/chain/src/tests/dep_cell.rs @@ -31,7 +31,7 @@ pub(crate) fn build_tx( .iter() .map(|index| { let output = inputs.0.output(*index as usize).expect("output index"); - let cap: Capacity = output.capacity().into(); + let cap: Capacity = output.capacity().unpack(); cap }) .try_fold(Capacity::zero(), Capacity::safe_add) @@ -45,13 +45,13 @@ pub(crate) fn build_tx( (0..outputs_len) .map(|_| { CellOutputBuilder::default() - .capacity(per_output_capacity) + .capacity(per_output_capacity.pack()) .lock(always_success_script.clone()) .build() }) .collect::>(), ) - .outputs_data((0..outputs_len).map(|_| Bytes::new().into())) + .outputs_data((0..outputs_len).map(|_| Bytes::new().pack())) .cell_deps(cell_deps.1.iter().map(|index| { CellDep::new_builder() .out_point(OutPoint::new(cell_deps.0.hash(), *index)) @@ -79,18 +79,18 @@ fn test_package_txs_with_deps() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -98,7 +98,7 @@ fn test_package_txs_with_deps() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -211,25 +211,25 @@ fn test_package_txs_with_deps_unstable_sort() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) - .output_data(Bytes::new()) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) + .output_data(Bytes::new().pack()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -237,7 +237,7 @@ fn test_package_txs_with_deps_unstable_sort() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -355,25 +355,25 @@ fn test_package_txs_with_deps2() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) - .output_data(Bytes::new()) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) + .output_data(Bytes::new().pack()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -381,7 +381,7 @@ fn test_package_txs_with_deps2() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -492,18 +492,18 @@ fn test_package_txs_with_deps_priority() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -511,7 +511,7 @@ fn test_package_txs_with_deps_priority() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/find_fork.rs b/chain/src/tests/find_fork.rs index 6c9fdfb6b7..2c39cfd0ca 100644 --- a/chain/src/tests/find_fork.rs +++ b/chain/src/tests/find_fork.rs @@ -9,7 +9,9 @@ use ckb_systemtime::unix_time_as_millis; use ckb_test_chain_utils::{MockChain, MockStore}; use ckb_types::{ core::{BlockBuilder, BlockExt, BlockView}, - packed, U256, + packed, + prelude::Pack, + U256, }; use ckb_verification_traits::Switch; use dashmap::DashSet; @@ -429,10 +431,10 @@ fn repeatedly_switch_fork() { .epoch(); let new_block1 = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .compact_target(parent.compact_target()) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .nonce(1u128) + .number((parent.number() + 1).pack()) + .compact_target(parent.compact_target().pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .nonce(1u128.pack()) .uncle(uncle) .build(); chain_controller @@ -448,10 +450,10 @@ fn repeatedly_switch_fork() { .epoch(); let new_block2 = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .compact_target(parent.compact_target()) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .nonce(2u128) + .number((parent.number() + 1).pack()) + .compact_target(parent.compact_target().pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .nonce(2u128.pack()) .build(); parent = new_block2.clone(); chain_controller @@ -464,10 +466,10 @@ fn repeatedly_switch_fork() { .epoch(); let new_block3 = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .compact_target(parent.compact_target()) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .nonce(2u128) + .number((parent.number() + 1).pack()) + .compact_target(parent.compact_target().pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .nonce(2u128.pack()) .build(); chain_controller .blocking_process_block_with_switch(Arc::new(new_block3), Switch::DISABLE_ALL) @@ -482,10 +484,10 @@ fn repeatedly_switch_fork() { .epoch(); let new_block4 = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .compact_target(parent.compact_target()) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .nonce(1u128) + .number((parent.number() + 1).pack()) + .compact_target(parent.compact_target().pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .nonce(1u128.pack()) .build(); chain_controller .blocking_process_block_with_switch(Arc::new(new_block4.clone()), Switch::DISABLE_ALL) @@ -499,10 +501,10 @@ fn repeatedly_switch_fork() { .epoch(); let new_block5 = BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .compact_target(parent.compact_target()) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .nonce(1u128) + .number((parent.number() + 1).pack()) + .compact_target(parent.compact_target().pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .nonce(1u128.pack()) .build(); chain_controller .blocking_process_block_with_switch(Arc::new(new_block5), Switch::DISABLE_ALL) diff --git a/chain/src/tests/load_code_with_snapshot.rs b/chain/src/tests/load_code_with_snapshot.rs index 108b89f829..9a51e6e82b 100644 --- a/chain/src/tests/load_code_with_snapshot.rs +++ b/chain/src/tests/load_code_with_snapshot.rs @@ -27,9 +27,9 @@ pub(crate) fn create_load_is_even_script_tx() -> TransactionView { .witness(load_is_even_script.clone().into_witness()) .input(CellInput::new(OutPoint::null(), 0)) .output(load_is_even_cell.clone()) - .output_data(load_is_even_data) + .output_data(load_is_even_data.pack()) .output(is_even_lib_cell.clone()) - .output_data(is_even_lib_data) + .output_data(is_even_lib_data.pack()) .build() } @@ -41,15 +41,15 @@ pub(crate) fn create_call_load_is_even_tx(parent: &TransactionView, index: u32) .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .input(CellInput::new(OutPoint::new(parent.hash(), index), 0)) .cell_dep(CellDep::new_builder().out_point(is_even_lib).build()) .cell_dep(CellDep::new_builder().out_point(load_is_even).build()) @@ -69,11 +69,11 @@ fn test_load_code() { let mut vec = Vec::with_capacity(40); vec.extend_from_slice(&number.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.as_slice().into() + vec.pack() }; let lock_script = Script::new_builder() - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .code_hash(load_is_even_script.code_hash()) .args(args) .build(); @@ -82,11 +82,11 @@ fn test_load_code() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(lock_script) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&load_is_even_script_tx, &issue_tx]).unwrap(); @@ -94,7 +94,7 @@ fn test_load_code() { let genesis_block = BlockBuilder::default() .transaction(load_is_even_script_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -130,11 +130,11 @@ fn test_load_code_with_snapshot() { let mut vec = Vec::with_capacity(40); vec.extend_from_slice(&number.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.as_slice().into() + vec.pack() }; let lock_script = Script::new_builder() - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .code_hash(load_is_even_script.code_hash()) .args(args) .build(); @@ -143,11 +143,11 @@ fn test_load_code_with_snapshot() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(lock_script) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&load_is_even_script_tx, &issue_tx]).unwrap(); @@ -155,7 +155,7 @@ fn test_load_code_with_snapshot() { let genesis_block = BlockBuilder::default() .transaction(load_is_even_script_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -209,11 +209,11 @@ fn _test_load_code_with_snapshot_after_hardfork(script_type: ScriptHashType) { let mut vec = Vec::with_capacity(40); vec.extend_from_slice(&number.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.as_slice().into() + vec.pack() }; let lock_script = Script::new_builder() - .hash_type(script_type) + .hash_type(script_type.into()) .code_hash(load_is_even_script.code_hash()) .args(args) .build(); @@ -222,11 +222,11 @@ fn _test_load_code_with_snapshot_after_hardfork(script_type: ScriptHashType) { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(lock_script) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&load_is_even_script_tx, &issue_tx]).unwrap(); @@ -234,7 +234,7 @@ fn _test_load_code_with_snapshot_after_hardfork(script_type: ScriptHashType) { let genesis_block = BlockBuilder::default() .transaction(load_is_even_script_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/load_input_cell_data.rs b/chain/src/tests/load_input_cell_data.rs index 8e711fb25c..236a952325 100644 --- a/chain/src/tests/load_input_cell_data.rs +++ b/chain/src/tests/load_input_cell_data.rs @@ -30,16 +30,16 @@ pub(crate) fn create_load_input_one_byte_transaction( .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .lock(load_input_one_byte_script.clone()) .build(), ) - .output_data(Bytes::from(b"1".to_vec())) + .output_data(Bytes::from(b"1".to_vec()).pack()) .input(CellInput::new(OutPoint::new(parent.hash(), index), 0)) .cell_dep( CellDep::new_builder() @@ -59,11 +59,11 @@ fn test_load_input_one_byte_cell() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(load_input_one_byte_script.clone()) .build(), ) - .output_data(Bytes::from(b"1".to_vec())) + .output_data(Bytes::from(b"1".to_vec()).pack()) .build(); let dao = genesis_dao_data(vec![&load_input_one_byte_cell_tx, &issue_tx]).unwrap(); @@ -71,7 +71,7 @@ fn test_load_input_one_byte_cell() { let genesis_block = BlockBuilder::default() .transaction(load_input_one_byte_cell_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/load_input_data_hash_cell.rs b/chain/src/tests/load_input_data_hash_cell.rs index ac0502c7e8..b753c1d91f 100644 --- a/chain/src/tests/load_input_data_hash_cell.rs +++ b/chain/src/tests/load_input_data_hash_cell.rs @@ -30,16 +30,16 @@ pub(crate) fn create_load_input_data_hash_transaction( .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .lock(load_input_data_hash_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .input(CellInput::new(OutPoint::new(parent.hash(), index), 0)) .cell_dep( CellDep::new_builder() @@ -59,11 +59,11 @@ fn test_load_input_data_hash_cell() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(load_input_data_hash_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&load_input_data_hash_cell_tx, &issue_tx]).unwrap(); @@ -71,7 +71,7 @@ fn test_load_input_data_hash_cell() { let genesis_block = BlockBuilder::default() .transaction(load_input_data_hash_cell_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/non_contextual_block_txs_verify.rs b/chain/src/tests/non_contextual_block_txs_verify.rs index 03cbbb5171..68178658d8 100644 --- a/chain/src/tests/non_contextual_block_txs_verify.rs +++ b/chain/src/tests/non_contextual_block_txs_verify.rs @@ -42,11 +42,11 @@ pub(crate) fn create_cellbase( builder .output( CellOutputBuilder::default() - .capacity(capacity) + .capacity(capacity.pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build() } } @@ -72,10 +72,10 @@ pub(crate) fn gen_block( let block = BlockBuilder::default() .parent_hash(parent_header.hash()) - .timestamp(parent_header.timestamp() + 20_000) - .number(number) - .compact_target(epoch.compact_target()) - .epoch(epoch.number_with_fraction(number)) + .timestamp((parent_header.timestamp() + 20_000).pack()) + .number(number.pack()) + .compact_target(epoch.compact_target().pack()) + .epoch(epoch.number_with_fraction(number).pack()) .transactions(txs) .build(); @@ -96,12 +96,12 @@ pub(crate) fn create_transaction( .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); let mut builder = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .lock(always_success_script.clone()) .build(), ) @@ -113,7 +113,7 @@ pub(crate) fn create_transaction( ); if !missing_output_data { - builder = builder.output_data(Bytes::new()) + builder = builder.output_data(Bytes::new().pack()) } builder.build() } @@ -127,11 +127,11 @@ fn non_contextual_block_txs_verify() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &issue_tx]).unwrap(); @@ -139,7 +139,7 @@ fn non_contextual_block_txs_verify() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(issue_tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); diff --git a/chain/src/tests/orphan_block_pool.rs b/chain/src/tests/orphan_block_pool.rs index 5e6aa45775..bc0ba1ceb9 100644 --- a/chain/src/tests/orphan_block_pool.rs +++ b/chain/src/tests/orphan_block_pool.rs @@ -5,6 +5,7 @@ use ckb_chain_spec::consensus::ConsensusBuilder; use ckb_systemtime::unix_time_as_millis; use ckb_types::core::{BlockBuilder, EpochNumberWithFraction, HeaderView}; use ckb_types::packed::Byte32; +use ckb_types::prelude::*; use std::collections::HashSet; use std::sync::Arc; use std::thread; @@ -15,14 +16,10 @@ fn gen_lonely_block(parent_header: &HeaderView) -> LonelyBlock { let number = parent_header.number() + 1; let block = BlockBuilder::default() .parent_hash(parent_header.hash()) - .timestamp(unix_time_as_millis()) - .number(number) - .epoch(EpochNumberWithFraction::new( - number / 1000, - number % 1000, - 1000, - )) - .nonce(parent_header.nonce() + 1) + .timestamp(unix_time_as_millis().pack()) + .number(number.pack()) + .epoch(EpochNumberWithFraction::new(number / 1000, number % 1000, 1000).pack()) + .nonce((parent_header.nonce() + 1).pack()) .build(); LonelyBlock { block: Arc::new(block), @@ -241,10 +238,10 @@ fn test_remove_expired_blocks() { for _ in 1..block_number { let new_block = BlockBuilder::default() .parent_hash(parent.hash()) - .timestamp(unix_time_as_millis()) - .number(parent.number() + 1) - .epoch(deprecated) - .nonce(parent.nonce() + 1) + .timestamp(unix_time_as_millis().pack()) + .number((parent.number() + 1).pack()) + .epoch(deprecated.clone().pack()) + .nonce((parent.nonce() + 1).pack()) .build(); parent = new_block.header(); diff --git a/chain/src/tests/reward.rs b/chain/src/tests/reward.rs index f11c7d1792..876a1495bf 100644 --- a/chain/src/tests/reward.rs +++ b/chain/src/tests/reward.rs @@ -47,11 +47,11 @@ pub(crate) fn create_cellbase( builder .output( CellOutputBuilder::default() - .capacity(reward.unwrap_or(capacity)) + .capacity(reward.unwrap_or(capacity).pack()) .lock(reward_lock) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build() } } @@ -91,10 +91,10 @@ pub(crate) fn gen_block( let block = BlockBuilder::default() .parent_hash(parent_header.hash()) - .timestamp(parent_header.timestamp() + 20_000) - .number(number) - .compact_target(epoch.compact_target()) - .epoch(epoch.number_with_fraction(number)) + .timestamp((parent_header.timestamp() + 20_000).pack()) + .number(number.pack()) + .compact_target(epoch.compact_target().pack()) + .epoch(epoch.number_with_fraction(number).pack()) .dao(dao) .transactions(txs) .uncles(uncles) @@ -115,16 +115,16 @@ pub(crate) fn create_transaction(parent: &TransactionView, index: u32) -> Transa .get(0) .expect("get output index 0") .capacity() - .into(); + .unpack(); TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(input_cap.safe_sub(TX_FEE).unwrap()) + .capacity(input_cap.safe_sub(TX_FEE).unwrap().pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .input(CellInput::new(OutPoint::new(parent.hash(), index), 0)) .cell_dep( CellDep::new_builder() @@ -142,11 +142,11 @@ fn finalize_reward() { .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(5_000)) + .capacity(capacity_bytes!(5_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx, &tx]).unwrap(); @@ -154,7 +154,7 @@ fn finalize_reward() { let genesis_block = BlockBuilder::default() .transaction(always_success_tx) .transaction(tx.clone()) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .dao(dao) .build(); @@ -176,19 +176,19 @@ fn finalize_reward() { let ids: Vec<_> = txs.iter().map(TransactionView::proposal_short_id).collect(); let mut blocks = Vec::with_capacity(24); - let bob_args: packed::Bytes = Bytes::from(b"b0b".to_vec()).into(); + let bob_args: packed::Bytes = Bytes::from(b"b0b".to_vec()).pack(); let bob = ScriptBuilder::default() .args(bob_args) .code_hash(always_success_script.code_hash()) - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build(); - let alice_args: packed::Bytes = Bytes::from(b"a11ce".to_vec()).into(); + let alice_args: packed::Bytes = Bytes::from(b"a11ce".to_vec()).pack(); let alice = ScriptBuilder::default() .args(alice_args) .code_hash(always_success_script.code_hash()) - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build(); for i in 1..23 { diff --git a/chain/src/tests/util.rs b/chain/src/tests/util.rs index dcfc8df14d..f29cd97ad7 100644 --- a/chain/src/tests/util.rs +++ b/chain/src/tests/util.rs @@ -42,18 +42,18 @@ pub(crate) fn start_chain_with_tx_pool_config( .input(CellInput::new(OutPoint::null(), 0)) .output( CellOutput::new_builder() - .capacity(capacity_bytes!(50_000)) + .capacity(capacity_bytes!(50_000).pack()) .lock(always_success_script.clone()) .build(), ) - .output_data(data) + .output_data(data.pack()) .build() }) .collect(); let genesis_block = BlockBuilder::default() .dao(dao) - .compact_target(DIFF_TWO) + .compact_target(DIFF_TWO.pack()) .transaction(tx) .transactions(transactions) .build(); diff --git a/chain/src/verify.rs b/chain/src/verify.rs index 3b6fb4eea9..1b2a007aa1 100644 --- a/chain/src/verify.rs +++ b/chain/src/verify.rs @@ -203,7 +203,9 @@ impl ConsumeUnverifiedBlockProcessor { match *assume_valid_target { Some(ref target) => { // if the target has been reached, delete it - if target == &Into::::into(&BlockView::hash(block)) { + if target + == &ckb_types::prelude::Unpack::::unpack(&BlockView::hash(block)) + { assume_valid_target.take(); Switch::NONE } else { diff --git a/ckb-bin/src/subcommand/init.rs b/ckb-bin/src/subcommand/init.rs index 063defdc3f..b8a72905f8 100644 --- a/ckb-bin/src/subcommand/init.rs +++ b/ckb-bin/src/subcommand/init.rs @@ -10,7 +10,7 @@ use ckb_resource::{ Resource, TemplateContext, AVAILABLE_SPECS, CKB_CONFIG_FILE_NAME, DB_OPTIONS_FILE_NAME, MINER_CONFIG_FILE_NAME, SPEC_DEV_FILE_NAME, }; -use ckb_types::H256; +use ckb_types::{prelude::*, H256}; use crate::cli; @@ -81,7 +81,7 @@ pub fn init(args: InitArgs) -> Result<(), ExitCode> { .build_consensus() .expect("Build consensus failed") .get_secp_type_script_hash() - .into(); + .unpack(); format!("{hash:#x}") }); diff --git a/ckb-bin/src/subcommand/list_hashes.rs b/ckb-bin/src/subcommand/list_hashes.rs index 93288d3b0f..b241d92eef 100644 --- a/ckb-bin/src/subcommand/list_hashes.rs +++ b/ckb-bin/src/subcommand/list_hashes.rs @@ -1,7 +1,7 @@ use ckb_app_config::{CKBAppConfig, ExitCode}; use ckb_chain_spec::ChainSpec; use ckb_resource::{Resource, AVAILABLE_SPECS}; -use ckb_types::{packed::CellOutput, H256}; +use ckb_types::{packed::CellOutput, prelude::*, H256}; use ckb_util::LinkedHashMap; use clap::ArgMatches; use serde::{Deserialize, Serialize}; @@ -41,7 +41,7 @@ impl TryFrom for SpecHashes { let hash_option = spec.genesis.hash.take(); let consensus = spec.build_consensus().map_err(to_config_error)?; if let Some(hash) = hash_option { - let genesis_hash: H256 = consensus.genesis_hash().into(); + let genesis_hash: H256 = consensus.genesis_hash().unpack(); if hash != genesis_hash { eprintln!( "Genesis hash unmatched in {} chainspec config file:\n\ @@ -71,14 +71,14 @@ impl TryFrom for SpecHashes { ) .enumerate() .map(|(index_minus_one, (resource, (output, data)))| { - let data_hash: H256 = CellOutput::calc_data_hash(&data.raw_data()).into(); + let data_hash: H256 = CellOutput::calc_data_hash(&data.raw_data()).unpack(); let type_hash: Option = output .type_() .to_opt() - .map(|script| script.calc_script_hash().into()); + .map(|script| script.calc_script_hash().unpack()); SystemCell { path: resource.to_string(), - tx_hash: cellbase.hash().into(), + tx_hash: cellbase.hash().unpack(), index: index_minus_one + 1, data_hash, type_hash, @@ -97,15 +97,15 @@ impl TryFrom for SpecHashes { .iter() .map(|res| res.to_string()) .collect::>(), - tx_hash: dep_group_tx.hash().into(), + tx_hash: dep_group_tx.hash().unpack(), index, }) .collect::>(); Ok(SpecHashes { - spec_hash: spec.hash.into(), - genesis: consensus.genesis_hash().into(), - cellbase: cellbase.hash().into(), + spec_hash: spec.hash.unpack(), + genesis: consensus.genesis_hash().unpack(), + cellbase: cellbase.hash().unpack(), system_cells: cells_hashes, dep_groups, }) diff --git a/devtools/ci/ci_main.sh b/devtools/ci/ci_main.sh index cd9c18edb4..33242b3035 100755 --- a/devtools/ci/ci_main.sh +++ b/devtools/ci/ci_main.sh @@ -67,7 +67,7 @@ case $GITHUB_WORKFLOW in sudo apt-get install -y gcc-multilib sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu clang rustup target add aarch64-unknown-linux-gnu - curl -LO https://openssl.org/source/old/3.1/openssl-3.1.3.tar.gz + curl -LO https://www.openssl.org/source/openssl-3.1.3.tar.gz tar -xvzf openssl-3.1.3.tar.gz cd openssl-3.1.3 CC=aarch64-linux-gnu-gcc ./Configure linux-aarch64 shared diff --git a/miner/src/miner.rs b/miner/src/miner.rs index 55034f841f..436ea53ca4 100644 --- a/miner/src/miner.rs +++ b/miner/src/miner.rs @@ -116,7 +116,8 @@ impl Miner { let parent_hash = work.block.header().into_view().parent_hash(); if !self.legacy_work.contains(&parent_hash) { let pow_hash = work.block.header().calc_pow_hash(); - let (target, _) = compact_to_target(work.block.header().raw().compact_target().into()); + let (target, _) = + compact_to_target(work.block.header().raw().compact_target().unpack()); self.notify_workers(WorkerMessage::NewWork { pow_hash, work, @@ -128,7 +129,10 @@ impl Miner { fn submit_nonce(&mut self, pow_hash: Byte32, work: Work, nonce: u128) { self.notify_workers(WorkerMessage::Stop); let raw_header = work.block.header().raw(); - let header = Header::new_builder().raw(raw_header).nonce(nonce).build(); + let header = Header::new_builder() + .raw(raw_header) + .nonce(nonce.pack()) + .build(); let block = work .block .as_advanced_builder() diff --git a/network/src/protocols/discovery/protocol.rs b/network/src/protocols/discovery/protocol.rs index 85d23c4287..0950e48784 100644 --- a/network/src/protocols/discovery/protocol.rs +++ b/network/src/protocols/discovery/protocol.rs @@ -32,16 +32,18 @@ impl DiscoveryMessage { listen_port, required_flags, } => { + let version = version.pack(); + let count = count.pack(); let listen_port = packed::PortOpt::new_builder() .set(listen_port.map(|port| { let port_le = port.to_le_bytes(); packed::Uint16::new_builder() - .nth0(port_le[0]) - .nth1(port_le[1]) + .nth0(port_le[0].into()) + .nth1(port_le[1].into()) .build() })) .build(); - let required_flags = required_flags.bits(); + let required_flags = required_flags.bits().pack(); let get_node = packed::GetNodes2::new_builder() .listen_port(listen_port) .count(count) @@ -68,7 +70,7 @@ impl DiscoveryMessage { ) } let bytes_vec = packed::BytesVec::new_builder().set(vec_addrs).build(); - let flags = item.flags.bits(); + let flags = item.flags.bits().pack(); let node = packed::Node2::new_builder() .addresses(bytes_vec) .flags(flags) @@ -116,7 +118,7 @@ impl DiscoveryMessage { let get_nodes2 = packed::GetNodes2::from_compatible_slice(reader.as_slice()).ok()?; let reader = get_nodes2.as_reader(); - Flags::from_bits_truncate(reader.required_flags().into()) + Flags::from_bits_truncate(reader.required_flags().unpack()) } else { Flags::COMPATIBILITY }; @@ -144,7 +146,7 @@ impl DiscoveryMessage { let node2 = packed::Node2::from_compatible_slice(node_reader.as_slice()).ok()?; let reader = node2.as_reader(); - Flags::from_bits_truncate(reader.flags().into()) + Flags::from_bits_truncate(reader.flags().unpack()) } else { Flags::COMPATIBILITY }; diff --git a/network/src/protocols/identify/mod.rs b/network/src/protocols/identify/mod.rs index 074768ec08..8f2448050d 100644 --- a/network/src/protocols/identify/mod.rs +++ b/network/src/protocols/identify/mod.rs @@ -588,9 +588,9 @@ impl Identify { fn new(name: String, flags: Flags, client_version: String) -> Self { Identify { encode_data: packed::Identify::new_builder() - .name(name.as_str()) - .flag(flags.bits()) - .client_version(client_version.as_str()) + .name(name.as_str().pack()) + .flag(flags.bits().pack()) + .client_version(client_version.as_str().pack()) .build() .as_bytes(), name, @@ -613,7 +613,7 @@ impl Identify { return None; } - let flag: u64 = reader.flag().into(); + let flag: u64 = reader.flag().unpack(); if flag == 0 { return None; } diff --git a/network/src/protocols/ping.rs b/network/src/protocols/ping.rs index e62dfb7cba..984dbf2a15 100644 --- a/network/src/protocols/ping.rs +++ b/network/src/protocols/ping.rs @@ -291,10 +291,10 @@ impl PingMessage { fn build_ping(nonce: u32) -> Bytes { let nonce_le = nonce.to_le_bytes(); let nonce = packed::Uint32::new_builder() - .nth0(nonce_le[0]) - .nth1(nonce_le[1]) - .nth2(nonce_le[2]) - .nth3(nonce_le[3]) + .nth0(nonce_le[0].into()) + .nth1(nonce_le[1].into()) + .nth2(nonce_le[2].into()) + .nth3(nonce_le[3].into()) .build(); let ping = packed::Ping::new_builder().nonce(nonce).build(); let payload = packed::PingPayload::new_builder().set(ping).build(); @@ -307,10 +307,10 @@ impl PingMessage { fn build_pong(nonce: u32) -> Bytes { let nonce_le = nonce.to_le_bytes(); let nonce = packed::Uint32::new_builder() - .nth0(nonce_le[0]) - .nth1(nonce_le[1]) - .nth2(nonce_le[2]) - .nth3(nonce_le[3]) + .nth0(nonce_le[0].into()) + .nth1(nonce_le[1].into()) + .nth2(nonce_le[2].into()) + .nth3(nonce_le[3].into()) .build(); let pong = packed::Pong::new_builder().nonce(nonce).build(); let payload = packed::PingPayload::new_builder().set(pong).build(); diff --git a/pow/src/eaglesong.rs b/pow/src/eaglesong.rs index 456f131945..f7bb88be27 100644 --- a/pow/src/eaglesong.rs +++ b/pow/src/eaglesong.rs @@ -9,11 +9,12 @@ pub struct EaglesongPowEngine; impl PowEngine for EaglesongPowEngine { fn verify(&self, header: &Header) -> bool { - let input = crate::pow_message(&header.as_reader().calc_pow_hash(), header.nonce().into()); + let input = + crate::pow_message(&header.as_reader().calc_pow_hash(), header.nonce().unpack()); let mut output = [0u8; 32]; eaglesong(&input, &mut output); - let (block_target, overflow) = compact_to_target(header.raw().compact_target().into()); + let (block_target, overflow) = compact_to_target(header.raw().compact_target().unpack()); if block_target.is_zero() || overflow { debug!( @@ -42,7 +43,7 @@ impl PowEngine for EaglesongPowEngine { ); debug!( "PowEngine::verify error: nonce {:#x}", - Into::::into(header.nonce()) + header.nonce().unpack() ); debug!( "PowEngine::verify error: pow input: 0x{:x}", diff --git a/pow/src/eaglesong_blake2b.rs b/pow/src/eaglesong_blake2b.rs index fbfbbd6df5..0b87aed9ad 100644 --- a/pow/src/eaglesong_blake2b.rs +++ b/pow/src/eaglesong_blake2b.rs @@ -10,14 +10,15 @@ pub struct EaglesongBlake2bPowEngine; impl PowEngine for EaglesongBlake2bPowEngine { fn verify(&self, header: &Header) -> bool { - let input = crate::pow_message(&header.as_reader().calc_pow_hash(), header.nonce().into()); + let input = + crate::pow_message(&header.as_reader().calc_pow_hash(), header.nonce().unpack()); let output = { let mut output_tmp = [0u8; 32]; eaglesong(&input, &mut output_tmp); blake2b_256(output_tmp) }; - let (block_target, overflow) = compact_to_target(header.raw().compact_target().into()); + let (block_target, overflow) = compact_to_target(header.raw().compact_target().unpack()); if block_target.is_zero() || overflow { debug!( @@ -50,7 +51,7 @@ impl PowEngine for EaglesongBlake2bPowEngine { ); debug!( "PowEngine::verify error: nonce {:#x}", - Into::::into(header.nonce()) + header.nonce().unpack() ); debug!( "PowEngine::verify error: pow input: 0x{:x}", diff --git a/pow/src/tests.rs b/pow/src/tests.rs index fafeabd3dd..ad4f27ca26 100644 --- a/pow/src/tests.rs +++ b/pow/src/tests.rs @@ -1,9 +1,10 @@ use crate::pow_message; use ckb_hash::blake2b_256; +use ckb_types::prelude::*; #[test] fn test_pow_message() { - let zero_hash = blake2b_256([]).into(); + let zero_hash = blake2b_256([]).pack(); let nonce = u128::max_value(); let message = pow_message(&zero_hash, nonce); assert_eq!( diff --git a/rpc/src/module/alert.rs b/rpc/src/module/alert.rs index fe6a243a03..959ea2e3ee 100644 --- a/rpc/src/module/alert.rs +++ b/rpc/src/module/alert.rs @@ -99,7 +99,7 @@ impl AlertRpc for AlertRpcImpl { fn send_alert(&self, alert: Alert) -> Result<()> { let alert: packed::Alert = alert.into(); let now_ms = ckb_systemtime::unix_time_as_millis(); - let notice_until: u64 = alert.raw().notice_until().into(); + let notice_until: u64 = alert.raw().notice_until().unpack(); if notice_until < now_ms { return Err(RPCError::invalid_params(format!( "Expected `params[0].notice_until` in the future (> {now_ms}), got {notice_until}", diff --git a/rpc/src/module/chain.rs b/rpc/src/module/chain.rs index d6288a3876..a82aabb77b 100644 --- a/rpc/src/module/chain.rs +++ b/rpc/src/module/chain.rs @@ -1636,7 +1636,7 @@ impl ChainRpc for ChainRpcImpl { with_cycles: Option, ) -> Result> { let snapshot = self.shared.snapshot(); - let block_hash = block_hash.into(); + let block_hash = block_hash.pack(); self.get_block_by_hash(&snapshot, &block_hash, verbosity, with_cycles) } @@ -1673,7 +1673,7 @@ impl ChainRpc for ChainRpcImpl { verbosity: Option, ) -> Result>> { let snapshot = self.shared.snapshot(); - let block_hash = block_hash.into(); + let block_hash = block_hash.pack(); if !snapshot.is_main_chain(&block_hash) { return Ok(None); } @@ -1731,7 +1731,7 @@ impl ChainRpc for ChainRpcImpl { fn get_block_filter(&self, block_hash: H256) -> Result> { let store = self.shared.store(); - let block_hash = block_hash.into(); + let block_hash = block_hash.pack(); if !store.is_main_chain(&block_hash) { return Ok(None); } @@ -1752,7 +1752,7 @@ impl ChainRpc for ChainRpcImpl { verbosity: Option, only_committed: Option, ) -> Result { - let tx_hash = tx_hash.into(); + let tx_hash = tx_hash.pack(); let verbosity = verbosity .map(|v| v.value()) .unwrap_or(DEFAULT_GET_TRANSACTION_VERBOSITY_LEVEL); @@ -1784,7 +1784,7 @@ impl ChainRpc for ChainRpcImpl { .shared .snapshot() .get_block_hash(block_number.into()) - .map(|h| h.into())) + .map(|h| h.unpack())) } fn get_tip_header(&self, verbosity: Option) -> Result> { @@ -1806,7 +1806,7 @@ impl ChainRpc for ChainRpcImpl { fn get_current_epoch(&self) -> Result { Ok(EpochView::from_ext( - self.shared.snapshot().epoch_ext().into(), + self.shared.snapshot().epoch_ext().pack(), )) } @@ -1817,7 +1817,7 @@ impl ChainRpc for ChainRpcImpl { .and_then(|hash| { snapshot .get_epoch_ext(&hash) - .map(|ext| EpochView::from_ext(ext.into())) + .map(|ext| EpochView::from_ext(ext.pack())) })) } @@ -1848,12 +1848,12 @@ impl ChainRpc for ChainRpcImpl { fn get_block_economic_state(&self, block_hash: H256) -> Result> { let snapshot = self.shared.snapshot(); - let block_number = - if let Some(block_number) = snapshot.get_block_number(&(&block_hash).into()) { - block_number - } else { - return Ok(None); - }; + let block_number = if let Some(block_number) = snapshot.get_block_number(&block_hash.pack()) + { + block_number + } else { + return Ok(None); + }; let delay_length = snapshot.consensus().finalization_delay_length(); let finalized_at_number = block_number + delay_length; @@ -1861,7 +1861,7 @@ impl ChainRpc for ChainRpcImpl { return Ok(None); } - let block_hash = (&block_hash).into(); + let block_hash = block_hash.pack(); let finalized_at = if let Some(block_hash) = snapshot.get_block_hash(finalized_at_number) { block_hash } else { @@ -1920,8 +1920,8 @@ impl ChainRpc for ChainRpcImpl { ) -> Result { let (block, leaf_indices) = self.get_tx_indices(tx_hashes, block_hash)?; Ok(TransactionProof { - block_hash: block.hash().into(), - witnesses_root: block.calc_witnesses_root().into(), + block_hash: block.hash().unpack(), + witnesses_root: block.calc_witnesses_root().unpack(), proof: CBMT::build_merkle_proof( &block .transactions() @@ -1939,12 +1939,12 @@ impl ChainRpc for ChainRpcImpl { let snapshot = self.shared.snapshot(); snapshot - .get_block(&(&tx_proof.block_hash).into()) + .get_block(&tx_proof.block_hash.pack()) .ok_or_else(|| { RPCError::invalid_params(format!("Cannot find block {:#x}", tx_proof.block_hash)) }) .and_then(|block| { - let witnesses_root = tx_proof.witnesses_root.into(); + let witnesses_root = tx_proof.witnesses_root.pack(); let merkle_proof = MerkleProof::new( tx_proof .proof @@ -1956,7 +1956,7 @@ impl ChainRpc for ChainRpcImpl { .proof .lemmas .into_iter() - .map(|lemma| lemma.into()) + .map(|lemma| lemma.pack()) .collect(), ); @@ -1968,7 +1968,7 @@ impl ChainRpc for ChainRpcImpl { if block.transactions_root() == merkle_root(&[raw_transactions_root, witnesses_root]) { - Some(tx_hashes.iter().map(|hash| hash.into()).collect()) + Some(tx_hashes.iter().map(|hash| hash.unpack()).collect()) } else { None } @@ -1985,7 +1985,7 @@ impl ChainRpc for ChainRpcImpl { ) -> Result { let (block, leaf_indices) = self.get_tx_indices(tx_hashes, block_hash)?; Ok(TransactionAndWitnessProof { - block_hash: block.hash().into(), + block_hash: block.hash().unpack(), transactions_proof: CBMT::build_merkle_proof( &block .transactions() @@ -2008,7 +2008,7 @@ impl ChainRpc for ChainRpcImpl { ) -> Result> { let snapshot = self.shared.snapshot(); snapshot - .get_block(&(&tx_proof.block_hash).into()) + .get_block(&tx_proof.block_hash.pack()) .ok_or_else(|| { RPCError::invalid_params(format!("Cannot find block {:#x}", tx_proof.block_hash)) }) @@ -2024,7 +2024,7 @@ impl ChainRpc for ChainRpcImpl { .transactions_proof .lemmas .into_iter() - .map(|lemma| lemma.into()) + .map(|lemma| lemma.pack()) .collect(), ); let witnesses_merkle_proof = MerkleProof::new( @@ -2038,7 +2038,7 @@ impl ChainRpc for ChainRpcImpl { .witnesses_proof .lemmas .into_iter() - .map(|lemma| lemma.into()) + .map(|lemma| lemma.pack()) .collect(), ); @@ -2055,7 +2055,12 @@ impl ChainRpc for ChainRpcImpl { witnesses_proof_root, ]) { - Some(tx_hashes.iter().map(|hash| hash.into()).collect()) + Some( + tx_hashes + .iter() + .map(|hash| hash.unpack()) + .collect(), + ) } else { None } @@ -2075,7 +2080,7 @@ impl ChainRpc for ChainRpcImpl { verbosity: Option, ) -> Result>> { let snapshot = self.shared.snapshot(); - let block_hash = block_hash.into(); + let block_hash = block_hash.pack(); if snapshot.is_main_chain(&block_hash) { return Ok(None); } @@ -2103,7 +2108,7 @@ impl ChainRpc for ChainRpcImpl { } fn get_block_median_time(&self, block_hash: H256) -> Result> { - let block_hash = block_hash.into(); + let block_hash = block_hash.pack(); let snapshot = self.shared.snapshot(); if !snapshot.is_main_chain(&block_hash) { return Ok(None); @@ -2155,7 +2160,7 @@ impl ChainRpcImpl { return Ok(TransactionWithStatus::with_committed( None, tx_info.block_number, - tx_info.block_hash.into(), + tx_info.block_hash.unpack(), tx_info.index as u32, cycles, None, @@ -2204,7 +2209,7 @@ impl ChainRpcImpl { return Ok(TransactionWithStatus::with_committed( Some(tx), tx_info.block_number, - tx_info.block_hash.into(), + tx_info.block_hash.unpack(), tx_info.index as u32, cycles, None, @@ -2291,7 +2296,7 @@ impl ChainRpcImpl { let mut retrieved_block_hash = None; let mut tx_indices = HashSet::new(); for tx_hash in tx_hashes { - match snapshot.get_transaction_info(&(&tx_hash).into()) { + match snapshot.get_transaction_info(&tx_hash.pack()) { Some(tx_info) => { if retrieved_block_hash.is_none() { retrieved_block_hash = Some(tx_info.block_hash); @@ -2317,7 +2322,7 @@ impl ChainRpcImpl { let retrieved_block_hash = retrieved_block_hash.expect("checked len"); if let Some(specified_block_hash) = block_hash { - if !retrieved_block_hash.eq(&specified_block_hash.into()) { + if !retrieved_block_hash.eq(&specified_block_hash.pack()) { return Err(RPCError::invalid_params( "Not all transactions found in specified block", )); diff --git a/rpc/src/module/experiment.rs b/rpc/src/module/experiment.rs index fe768c3719..90e910dc1a 100644 --- a/rpc/src/module/experiment.rs +++ b/rpc/src/module/experiment.rs @@ -7,7 +7,7 @@ use ckb_jsonrpc_types::{ }; use ckb_shared::{shared::Shared, Snapshot}; use ckb_store::ChainStore; -use ckb_types::{core, packed}; +use ckb_types::{core, packed, prelude::*}; use jsonrpc_core::Result; use jsonrpc_utils::rpc; @@ -193,18 +193,18 @@ impl ExperimentRpc for ExperimentRpcImpl { .ok_or_else(|| RPCError::invalid_params("invalid out_point"))?; let output = tx .outputs() - .get(out_point.index().into()) + .get(out_point.index().unpack()) .ok_or_else(|| RPCError::invalid_params("invalid out_point"))?; let output_data = tx .outputs_data() - .get(out_point.index().into()) + .get(out_point.index().unpack()) .ok_or_else(|| RPCError::invalid_params("invalid out_point"))?; match calculator.calculate_maximum_withdraw( &output, core::Capacity::bytes(output_data.len()).expect("should not overflow"), &deposit_header_hash, - &withdrawing_header_hash.into(), + &withdrawing_header_hash.pack(), ) { Ok(capacity) => Ok(capacity.into()), Err(err) => Err(RPCError::custom_with_error(RPCError::DaoError, err)), @@ -222,11 +222,11 @@ impl ExperimentRpc for ExperimentRpcImpl { let output = withdrawing_tx .outputs() - .get(withdrawing_out_point.index().into()) + .get(withdrawing_out_point.index().unpack()) .ok_or_else(|| RPCError::invalid_params("invalid withdrawing_out_point"))?; let output_data = withdrawing_tx .outputs_data() - .get(withdrawing_out_point.index().into()) + .get(withdrawing_out_point.index().unpack()) .ok_or_else(|| RPCError::invalid_params("invalid withdrawing_out_point"))?; match calculator.calculate_maximum_withdraw( diff --git a/rpc/src/module/miner.rs b/rpc/src/module/miner.rs index 506ba44665..3338c6d5aa 100644 --- a/rpc/src/module/miner.rs +++ b/rpc/src/module/miner.rs @@ -332,7 +332,7 @@ impl MinerRpc for MinerRpcImpl { Ok(root) => root, Err(err) => { error!("Generate last state to light client failed: {:?}", err); - return Ok(header.hash().into()); + return Ok(header.hash().unpack()); } } }; @@ -340,7 +340,7 @@ impl MinerRpc for MinerRpcImpl { let tip_header = packed::VerifiableHeader::new_builder() .header(header.data()) .uncles_hash(block.calc_uncles_hash()) - .extension(block.extension()) + .extension(Pack::pack(&block.extension())) .parent_chain_root(parent_chain_root) .build(); let light_client_message = { @@ -367,7 +367,7 @@ impl MinerRpc for MinerRpcImpl { } } - Ok(header.hash().into()) + Ok(header.hash().unpack()) } } diff --git a/rpc/src/module/net.rs b/rpc/src/module/net.rs index dd1fee9c33..de75699e68 100644 --- a/rpc/src/module/net.rs +++ b/rpc/src/module/net.rs @@ -8,7 +8,7 @@ use ckb_jsonrpc_types::{ use ckb_network::{extract_peer_id, multiaddr::Multiaddr, NetworkController}; use ckb_sync::SyncShared; use ckb_systemtime::unix_time_as_millis; -use ckb_types::packed; +use ckb_types::prelude::{Pack, Unpack}; use jsonrpc_core::Result; use jsonrpc_utils::rpc; use std::sync::Arc; @@ -740,14 +740,13 @@ impl NetRpc for NetRpcImpl { let sync_state = SyncState { ibd: chain.is_initial_block_download(), assume_valid_target_reached: shared.assume_valid_target().is_none(), - assume_valid_target: Into::::into( - shared - .assume_valid_target_specified() - .as_ref() - .clone() - .unwrap_or_default(), - ) - .into(), + assume_valid_target: shared + .assume_valid_target_specified() + .as_ref() + .clone() + .unwrap_or_default() + .pack() + .into(), min_chain_work: min_chain_work.into(), min_chain_work_reached: state.min_chain_work_ready(), best_known_block_number: best_known.number().into(), @@ -756,9 +755,9 @@ impl NetRpc for NetRpcImpl { inflight_blocks_count: (state.read_inflight_blocks().total_inflight_count() as u64) .into(), unverified_tip_number: unverified_tip.number().into(), - unverified_tip_hash: unverified_tip.hash().into(), + unverified_tip_hash: unverified_tip.hash().unpack(), tip_number: chain.tip_number().into(), - tip_hash: chain.tip_hash().into(), + tip_hash: chain.tip_hash().unpack(), fast_time: fast_time.into(), normal_time: normal_time.into(), low_time: low_time.into(), diff --git a/rpc/src/module/pool.rs b/rpc/src/module/pool.rs index 21e239ca42..a9e65da1c3 100644 --- a/rpc/src/module/pool.rs +++ b/rpc/src/module/pool.rs @@ -627,7 +627,7 @@ impl PoolRpc for PoolRpcImpl { let tx_hash = tx.hash(); match submit_tx.unwrap() { - Ok(_) => Ok(tx_hash.into()), + Ok(_) => Ok(tx_hash.unpack()), Err(reject) => Err(RPCError::from_submit_transaction_reject(&reject)), } } @@ -660,7 +660,7 @@ impl PoolRpc for PoolRpcImpl { fn remove_transaction(&self, tx_hash: H256) -> Result { let tx_pool = self.shared.tx_pool_controller(); - tx_pool.remove_local_tx(tx_hash.into()).map_err(|e| { + tx_pool.remove_local_tx(tx_hash.pack()).map_err(|e| { error!("Send remove_tx request error {}", e); RPCError::ckb_internal_error(e) }) @@ -718,7 +718,7 @@ impl PoolRpc for PoolRpcImpl { fn get_pool_tx_detail_info(&self, tx_hash: H256) -> Result { let tx_pool = self.shared.tx_pool_controller(); let tx_detail = tx_pool - .get_tx_detail(tx_hash.into()) + .get_tx_detail(tx_hash.pack()) .map_err(|err| RPCError::custom(RPCError::CKBInternalError, err.to_string()))?; Ok(tx_detail.into()) } diff --git a/rpc/src/module/stats.rs b/rpc/src/module/stats.rs index 8df7056955..0dececa47f 100644 --- a/rpc/src/module/stats.rs +++ b/rpc/src/module/stats.rs @@ -3,6 +3,7 @@ use ckb_jsonrpc_types::{AlertMessage, ChainInfo, DeploymentInfo, DeploymentPos, use ckb_network_alert::notifier::Notifier as AlertNotifier; use ckb_shared::shared::Shared; use ckb_traits::HeaderFieldsProvider; +use ckb_types::prelude::Unpack; use ckb_util::Mutex; use jsonrpc_core::Result; use jsonrpc_utils::rpc; @@ -178,7 +179,7 @@ impl StatsRpc for StatsRpcImpl { .collect(); Ok(DeploymentsInfo { - hash: snapshot.tip_hash().into(), + hash: snapshot.tip_hash().unpack(), epoch: snapshot.tip_header().epoch().number().into(), deployments, }) diff --git a/rpc/src/module/test.rs b/rpc/src/module/test.rs index a6acf8f08a..1974b39404 100644 --- a/rpc/src/module/test.rs +++ b/rpc/src/module/test.rs @@ -621,7 +621,7 @@ impl IntegrationTestRpc for IntegrationTestRpcImpl { } } if ret.is_ok() { - Ok(Some(block.hash().into())) + Ok(Some(block.hash().unpack())) } else { error!("process_block_without_verify error: {:?}", ret); Ok(None) @@ -632,7 +632,7 @@ impl IntegrationTestRpc for IntegrationTestRpcImpl { let header = { let snapshot = self.shared.snapshot(); let header = snapshot - .get_block_header(&target_tip_hash.into()) + .get_block_header(&target_tip_hash.pack()) .ok_or_else(|| { RPCError::custom(RPCError::Invalid, "block not found".to_string()) })?; @@ -706,7 +706,7 @@ impl IntegrationTestRpc for IntegrationTestRpcImpl { error!("Send notify_txs request error {}", e); return Err(RPCError::ckb_internal_error(e)); } - Ok(tx_hash.into()) + Ok(tx_hash.unpack()) } fn generate_block_with_template(&self, block_template: BlockTemplate) -> Result { @@ -722,7 +722,7 @@ impl IntegrationTestRpc for IntegrationTestRpcImpl { let snapshot: &Snapshot = &self.shared.snapshot(); let consensus = snapshot.consensus(); let parent_header = snapshot - .get_block_header(&(&block_template.parent_hash).into()) + .get_block_header(&block_template.parent_hash.pack()) .expect("parent header should be stored"); let mut seen_inputs = HashSet::new(); @@ -800,7 +800,7 @@ impl IntegrationTestRpc for IntegrationTestRpcImpl { let tx_hash = tx.hash(); match submit_tx.unwrap() { - Ok(_) => Ok(tx_hash.into()), + Ok(_) => Ok(tx_hash.unpack()), Err(reject) => Err(RPCError::from_submit_transaction_reject(&reject)), } } @@ -825,6 +825,6 @@ impl IntegrationTestRpcImpl { error!("Broadcast new block failed: {:?}", err); } - Ok(block_view.header().hash().into()) + Ok(block_view.header().hash().unpack()) } } diff --git a/rpc/src/tests/examples.rs b/rpc/src/tests/examples.rs index 0b2fbd69dc..03afbb9d3c 100644 --- a/rpc/src/tests/examples.rs +++ b/rpc/src/tests/examples.rs @@ -18,7 +18,7 @@ use std::path::PathBuf; use ckb_types::{ core::{capacity_bytes, Capacity, TransactionBuilder, TransactionView}, h256, - packed::{self, CellDep, CellInput, CellOutputBuilder, OutPoint}, + packed::{CellDep, CellInput, CellOutputBuilder, OutPoint}, prelude::*, H256, }; @@ -102,10 +102,10 @@ fn collect_code_block( } fn construct_example_transaction() -> TransactionView { - let previous_output = OutPoint::new(EXAMPLE_TX_PARENT.clone().into(), 0); + let previous_output = OutPoint::new(EXAMPLE_TX_PARENT.clone().pack(), 0); let input = CellInput::new(previous_output, 0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_cell().2.clone()) .build(); let cell_dep = CellDep::new_builder() @@ -114,7 +114,7 @@ fn construct_example_transaction() -> TransactionView { TransactionBuilder::default() .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(cell_dep) .header_dep(always_success_consensus().genesis_hash()) .build() @@ -278,7 +278,7 @@ impl RpcTestSuite { let example_tx = construct_example_transaction(); assert_eq!( EXAMPLE_TX_HASH, - example_tx.hash().into(), + example_tx.hash().unpack(), "Expect the example tx hash match the constant" ); let example_tx: ckb_jsonrpc_types::Transaction = example_tx.data().into(); diff --git a/rpc/src/tests/mod.rs b/rpc/src/tests/mod.rs index 800066113b..59a2191b1b 100644 --- a/rpc/src/tests/mod.rs +++ b/rpc/src/tests/mod.rs @@ -11,6 +11,7 @@ use ckb_types::{ TransactionView, }, packed::{CellInput, OutPoint}, + prelude::*, }; use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; @@ -198,10 +199,10 @@ fn next_block(shared: &Shared, parent: &HeaderView) -> BlockView { BlockBuilder::default() .transaction(cellbase) .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .timestamp(parent.timestamp() + 1) - .compact_target(epoch.compact_target()) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .timestamp((parent.timestamp() + 1).pack()) + .compact_target(epoch.compact_target().pack()) .dao(dao) .build() } @@ -215,7 +216,7 @@ fn always_success_transaction() -> TransactionView { TransactionBuilder::default() .input(CellInput::new(OutPoint::null(), 0)) .output(always_success_cell.clone()) - .output_data(always_success_cell_data) + .output_data(always_success_cell_data.to_owned().pack()) .witness(always_success_script.clone().into_witness()) .build() } diff --git a/rpc/src/tests/module/miner.rs b/rpc/src/tests/module/miner.rs index 29b0a6d252..42f9bbb325 100644 --- a/rpc/src/tests/module/miner.rs +++ b/rpc/src/tests/module/miner.rs @@ -3,7 +3,7 @@ use ckb_store::ChainStore; use ckb_test_chain_utils::{always_success_cell, always_success_consensus}; use ckb_types::{ core::{capacity_bytes, Capacity, TransactionBuilder}, - packed::{self, CellDep, CellInput, CellOutputBuilder, OutPoint}, + packed::{CellDep, CellInput, CellOutputBuilder, OutPoint}, prelude::*, }; use serde_json::json; @@ -31,7 +31,7 @@ fn test_get_block_template_cache() { parent .header() .as_advanced_builder() - .timestamp(parent.header().timestamp() + 1) + .timestamp((parent.header().timestamp() + 1).pack()) .build(), ) .build(); @@ -67,7 +67,7 @@ fn test_get_block_template_cache() { let input = CellInput::new(previous_output, 0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_cell().2.clone()) .build(); let cell_dep = CellDep::new_builder() @@ -76,7 +76,7 @@ fn test_get_block_template_cache() { let tx = TransactionBuilder::default() .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(cell_dep) .build(); diff --git a/rpc/src/tests/module/pool.rs b/rpc/src/tests/module/pool.rs index 560d3d6bc0..f96bb1f24b 100644 --- a/rpc/src/tests/module/pool.rs +++ b/rpc/src/tests/module/pool.rs @@ -151,7 +151,8 @@ fn test_send_transaction_exceeded_maximum_ancestors_count() { Capacity::bytes(1000) .unwrap() .safe_sub(Capacity::shannons(i * 41 * 1000)) - .unwrap(), + .unwrap() + .pack(), ) .lock(always_success_cell().2.clone()) .build(); @@ -161,7 +162,7 @@ fn test_send_transaction_exceeded_maximum_ancestors_count() { let tx = TransactionBuilder::default() .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(cell_dep) .build(); let new_tx: ckb_jsonrpc_types::Transaction = tx.data().into(); @@ -190,8 +191,8 @@ fn build_tx( ) -> core::TransactionView { let lock = packed::ScriptBuilder::default() .code_hash(code_hash.clone()) - .hash_type(hash_type) - .args(args.as_slice()) + .hash_type(hash_type.into()) + .args(args.pack()) .build(); core::TransactionBuilder::default() .output(packed::CellOutput::new_builder().lock(lock).build()) @@ -207,18 +208,18 @@ fn build_tx_with_type( ) -> core::TransactionView { let lock = packed::ScriptBuilder::default() .code_hash(lock_code_hash.clone()) - .hash_type(lock_hash_type) - .args(lock_args) + .hash_type(lock_hash_type.into()) + .args(lock_args.pack()) .build(); let type_ = packed::ScriptBuilder::default() .code_hash(type_code_hash.clone()) - .hash_type(type_hash_type) + .hash_type(type_hash_type.into()) .build(); core::TransactionBuilder::default() .output( packed::CellOutput::new_builder() .lock(lock) - .type_(Some(type_)) + .type_(Some(type_).pack()) .build(), ) .build() diff --git a/rpc/src/tests/setup.rs b/rpc/src/tests/setup.rs index 03a1675973..888186fe57 100644 --- a/rpc/src/tests/setup.rs +++ b/rpc/src/tests/setup.rs @@ -23,7 +23,7 @@ use std::{thread::sleep, time::Duration}; use ckb_types::{ core::{BlockBuilder, Capacity, EpochNumberWithFraction, Ratio}, h256, - packed::{self, AlertBuilder, RawAlertBuilder}, + packed::{AlertBuilder, RawAlertBuilder}, prelude::*, }; @@ -40,9 +40,9 @@ pub(crate) fn always_success_consensus() -> Consensus { let always_success_tx = always_success_transaction(); let dao = genesis_dao_data(vec![&always_success_tx]).unwrap(); let genesis = BlockBuilder::default() - .timestamp(GENESIS_TIMESTAMP) - .compact_target(GENESIS_TARGET) - .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0)) + .timestamp(GENESIS_TIMESTAMP.pack()) + .compact_target(GENESIS_TARGET.pack()) + .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0).pack()) .dao(dao) .transaction(always_success_tx) .build(); @@ -78,7 +78,7 @@ pub(crate) fn setup_rpc_test_suite(height: u64, consensus: Option) -> code_hash: h256!("0x1892ea40d82b53c678ff88312450bbb17e164d7a3e0a90941aa58839f56f8df2"), hash_type: ckb_jsonrpc_types::ScriptHashType::Type, args: json_bytes("0xb2e61ff569acf041b3c2c17724e2379c581eeac3"), - message: Into::::into("message").into(), + message: "message".pack().into(), use_binary_version_as_message_prefix: true, binary_version: "TEST".to_string(), update_interval_millis: 800, @@ -154,12 +154,12 @@ pub(crate) fn setup_rpc_test_suite(height: u64, consensus: Option) -> let alert = AlertBuilder::default() .raw( RawAlertBuilder::default() - .id(42u32) - .min_version(Some("0.0.1".to_string())) - .max_version(Some("1.0.0".to_string())) - .priority(1u32) - .notice_until(ALERT_UNTIL_TIMESTAMP * 1000) - .message("An example alert message!") + .id(42u32.pack()) + .min_version(Some("0.0.1".to_string()).pack()) + .max_version(Some("1.0.0".to_string()).pack()) + .priority(1u32.pack()) + .notice_until((ALERT_UNTIL_TIMESTAMP * 1000).pack()) + .message("An example alert message!".pack()) .build(), ) .build(); @@ -258,7 +258,7 @@ pub(crate) fn setup_rpc_test_suite(height: u64, consensus: Option) -> parent .header() .as_advanced_builder() - .timestamp(parent.header().timestamp() + 1) + .timestamp((parent.header().timestamp() + 1).pack()) .build(), ) .build(); diff --git a/script/fuzz/fuzz_targets/syscall_exec.rs b/script/fuzz/fuzz_targets/syscall_exec.rs index 63e6d69ccd..7e03cabcb5 100644 --- a/script/fuzz/fuzz_targets/syscall_exec.rs +++ b/script/fuzz/fuzz_targets/syscall_exec.rs @@ -45,16 +45,16 @@ impl ExtensionProvider for MockDataLoader { fn mock_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64.into()) - .block_epoch(0u64.into()) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32.into()) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } static CALLER: &[u8] = include_bytes!("../programs/exec_caller"); @@ -103,13 +103,13 @@ fn run(data: FuzzData) { }; let exec_caller_cell = CellOutput::new_builder() - .capacity(Capacity::bytes(exec_caller_cell_data.len()).unwrap().into()) + .capacity(Capacity::bytes(exec_caller_cell_data.len()).unwrap().pack()) .build(); let exec_callee_cell = CellOutput::new_builder() - .capacity(Capacity::bytes(exec_callee_cell_data.len()).unwrap().into()) + .capacity(Capacity::bytes(exec_callee_cell_data.len()).unwrap().pack()) .build(); let exec_caller_data_cell = CellOutput::new_builder() - .capacity(Capacity::bytes(exec_caller_data_data.len()).unwrap().into()) + .capacity(Capacity::bytes(exec_caller_data_data.len()).unwrap().pack()) .build(); let exec_caller_script = Script::new_builder() @@ -117,14 +117,14 @@ fn run(data: FuzzData) { .code_hash(CellOutput::calc_data_hash(&exec_caller_cell_data)) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100).into()) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); let transaction = TransactionBuilder::default() .input(input) - .set_witnesses(vec![exec_callee_cell_data.into()]) + .set_witnesses(vec![exec_callee_cell_data.pack()]) .build(); let dummy_cell = CellMetaBuilder::from_cell_output(output, Bytes::new()) @@ -154,7 +154,7 @@ fn run(data: FuzzData) { let provider = MockDataLoader {}; let consensus = ConsensusBuilder::default().build(); let tx_verify_env = - TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.into()).build()); + TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.pack()).build()); let verifier = TransactionScriptsVerifier::new( rtx.into(), provider, diff --git a/script/fuzz/fuzz_targets/syscall_spawn.rs b/script/fuzz/fuzz_targets/syscall_spawn.rs index 7c87e9f879..8782bee23a 100644 --- a/script/fuzz/fuzz_targets/syscall_spawn.rs +++ b/script/fuzz/fuzz_targets/syscall_spawn.rs @@ -47,16 +47,16 @@ impl ExtensionProvider for MockDataLoader { fn mock_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64) - .block_epoch(0u64) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } static PROGRAM_DATA: &[u8] = include_bytes!("../../testdata/spawn_fuzzing"); @@ -69,7 +69,7 @@ fn run(data: &[u8]) { let split_offset = usize::min(split_offset, data.len() - 1); let parent_witness = Bytes::copy_from_slice(&data[0..split_offset]); let child_witness = Bytes::copy_from_slice(&data[split_offset..]); - let witnesses = vec![parent_witness.into(), child_witness.into()]; + let witnesses = vec![parent_witness.pack(), child_witness.pack()]; let transaction = TransactionBuilder::default() .input(CellInput::new(OutPoint::null(), 0)) @@ -83,17 +83,17 @@ fn run(data: &[u8]) { .build(); let dep_cell = CellMetaBuilder::from_cell_output( CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(), data, ) .transaction_info(mock_transaction_info()) - .out_point(OutPoint::new(h256!("0x0"), 0)) + .out_point(OutPoint::new(h256!("0x0").pack(), 0)) .build(); let input_cell = CellMetaBuilder::from_cell_output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(), Bytes::new(), @@ -121,7 +121,7 @@ fn run(data: &[u8]) { .hardfork_switch(hardfork_switch) .build(); let tx_verify_env = - TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0).build()); + TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.pack()).build()); let verifier = TransactionScriptsVerifier::new( rtx.into(), provider, diff --git a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data0.rs b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data0.rs index 3c2591d51c..ccb922337e 100644 --- a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data0.rs +++ b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data0.rs @@ -47,16 +47,16 @@ impl ExtensionProvider for MockDataLoader { fn mock_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64.into()) - .block_epoch(0u64.into()) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32.into()) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } fn run(data: &[u8]) { @@ -71,17 +71,17 @@ fn run(data: &[u8]) { .build(); let dep_cell = CellMetaBuilder::from_cell_output( CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap().into()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(), data, ) .transaction_info(mock_transaction_info()) - .out_point(OutPoint::new(h256!("0x0").into(), 0)) + .out_point(OutPoint::new(h256!("0x0").pack(), 0)) .build(); let input_cell = CellMetaBuilder::from_cell_output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100).into()) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(), Bytes::new(), @@ -105,7 +105,7 @@ fn run(data: &[u8]) { .hardfork_switch(hardfork_switch) .build(); let tx_verify_env = - TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.into()).build()); + TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.pack()).build()); let verifier = TransactionScriptsVerifier::new( rtx.into(), provider, diff --git a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data1.rs b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data1.rs index b005620b01..f9be40d6be 100644 --- a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data1.rs +++ b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data1.rs @@ -47,16 +47,16 @@ impl ExtensionProvider for MockDataLoader { fn mock_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64.into()) - .block_epoch(0u64.into()) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32.into()) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } fn run(data: &[u8]) { @@ -71,17 +71,17 @@ fn run(data: &[u8]) { .build(); let dep_cell = CellMetaBuilder::from_cell_output( CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap().into()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(), data, ) .transaction_info(mock_transaction_info()) - .out_point(OutPoint::new(h256!("0x0").into(), 0)) + .out_point(OutPoint::new(h256!("0x0").pack(), 0)) .build(); let input_cell = CellMetaBuilder::from_cell_output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100).into()) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(), Bytes::new(), @@ -105,7 +105,7 @@ fn run(data: &[u8]) { .hardfork_switch(hardfork_switch) .build(); let tx_verify_env = - TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.into()).build()); + TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.pack()).build()); let verifier = TransactionScriptsVerifier::new( rtx.into(), provider, diff --git a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data2.rs b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data2.rs index c14fb5d109..8c05a5baab 100644 --- a/script/fuzz/fuzz_targets/transaction_scripts_verifier_data2.rs +++ b/script/fuzz/fuzz_targets/transaction_scripts_verifier_data2.rs @@ -47,16 +47,16 @@ impl ExtensionProvider for MockDataLoader { fn mock_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64.into()) - .block_epoch(0u64.into()) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32.into()) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } fn run(data: &[u8]) { @@ -71,17 +71,17 @@ fn run(data: &[u8]) { .build(); let dep_cell = CellMetaBuilder::from_cell_output( CellOutput::new_builder() - .capacity(Capacity::bytes(data.len()).unwrap().into()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(), data, ) .transaction_info(mock_transaction_info()) - .out_point(OutPoint::new(h256!("0x0").into(), 0)) + .out_point(OutPoint::new(h256!("0x0").pack(), 0)) .build(); let input_cell = CellMetaBuilder::from_cell_output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100).into()) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(), Bytes::new(), @@ -105,7 +105,7 @@ fn run(data: &[u8]) { .hardfork_switch(hardfork_switch) .build(); let tx_verify_env = - TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.into()).build()); + TxVerifyEnv::new_submit(&HeaderView::new_advanced_builder().epoch(0.pack()).build()); let verifier = TransactionScriptsVerifier::new( rtx.into(), provider, diff --git a/script/src/syscalls/load_cell.rs b/script/src/syscalls/load_cell.rs index e7f4253e1e..0dee77937f 100644 --- a/script/src/syscalls/load_cell.rs +++ b/script/src/syscalls/load_cell.rs @@ -109,7 +109,7 @@ impl LoadCell
{ let result = match field { CellField::Capacity => { - let capacity: Capacity = output.capacity().into(); + let capacity: Capacity = output.capacity().unpack(); let mut buffer = vec![]; buffer.write_u64::(capacity.as_u64())?; (SUCCESS, store_data(machine, &buffer)?) diff --git a/script/src/syscalls/load_input.rs b/script/src/syscalls/load_input.rs index 33f427e822..8f19c0d6c9 100644 --- a/script/src/syscalls/load_input.rs +++ b/script/src/syscalls/load_input.rs @@ -80,7 +80,7 @@ impl LoadInput { } InputField::Since => { let mut buffer = vec![]; - buffer.write_u64::(input.since().into())?; + buffer.write_u64::(input.since().unpack())?; store_data(machine, &buffer) } } diff --git a/script/src/syscalls/tests/utils.rs b/script/src/syscalls/tests/utils.rs index 920f362265..de9ca6f542 100644 --- a/script/src/syscalls/tests/utils.rs +++ b/script/src/syscalls/tests/utils.rs @@ -41,7 +41,7 @@ pub(crate) fn new_mock_data_loader() -> MockDataLoader { pub(crate) fn build_cell_meta(capacity_bytes: usize, data: Bytes) -> CellMeta { let capacity = Capacity::bytes(capacity_bytes).expect("capacity bytes overflow"); - let builder = CellOutput::new_builder().capacity(capacity); + let builder = CellOutput::new_builder().capacity(capacity.pack()); let data_hash = CellOutput::calc_data_hash(&data); CellMeta { out_point: OutPoint::default(), diff --git a/script/src/syscalls/tests/vm_latest/syscalls_1.rs b/script/src/syscalls/tests/vm_latest/syscalls_1.rs index 99bb2ec7b1..761537e2ff 100644 --- a/script/src/syscalls/tests/vm_latest/syscalls_1.rs +++ b/script/src/syscalls/tests/vm_latest/syscalls_1.rs @@ -7,7 +7,7 @@ use ckb_types::{ Capacity, EpochNumberWithFraction, HeaderBuilder, ScriptHashType, TransactionBuilder, TransactionInfo, }, - packed::{self, CellInput, CellOutput, OutPoint, Script, ScriptBuilder}, + packed::{CellInput, CellOutput, OutPoint, Script, ScriptBuilder}, prelude::*, H256, }; @@ -438,7 +438,7 @@ fn _test_load_cell_capacity(capacity: Capacity) -> Result<(), TestCaseError> { let input_cell = CellMeta { out_point: OutPoint::default(), transaction_info: None, - cell_output: CellOutput::new_builder().capacity(capacity).build(), + cell_output: CellOutput::new_builder().capacity(capacity.pack()).build(), data_bytes: 0, mem_cell_data: Some(data), mem_cell_data_hash: Some(data_hash), @@ -499,7 +499,7 @@ fn _test_load_cell_occupied_capacity(data: &[u8]) -> Result<(), TestCaseError> { let input_cell = CellMeta { out_point: OutPoint::default(), transaction_info: None, - cell_output: CellOutput::new_builder().capacity(100).build(), + cell_output: CellOutput::new_builder().capacity(100.pack()).build(), data_bytes: 0, mem_cell_data: Some(data), mem_cell_data_hash: Some(data_hash), @@ -561,7 +561,7 @@ fn test_load_missing_data_hash() { let input_cell = CellMeta { out_point: OutPoint::default(), transaction_info: None, - cell_output: CellOutput::new_builder().capacity(100).build(), + cell_output: CellOutput::new_builder().capacity(100.pack()).build(), data_bytes: 0, mem_cell_data: None, mem_cell_data_hash: None, @@ -655,7 +655,7 @@ fn _test_load_header( machine.set_register(A4, source); //source: 4 header machine.set_register(A7, LOAD_HEADER_SYSCALL_NUMBER); // syscall number - let data_hash = blake2b_256(data); + let data_hash = blake2b_256(data).pack(); let header = HeaderBuilder::default() .transactions_root(data_hash) .build(); @@ -671,7 +671,7 @@ fn _test_load_header( block_epoch: header.epoch(), index: 1, }), - cell_output: CellOutput::new_builder().capacity(100).build(), + cell_output: CellOutput::new_builder().capacity(100.pack()).build(), data_bytes: 0, mem_cell_data: None, mem_cell_data_hash: None, @@ -775,9 +775,9 @@ fn _test_load_header_by_field(data: &[u8], field: HeaderField) -> Result<(), Tes let data_hash: H256 = blake2b_256(data).into(); let epoch = EpochNumberWithFraction::new(1, 40, 1000); let header = HeaderBuilder::default() - .transactions_root(data_hash) - .number(2000) - .epoch(epoch) + .transactions_root(data_hash.pack()) + .number(2000.pack()) + .epoch(epoch.pack()) .build(); let mut correct_data = [0u8; 8]; @@ -847,7 +847,9 @@ fn _test_load_tx_hash(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A2, 0); // offset machine.set_register(A7, LOAD_TX_HASH_SYSCALL_NUMBER); // syscall number - let transaction_view = TransactionBuilder::default().output_data(data).build(); + let transaction_view = TransactionBuilder::default() + .output_data(data.pack()) + .build(); let hash = transaction_view.hash(); let hash_len = 32u64; @@ -896,7 +898,9 @@ fn _test_load_tx(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A2, 0); // offset machine.set_register(A7, LOAD_TRANSACTION_SYSCALL_NUMBER); // syscall number - let transaction_view = TransactionBuilder::default().output_data(data).build(); + let transaction_view = TransactionBuilder::default() + .output_data(data.pack()) + .build(); let tx = transaction_view.data(); let tx_len = transaction_view.data().as_slice().len() as u64; @@ -946,8 +950,8 @@ fn _test_load_current_script_hash(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_SCRIPT_HASH_SYSCALL_NUMBER); // syscall number let script = Script::new_builder() - .args(Bytes::from(data.to_owned())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(data.to_owned()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let hash = script.calc_script_hash(); let data = hash.raw_data(); @@ -1001,8 +1005,8 @@ fn _test_load_input_lock_script_hash(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_CELL_BY_FIELD_SYSCALL_NUMBER); // syscall number let script = Script::new_builder() - .args(Bytes::from(data.to_owned())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(data.to_owned()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let h = script.calc_script_hash(); let hash = h.as_bytes(); @@ -1067,8 +1071,8 @@ fn _test_load_input_lock_script(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_CELL_BY_FIELD_SYSCALL_NUMBER); // syscall number let script = Script::new_builder() - .args(Bytes::from(data.to_owned())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(data.to_owned()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let lock = script.as_slice(); @@ -1135,8 +1139,8 @@ fn _test_load_input_type_script(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_CELL_BY_FIELD_SYSCALL_NUMBER); // syscall number let script = Script::new_builder() - .args(Bytes::from(data.to_owned())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(data.to_owned()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let type_ = script.as_slice(); @@ -1145,7 +1149,7 @@ fn _test_load_input_type_script(data: &[u8]) -> Result<(), TestCaseError> { .cell_output .clone() .as_builder() - .type_(Some(script.to_owned())) + .type_(Some(script.to_owned()).pack()) .build(); input_cell.cell_output = output_with_type; @@ -1203,8 +1207,8 @@ fn _test_load_input_type_script_hash(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_CELL_BY_FIELD_SYSCALL_NUMBER); // syscall number let script = Script::new_builder() - .args(Bytes::from(data.to_owned())) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(data.to_owned()).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let type_h = script.calc_script_hash(); @@ -1215,7 +1219,7 @@ fn _test_load_input_type_script_hash(data: &[u8]) -> Result<(), TestCaseError> { .cell_output .clone() .as_builder() - .type_(Some(script)) + .type_(Some(script).pack()) .build(); input_cell.cell_output = output_with_type; let outputs = Arc::new(vec![]); @@ -1270,7 +1274,7 @@ fn _test_load_witness(data: &[u8], source: SourceEntry) -> Result<(), TestCaseEr machine.set_register(A4, u64::from(Source::Transaction(source))); //source machine.set_register(A7, LOAD_WITNESS_SYSCALL_NUMBER); // syscall number - let witness: packed::Bytes = Bytes::from(data.to_owned()).into(); + let witness = Bytes::from(data.to_owned()).pack(); let witness_correct_data = witness.raw_data(); @@ -1279,7 +1283,7 @@ fn _test_load_witness(data: &[u8], source: SourceEntry) -> Result<(), TestCaseEr let group_outputs = Arc::new(vec![]); let rtx = Arc::new(ResolvedTransaction { transaction: TransactionBuilder::default() - .witnesses(Into::::into(witnesses)) + .witnesses(witnesses.pack()) .build(), resolved_cell_deps: vec![], resolved_inputs: vec![], @@ -1334,17 +1338,17 @@ fn _test_load_group_witness(data: &[u8], source: SourceEntry) -> Result<(), Test machine.set_register(A4, u64::from(Source::Group(source))); //source machine.set_register(A7, LOAD_WITNESS_SYSCALL_NUMBER); // syscall number - let witness: packed::Bytes = Bytes::from(data.to_owned()).into(); + let witness = Bytes::from(data.to_owned()).pack(); let witness_correct_data = witness.raw_data(); - let dummy_witness = Bytes::default().into(); + let dummy_witness = Bytes::default().pack(); let witnesses = vec![dummy_witness, witness]; let group_inputs = Arc::new(vec![1]); let group_outputs = Arc::new(vec![1]); let rtx = Arc::new(ResolvedTransaction { transaction: TransactionBuilder::default() - .witnesses(Into::::into(witnesses)) + .witnesses(witnesses.pack()) .build(), resolved_cell_deps: vec![], resolved_inputs: vec![], @@ -1393,7 +1397,7 @@ fn _test_load_script(data: &[u8]) -> Result<(), TestCaseError> { machine.set_register(A7, LOAD_SCRIPT_SYSCALL_NUMBER); // syscall number let script = ScriptBuilder::default() - .args(Bytes::from(data.to_owned())) + .args(Bytes::from(data.to_owned()).pack()) .build(); let script_correct_data = script.as_slice(); @@ -1454,7 +1458,7 @@ fn _test_load_cell_data_as_code( let data_loader = new_mock_data_loader(); let rtx = Arc::new(ResolvedTransaction { transaction: TransactionBuilder::default() - .output_data(data.clone()) + .output_data(data.pack()) .build(), resolved_cell_deps: vec![dep_cell], resolved_inputs: vec![input_cell], @@ -1527,7 +1531,7 @@ fn _test_load_cell_data( let rtx = Arc::new(ResolvedTransaction { transaction: TransactionBuilder::default() - .output_data(data.clone()) + .output_data(data.pack()) .build(), resolved_cell_deps: vec![dep_cell], resolved_inputs: vec![input_cell], @@ -1958,10 +1962,15 @@ fn _test_load_input( prop_assert!(machine.memory_mut().store64(&size_addr, &addr_size).is_ok()); let data = Bytes::from(data.to_owned()); - let hash = blake2b_256(&data); + let hash = blake2b_256(&data).pack(); let input = CellInput::new_builder() - .previous_output(OutPoint::new_builder().tx_hash(hash).index(0u32).build()) - .since(10u64) + .previous_output( + OutPoint::new_builder() + .tx_hash(hash) + .index(0u32.pack()) + .build(), + ) + .since(10u64.pack()) .build(); let previous_output = input.previous_output(); @@ -1979,7 +1988,7 @@ fn _test_load_input( match field { InputField::OutPoint => previous_output.as_slice(), InputField::Since => { - buffer.write_u64::(input.since().into())?; + buffer.write_u64::(input.since().unpack())?; buffer.as_slice() } } diff --git a/script/src/syscalls/tests/vm_latest/syscalls_2.rs b/script/src/syscalls/tests/vm_latest/syscalls_2.rs index 07d2eb6db2..4cac872f56 100644 --- a/script/src/syscalls/tests/vm_latest/syscalls_2.rs +++ b/script/src/syscalls/tests/vm_latest/syscalls_2.rs @@ -87,14 +87,14 @@ fn _test_load_extension( block_epoch: header.epoch(), index: 1, }), - cell_output: CellOutput::new_builder().capacity(100).build(), + cell_output: CellOutput::new_builder().capacity(100.pack()).build(), data_bytes: 0, mem_cell_data: None, mem_cell_data_hash: None, }; let mut extensions = HashMap::default(); - extensions.insert(header.hash(), (&data).into()); + extensions.insert(header.hash(), data.pack()); let data_loader = MockDataLoader { extensions, ..Default::default() diff --git a/script/src/verify.rs b/script/src/verify.rs index a79e3d8c92..f91328e598 100644 --- a/script/src/verify.rs +++ b/script/src/verify.rs @@ -407,7 +407,7 @@ where .map(|(index, (cell_output, data))| { let out_point = OutPoint::new_builder() .tx_hash(tx_hash.clone()) - .index(index) + .index(index.pack()) .build(); let data_hash = CellOutput::calc_data_hash(&data); CellMeta { @@ -962,7 +962,7 @@ where group: &ScriptGroup, max_cycles: Cycle, ) -> Result { - if group.script.code_hash() == TYPE_ID_CODE_HASH.into() + if group.script.code_hash() == TYPE_ID_CODE_HASH.pack() && Into::::into(group.script.hash_type()) == Into::::into(ScriptHashType::Type) { let verifier = TypeIdSystemScript { @@ -1000,7 +1000,7 @@ where max_cycles: Cycle, state: &Option, ) -> Result { - if group.script.code_hash() == TYPE_ID_CODE_HASH.into() + if group.script.code_hash() == TYPE_ID_CODE_HASH.pack() && Into::::into(group.script.hash_type()) == Into::::into(ScriptHashType::Type) { let verifier = TypeIdSystemScript { @@ -1078,7 +1078,7 @@ where max_cycles: Cycle, command_rx: &mut Receiver, ) -> Result { - if group.script.code_hash() == TYPE_ID_CODE_HASH.into() + if group.script.code_hash() == TYPE_ID_CODE_HASH.pack() && Into::::into(group.script.hash_type()) == Into::::into(ScriptHashType::Type) { let verifier = TypeIdSystemScript { diff --git a/script/src/verify/tests/ckb_latest/features_since_v2019.rs b/script/src/verify/tests/ckb_latest/features_since_v2019.rs index 2cfa0ea806..a69c887575 100644 --- a/script/src/verify/tests/ckb_latest/features_since_v2019.rs +++ b/script/src/verify/tests/ckb_latest/features_since_v2019.rs @@ -25,7 +25,7 @@ fn check_always_success_hash() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script.clone()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -68,13 +68,13 @@ fn check_signature() { args.extend(&to_hex_signature(&signature)); let code_hash = blake2b_256(&buffer); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); let dep_cell = CellMetaBuilder::from_cell_output(output, data) .transaction_info(default_transaction_info()) @@ -82,9 +82,9 @@ fn check_signature() { .build(); let script = Script::new_builder() - .args(Bytes::from(args)) - .code_hash(code_hash) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(args).pack()) + .code_hash(code_hash.pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -94,7 +94,7 @@ fn check_signature() { .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let dummy_cell = create_dummy_cell(output); @@ -137,19 +137,22 @@ fn check_signature_referenced_via_type_hash() { args.extend(&to_hex_pubkey(&pubkey)); args.extend(&to_hex_signature(&signature)); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) - .type_(Some( - Script::new_builder() - .code_hash(h256!("0x123456abcd90")) - .hash_type(ScriptHashType::Data) - .build(), - )) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) + .type_( + Some( + Script::new_builder() + .code_hash(h256!("0x123456abcd90").pack()) + .hash_type(ScriptHashType::Data.into()) + .build(), + ) + .pack(), + ) .build(); let type_hash = output.type_().to_opt().as_ref().unwrap().calc_script_hash(); let dep_cell = CellMetaBuilder::from_cell_output(output, data) @@ -158,9 +161,9 @@ fn check_signature_referenced_via_type_hash() { .build(); let script = Script::new_builder() - .args(Bytes::from(args)) + .args(Bytes::from(args).pack()) .code_hash(type_hash) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -170,7 +173,7 @@ fn check_signature_referenced_via_type_hash() { .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let dummy_cell = create_dummy_cell(output); @@ -210,20 +213,20 @@ fn check_invalid_signature() { args.extend(&to_hex_signature(&signature)); let code_hash = blake2b_256(&buffer); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder().out_point(dep_out_point).build(); let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); let dep_cell = CellMetaBuilder::from_cell_output(output, data) .transaction_info(default_transaction_info()) .build(); let script = Script::new_builder() - .args(Bytes::from(args)) - .code_hash(code_hash) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(args).pack()) + .code_hash(code_hash.pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -233,7 +236,7 @@ fn check_invalid_signature() { .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script.clone()) .build(); let dummy_cell = create_dummy_cell(output); @@ -267,14 +270,14 @@ fn check_invalid_dep_reference() { args.extend(&to_hex_pubkey(&pubkey)); args.extend(&to_hex_signature(&signature)); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder().out_point(dep_out_point).build(); - let script_code_hash: Byte32 = blake2b_256(&buffer).into(); + let script_code_hash = blake2b_256(&buffer).pack(); let script = Script::new_builder() - .args(Bytes::from(args)) + .args(Bytes::from(args).pack()) .code_hash(script_code_hash.clone()) - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -284,7 +287,7 @@ fn check_invalid_dep_reference() { .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let dummy_cell = create_dummy_cell(output); @@ -322,7 +325,7 @@ fn check_output_contract() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script.clone()) .build(); let dummy_cell = create_dummy_cell(output); @@ -334,28 +337,28 @@ fn check_output_contract() { .build(); let script = Script::new_builder() - .args(Bytes::from(args)) - .code_hash(blake2b_256(&buffer)) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(args).pack()) + .code_hash(blake2b_256(&buffer).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let output_data = Bytes::default(); let output = CellOutputBuilder::default() .lock( Script::new_builder() - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build(), ) - .type_(Some(script)) + .type_(Some(script).pack()) .build(); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let dep_cell = { let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); CellMetaBuilder::from_cell_output(output, data) .transaction_info(default_transaction_info()) @@ -366,7 +369,7 @@ fn check_output_contract() { let transaction = TransactionBuilder::default() .input(input) .output(output) - .output_data(output_data) + .output_data(output_data.pack()) .cell_dep(cell_dep) .build(); @@ -403,7 +406,7 @@ fn check_invalid_output_contract() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script.clone()) .build(); let dummy_cell = create_dummy_cell(output); @@ -415,20 +418,20 @@ fn check_invalid_output_contract() { .build(); let script = Script::new_builder() - .args(Bytes::from(args)) - .code_hash(blake2b_256(&buffer)) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(args).pack()) + .code_hash(blake2b_256(&buffer).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let output = CellOutputBuilder::default() - .type_(Some(script.clone())) + .type_(Some(script.clone()).pack()) .build(); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder().out_point(dep_out_point).build(); let dep_cell = { let dep_cell_data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(dep_cell_data.len()).unwrap()) + .capacity(Capacity::bytes(dep_cell_data.len()).unwrap().pack()) .build(); CellMetaBuilder::from_cell_output(output, dep_cell_data) .transaction_info(default_transaction_info()) @@ -438,7 +441,7 @@ fn check_invalid_output_contract() { let transaction = TransactionBuilder::default() .input(input) .output(output) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .cell_dep(cell_dep) .build(); @@ -474,18 +477,18 @@ fn check_same_lock_and_type_script_are_executed_twice() { args.extend(&to_hex_signature(&signature)); let script = Script::new_builder() - .args(Bytes::from(args)) - .code_hash(blake2b_256(&buffer)) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(args).pack()) + .code_hash(blake2b_256(&buffer).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); let dep_cell = CellMetaBuilder::from_cell_output(output, data) .transaction_info(default_transaction_info()) @@ -499,9 +502,9 @@ fn check_same_lock_and_type_script_are_executed_twice() { // The lock and type scripts here are both executed. let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script.clone()) - .type_(Some(script)) + .type_(Some(script).pack()) .build(); let dummy_cell = create_dummy_cell(output); @@ -524,25 +527,25 @@ fn check_type_id_one_in_one_out() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let transaction = TransactionBuilder::default() @@ -589,25 +592,25 @@ fn check_type_id_one_in_one_out_not_enough_cycles() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let transaction = TransactionBuilder::default() @@ -654,11 +657,11 @@ fn check_type_id_creation() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) .build(); @@ -672,15 +675,15 @@ fn check_type_id_creation() { }; let type_id_script = Script::new_builder() - .args(input_hash) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(input_hash.pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let transaction = TransactionBuilder::default() @@ -721,23 +724,23 @@ fn check_type_id_termination() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) .build(); @@ -779,11 +782,11 @@ fn check_type_id_invalid_creation() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) .build(); @@ -791,7 +794,7 @@ fn check_type_id_invalid_creation() { let mut blake2b = new_blake2b(); blake2b.update(&input.previous_output().tx_hash().as_bytes()); let mut buf = [0; 4]; - LittleEndian::write_u32(&mut buf, input.previous_output().index().into()); + LittleEndian::write_u32(&mut buf, input.previous_output().index().unpack()); blake2b.update(&buf[..]); let mut buf = [0; 8]; LittleEndian::write_u64(&mut buf, 0); @@ -803,15 +806,15 @@ fn check_type_id_invalid_creation() { }; let type_id_script = Script::new_builder() - .args(input_hash) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(input_hash.pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let transaction = TransactionBuilder::default() @@ -855,11 +858,11 @@ fn check_type_id_invalid_creation_length() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) .build(); @@ -867,7 +870,7 @@ fn check_type_id_invalid_creation_length() { let mut blake2b = new_blake2b(); blake2b.update(&input.previous_output().tx_hash().as_bytes()); let mut buf = [0; 4]; - LittleEndian::write_u32(&mut buf, input.previous_output().index().into()); + LittleEndian::write_u32(&mut buf, input.previous_output().index().unpack()); blake2b.update(&buf[..]); let mut buf = [0; 8]; LittleEndian::write_u64(&mut buf, 0); @@ -882,15 +885,15 @@ fn check_type_id_invalid_creation_length() { }; let type_id_script = Script::new_builder() - .args(input_hash) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(input_hash.pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let transaction = TransactionBuilder::default() @@ -934,30 +937,30 @@ fn check_type_id_one_in_two_out() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(2000)) + .capacity(capacity_bytes!(2000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let transaction = TransactionBuilder::default() @@ -1029,19 +1032,19 @@ fn create_rtx_to_load_code_to_stack_then_reuse( vec.extend_from_slice(&flag.to_le_bytes()); vec.extend_from_slice(&size.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.into() + vec.pack() }; let (dyn_lock_cell, dyn_lock_data_hash) = load_cell_from_path("testdata/load_code_to_stack_then_reuse"); let dyn_lock_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(dyn_lock_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(dyn_lock_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1108,7 +1111,7 @@ fn check_debugger() { let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script.clone()) .build(); let dummy_cell = create_dummy_cell(output); @@ -1120,27 +1123,27 @@ fn check_debugger() { .build(); let script = Script::new_builder() - .code_hash(blake2b_256(&buffer)) - .hash_type(ScriptHashType::Data) + .code_hash(blake2b_256(&buffer).pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let output_data = Bytes::default(); let output = CellOutputBuilder::default() .lock( Script::new_builder() - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build(), ) - .type_(Some(script)) + .type_(Some(script).pack()) .build(); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let dep_cell = { let data = Bytes::from(buffer); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) .build(); CellMetaBuilder::from_cell_output(output, data) .transaction_info(default_transaction_info()) @@ -1151,7 +1154,7 @@ fn check_debugger() { let transaction = TransactionBuilder::default() .input(input) .output(output) - .output_data(output_data) + .output_data(output_data.pack()) .cell_dep(cell_dep) .build(); diff --git a/script/src/verify/tests/ckb_latest/features_since_v2021.rs b/script/src/verify/tests/ckb_latest/features_since_v2021.rs index 93e94557bc..cb70fb0b4c 100644 --- a/script/src/verify/tests/ckb_latest/features_since_v2021.rs +++ b/script/src/verify/tests/ckb_latest/features_since_v2021.rs @@ -28,11 +28,11 @@ fn test_hint_instructions() { load_cell_from_path("testdata/cadd_hint_lock"); let always_success_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(always_success_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -73,18 +73,18 @@ fn test_b_extension() { let mut vec = Vec::with_capacity(8 * 2); vec.extend_from_slice(&num0.to_le_bytes()); vec.extend_from_slice(&num1.to_le_bytes()); - vec.into() + vec.pack() }; let (cpop_lock_cell, cpop_lock_data_hash) = load_cell_from_path("testdata/cpop_lock"); let cpop_lock_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(cpop_lock_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(cpop_lock_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -128,11 +128,11 @@ fn test_cycles_difference() { load_cell_from_path("testdata/mop_adc_lock"); let always_success_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(always_success_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -167,11 +167,11 @@ fn check_current_cycles() { load_cell_from_path("testdata/current_cycles"); let current_cycles_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(current_cycles_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(current_cycles_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -199,11 +199,11 @@ fn check_current_cycles_with_snapshot() { load_cell_from_path("testdata/current_cycles_with_snapshot"); let current_cycles_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(current_cycles_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(current_cycles_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -244,11 +244,11 @@ fn check_vm_version() { let (vm_version_cell, vm_version_data_hash) = load_cell_from_path("testdata/vm_version"); let vm_version_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(vm_version_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(vm_version_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -276,11 +276,11 @@ fn check_vm_version_with_snapshot() { load_cell_from_path("testdata/vm_version_with_snapshot"); let vm_version_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(vm_version_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(vm_version_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -323,11 +323,11 @@ fn check_exec_from_cell_data() { let (exec_callee_cell, _exec_callee_data_hash) = load_cell_from_path("testdata/exec_callee"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -356,11 +356,11 @@ fn check_exec_from_witness() { let (exec_callee_cell, _exec_caller_data_hash) = load_cell_from_path("testdata/exec_callee"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -368,7 +368,7 @@ fn check_exec_from_witness() { let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let transaction = TransactionBuilder::default() .input(input) - .set_witnesses(vec![exec_callee_cell_data.into()]) + .set_witnesses(vec![exec_callee_cell_data.pack()]) .build(); let dummy_cell = create_dummy_cell(output); @@ -399,11 +399,11 @@ fn check_exec_wrong_callee_format() { load_cell_from_slice(&[0x00, 0x01, 0x02, 0x03]); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -433,11 +433,11 @@ async fn async_check_exec_wrong_callee_format() { load_cell_from_slice(&[0x00, 0x01, 0x02, 0x03]); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -469,11 +469,11 @@ fn check_exec_big_offset_length() { load_cell_from_slice(&[0x00, 0x01, 0x02, 0x03]); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -500,25 +500,25 @@ fn _check_type_id_one_in_one_out_resume(step_cycles: Cycle) -> Result<(), TestCa let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let transaction = TransactionBuilder::default() @@ -650,25 +650,25 @@ fn _check_type_id_one_in_one_out_resume_with_state( let (always_success_cell, always_success_cell_data, always_success_script) = always_success_cell(); - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let type_id_script = Script::new_builder() - .args(Bytes::from(h256!("0x1111").as_ref())) - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) + .args(Bytes::from(h256!("0x1111").as_ref()).pack()) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) .build(); - let input = CellInput::new(OutPoint::new(h256!("0x1234").into(), 8), 0); + let input = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 8), 0); let input_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script.clone())) + .type_(Some(type_id_script.clone()).pack()) .build(); let output_cell = CellOutputBuilder::default() - .capacity(capacity_bytes!(990)) + .capacity(capacity_bytes!(990).pack()) .lock(always_success_script.clone()) - .type_(Some(type_id_script)) + .type_(Some(type_id_script).pack()) .build(); let transaction = TransactionBuilder::default() @@ -1045,19 +1045,19 @@ fn load_code_into_global() { let mut vec = Vec::with_capacity(8 + data_hash.len()); vec.extend_from_slice(&number.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.into() + vec.pack() }; let (dyn_lock_cell, dyn_lock_data_hash) = load_cell_from_path("testdata/load_is_even_into_global"); let dyn_lock_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(dyn_lock_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(dyn_lock_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1101,19 +1101,19 @@ fn load_code_with_snapshot() { let mut vec = Vec::with_capacity(8 + data_hash.len()); vec.extend_from_slice(&number.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.into() + vec.pack() }; let (dyn_lock_cell, dyn_lock_data_hash) = load_cell_from_path("testdata/load_is_even_with_snapshot"); let dyn_lock_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(dyn_lock_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(dyn_lock_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1202,16 +1202,16 @@ fn load_code_with_snapshot_more_times() { vec.extend_from_slice(&div2); // num0 = 3 vec.extend_from_slice(&sub1); // num0 = 2 vec.extend_from_slice(&div2); // num0 = 1 - vec.into() + vec.pack() }; let lock_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(lock_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1330,7 +1330,7 @@ fn test_exec( vec.extend_from_slice(&place.to_le_bytes()); vec.extend_from_slice(&bounds.to_le_bytes()); vec.extend_from_slice(&data_hash); - vec.into() + vec.pack() }; let rtx = { @@ -1343,12 +1343,12 @@ fn test_exec( always_success_cell(); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .args(args) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script.clone()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1360,7 +1360,7 @@ fn test_exec( let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let tx = TransactionBuilder::default() .input(input) - .set_witnesses(vec![exec_callee_cell_data.into()]) + .set_witnesses(vec![exec_callee_cell_data.pack()]) .build(); (tx, vec![create_dummy_cell(output)]) } @@ -1372,7 +1372,7 @@ fn test_exec( let tx = TransactionBuilder::default() .input(input) - .set_witnesses(vec![data.into()]) + .set_witnesses(vec![data.pack()]) .build(); (tx, vec![create_dummy_cell(output)]) } @@ -1383,18 +1383,18 @@ fn test_exec( ExecFrom::GroupOutputWitness => { let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) - .type_(Some(exec_caller_script)) + .capacity(capacity_bytes!(100).pack()) + .type_(Some(exec_caller_script).pack()) .build(); let tx = TransactionBuilder::default() .output(output) - .set_witnesses(vec![exec_callee_cell_data.into()]) + .set_witnesses(vec![exec_callee_cell_data.pack()]) .build(); (tx, vec![]) } ExecFrom::TxInputCell => { let callee_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script.clone()) .build(); let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); @@ -1407,9 +1407,9 @@ fn test_exec( } ExecFrom::GroupInputCell => { let caller_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) - .type_(Some(always_success_script.clone())) + .type_(Some(always_success_script.clone()).pack()) .build(); let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let caller_cell = @@ -1422,38 +1422,38 @@ fn test_exec( ExecFrom::TxOutputCell => { let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let callee_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script.clone()) .build(); let tx = TransactionBuilder::default() .input(input) .output(callee_output) - .output_data(exec_callee_cell_data) + .output_data(exec_callee_cell_data.pack()) .build(); (tx, vec![create_dummy_cell(output)]) } ExecFrom::GroupOutputCell => { let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let callee_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) - .type_(Some(exec_caller_script)) + .capacity(capacity_bytes!(100).pack()) + .type_(Some(exec_caller_script).pack()) .build(); let tx = TransactionBuilder::default() .output(callee_output) - .output_data(exec_callee_cell_data) + .output_data(exec_callee_cell_data.pack()) .build(); (tx, vec![]) } ExecFrom::OutOfBound(..) => { let exec_callee_cell_data = exec_callee_cell.mem_cell_data.as_ref().unwrap(); let tx = TransactionBuilder::default() - .set_witnesses(vec![exec_callee_cell_data.into()]) + .set_witnesses(vec![exec_callee_cell_data.pack()]) .build(); (tx, vec![create_dummy_cell(output)]) } }; - let always_success_out_point = OutPoint::new(h256!("0x11").into(), 0); + let always_success_out_point = OutPoint::new(h256!("0x11").pack(), 0); let resolved_always_success_cell = CellMetaBuilder::from_cell_output( always_success_cell.clone(), always_success_cell_data.to_owned(), @@ -1793,18 +1793,21 @@ fn check_signature_referenced_via_type_hash_ok_with_multiple_matches() { args.extend(&to_hex_pubkey(&pubkey)); args.extend(&to_hex_signature(&signature)); - let dep_out_point = OutPoint::new(h256!("0x123").into(), 8); + let dep_out_point = OutPoint::new(h256!("0x123").pack(), 8); let cell_dep = CellDep::new_builder() .out_point(dep_out_point.clone()) .build(); let output = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) - .type_(Some( - Script::new_builder() - .code_hash(h256!("0x123456abcd90")) - .hash_type(ScriptHashType::Data) - .build(), - )) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) + .type_( + Some( + Script::new_builder() + .code_hash(h256!("0x123456abcd90").pack()) + .hash_type(ScriptHashType::Data.into()) + .build(), + ) + .pack(), + ) .build(); let type_hash = output.type_().to_opt().as_ref().unwrap().calc_script_hash(); let dep_cell = CellMetaBuilder::from_cell_output(output, data.clone()) @@ -1812,18 +1815,21 @@ fn check_signature_referenced_via_type_hash_ok_with_multiple_matches() { .out_point(dep_out_point) .build(); - let dep_out_point2 = OutPoint::new(h256!("0x1234").into(), 8); + let dep_out_point2 = OutPoint::new(h256!("0x1234").pack(), 8); let cell_dep2 = CellDep::new_builder() .out_point(dep_out_point2.clone()) .build(); let output2 = CellOutputBuilder::default() - .capacity(Capacity::bytes(data.len()).unwrap()) - .type_(Some( - Script::new_builder() - .code_hash(h256!("0x123456abcd90")) - .hash_type(ScriptHashType::Data) - .build(), - )) + .capacity(Capacity::bytes(data.len()).unwrap().pack()) + .type_( + Some( + Script::new_builder() + .code_hash(h256!("0x123456abcd90").pack()) + .hash_type(ScriptHashType::Data.into()) + .build(), + ) + .pack(), + ) .build(); let dep_cell2 = CellMetaBuilder::from_cell_output(output2, data) .transaction_info(default_transaction_info()) @@ -1831,9 +1837,9 @@ fn check_signature_referenced_via_type_hash_ok_with_multiple_matches() { .build(); let script = Script::new_builder() - .args(Bytes::from(args)) + .args(Bytes::from(args).pack()) .code_hash(type_hash) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1844,7 +1850,7 @@ fn check_signature_referenced_via_type_hash_ok_with_multiple_matches() { .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let dummy_cell = create_dummy_cell(output); @@ -1874,11 +1880,11 @@ fn check_exec_callee_pause() { load_cell_from_path("testdata/exec_callee_pause"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); diff --git a/script/src/verify/tests/ckb_latest/features_since_v2023.rs b/script/src/verify/tests/ckb_latest/features_since_v2023.rs index e44809e783..4cb4fd8583 100644 --- a/script/src/verify/tests/ckb_latest/features_since_v2023.rs +++ b/script/src/verify/tests/ckb_latest/features_since_v2023.rs @@ -14,12 +14,12 @@ fn simple_spawn_test(bin_path: &str, args: &[u8]) -> Result { let (cell, data_hash) = load_cell_from_path(bin_path); let script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(data_hash) - .args(Bytes::copy_from_slice(args)) + .args(Bytes::copy_from_slice(args).pack()) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -116,11 +116,11 @@ fn check_vm_version() { let (vm_version_cell, vm_version_data_hash) = load_cell_from_path("testdata/vm_version_2"); let vm_version_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(vm_version_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(vm_version_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -150,10 +150,11 @@ fn check_spawn_strcat() { load_cell_from_path("testdata/spawn_callee_strcat"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -182,11 +183,11 @@ fn check_spawn_out_of_cycles() { load_cell_from_path("testdata/spawn_callee_out_of_cycles"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -222,11 +223,11 @@ fn check_spawn_exec() { let (spawn_callee_callee_cell, _) = load_cell_from_path("testdata/spawn_callee_exec_callee"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -259,11 +260,11 @@ fn check_spawn_strcat_wrap() { let (spawn_callee_callee_cell, _) = load_cell_from_path("testdata/spawn_callee_strcat"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -296,11 +297,11 @@ fn check_spawn_out_of_cycles_wrap() { let (spawn_callee_callee_cell, _) = load_cell_from_path("testdata/spawn_callee_out_of_cycles"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -338,11 +339,11 @@ fn check_spawn_recursive() { load_cell_from_path("testdata/spawn_recursive"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -378,11 +379,11 @@ fn check_spawn_snapshot() { let (snapshot_cell, _) = load_cell_from_path("testdata/current_cycles_with_snapshot"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -419,11 +420,11 @@ async fn check_spawn_async() { let (snapshot_cell, _) = load_cell_from_path("testdata/current_cycles_with_snapshot"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -498,11 +499,11 @@ async fn check_spawn_suspend_shutdown() { let (snapshot_cell, _) = load_cell_from_path("testdata/infinite_loop"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -555,11 +556,11 @@ fn check_spawn_state() { let (snapshot_cell, _) = load_cell_from_path("testdata/current_cycles_with_snapshot"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -623,11 +624,11 @@ fn check_spawn_current_cycles() { load_cell_from_path("testdata/spawn_callee_current_cycles"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -700,19 +701,18 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { load_cell_from_path("testdata/always_success"); let spawn_callee_cell_data = spawn_callee_cell.mem_cell_data.as_ref().unwrap(); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) - .args(args) + .args(args.pack()) .build(); - let always_success_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(always_success_data_hash) .build(); let input_spawn_caller = create_dummy_cell( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script.clone()) .build(), ); @@ -721,7 +721,7 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { SpawnFrom::TxInputWitness | SpawnFrom::TxOutputWitness | SpawnFrom::GroupInputWitness => { ResolvedTransaction { transaction: TransactionBuilder::default() - .set_witnesses(vec![spawn_callee_cell_data.into()]) + .set_witnesses(vec![spawn_callee_cell_data.pack()]) .build(), resolved_cell_deps: vec![spawn_caller_cell, spawn_callee_cell], resolved_inputs: vec![input_spawn_caller], @@ -732,11 +732,11 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { transaction: TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) - .type_(Some(spawn_caller_script)) + .capacity(capacity_bytes!(100).pack()) + .type_(Some(spawn_caller_script).pack()) .build(), ) - .set_witnesses(vec![spawn_callee_cell_data.into()]) + .set_witnesses(vec![spawn_callee_cell_data.pack()]) .build(), resolved_cell_deps: vec![spawn_caller_cell, spawn_callee_cell], resolved_inputs: vec![], @@ -750,7 +750,7 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { }, SpawnFrom::TxInputCell => { let input_spawn_callee_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(always_success_script) .build(); let input_spawn_callee = CellMetaBuilder::from_cell_output( @@ -769,11 +769,11 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { transaction: TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_success_script) .build(), ) - .output_data(spawn_callee_cell_data) + .output_data(spawn_callee_cell_data.pack()) .build(), resolved_cell_deps: vec![spawn_caller_cell, spawn_callee_cell, always_success_cell], resolved_inputs: vec![input_spawn_caller], @@ -782,7 +782,7 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { SpawnFrom::GroupInputCell => { let input_spawn_caller = CellMetaBuilder::from_cell_output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(), spawn_callee_cell_data.clone(), @@ -799,11 +799,11 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { transaction: TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) - .type_(Some(spawn_caller_script)) + .capacity(capacity_bytes!(100).pack()) + .type_(Some(spawn_caller_script).pack()) .build(), ) - .output_data(spawn_callee_cell_data) + .output_data(spawn_callee_cell_data.pack()) .build(), resolved_cell_deps: vec![spawn_caller_cell, spawn_callee_cell, always_success_cell], resolved_inputs: vec![], @@ -817,7 +817,7 @@ fn check_spawn_configurable_once(spawn_from: SpawnFrom) { } ResolvedTransaction { transaction: TransactionBuilder::default() - .set_witnesses(vec![data.into()]) + .set_witnesses(vec![data.pack()]) .build(), resolved_cell_deps: vec![spawn_caller_cell, spawn_callee_cell], resolved_inputs: vec![input_spawn_caller], @@ -1130,17 +1130,17 @@ proptest! { let (code_dep, code_dep_hash) = load_cell_from_slice(&program[..]); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type() ) + .hash_type(script_version.data_hash_type().into()) .code_hash(code_dep_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100) ) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let dummy_cell = create_dummy_cell(output); let rtx = ResolvedTransaction { - transaction: TransactionBuilder::default().witness(data.as_bytes()).build(), + transaction: TransactionBuilder::default().witness(data.as_bytes().pack()).build(), resolved_cell_deps: vec![code_dep], resolved_inputs: vec![dummy_cell], resolved_dep_groups: vec![], @@ -1190,11 +1190,11 @@ fn check_spawn_huge_swap() { load_cell_from_path("testdata/spawn_huge_swap"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1243,11 +1243,11 @@ fn check_spawn_cycles() { let (spawn_callee_cell, _spawn_callee_data_hash) = load_cell_from_path("testdata/spawn_cycles"); let spawn_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(spawn_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(spawn_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1278,12 +1278,12 @@ fn spawn_io_test(io_size: u64, enable_check: bool) -> Result { let (cell, data_hash) = load_cell_from_path("testdata/spawn_io_cycles"); let script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(data_hash) - .args(Bytes::copy_from_slice(&args)) + .args(Bytes::copy_from_slice(&args).pack()) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1333,11 +1333,11 @@ fn check_infinite_exec() { let (exec_caller_cell, exec_caller_data_hash) = load_cell_from_path("testdata/infinite_exec"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1370,11 +1370,11 @@ fn check_fuzz_crash_1() { let (exec_caller_cell, exec_caller_data_hash) = load_cell_from_path("testdata/crash-5a27052f"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1408,11 +1408,11 @@ fn check_fuzz_crash_2() { let script_version = SCRIPT_VERSION; let (exec_caller_cell, exec_caller_data_hash) = load_cell_from_path("testdata/crash-45a6098d"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); @@ -1441,11 +1441,11 @@ fn check_fuzz_crash_3() { let script_version = SCRIPT_VERSION; let (exec_caller_cell, exec_caller_data_hash) = load_cell_from_path("testdata/crash-4717eb0e"); let exec_caller_script = Script::new_builder() - .hash_type(script_version.data_hash_type()) + .hash_type(script_version.data_hash_type().into()) .code_hash(exec_caller_data_hash) .build(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(exec_caller_script) .build(); let input = CellInput::new(OutPoint::null(), 0); diff --git a/script/src/verify/tests/utils.rs b/script/src/verify/tests/utils.rs index 97ff7f6740..760921f627 100644 --- a/script/src/verify/tests/utils.rs +++ b/script/src/verify/tests/utils.rs @@ -22,7 +22,7 @@ use ckb_types::{ }, h256, packed::{ - self, Byte32, CellDep, CellInput, OutPoint, Script, TransactionInfoBuilder, + Byte32, CellDep, CellInput, OutPoint, Script, TransactionInfoBuilder, TransactionKeyBuilder, WitnessArgs, }, H256, @@ -67,7 +67,7 @@ pub(crate) fn load_cell_from_path(path_str: &str) -> (CellMeta, Byte32) { pub(crate) fn load_cell_from_slice(slice: &[u8]) -> (CellMeta, Byte32) { let cell_data = Bytes::copy_from_slice(slice); let cell_output = CellOutput::new_builder() - .capacity(Capacity::bytes(cell_data.len()).unwrap()) + .capacity(Capacity::bytes(cell_data.len()).unwrap().pack()) .build(); let cell_meta = CellMetaBuilder::from_cell_output(cell_output, cell_data) .transaction_info(default_transaction_info()) @@ -107,16 +107,16 @@ pub(crate) fn sign_args(args: &[u8], privkey: &Privkey) -> Signature { pub(crate) fn default_transaction_info() -> TransactionInfo { TransactionInfoBuilder::default() - .block_number(1u64) - .block_epoch(0u64) + .block_number(1u64.pack()) + .block_epoch(0u64.pack()) .key( TransactionKeyBuilder::default() .block_hash(Byte32::zero()) - .index(1u32) + .index(1u32.pack()) .build(), ) .build() - .into() + .unpack() } pub(crate) struct TransactionScriptsVerifierWithEnv { @@ -184,7 +184,9 @@ impl TransactionScriptsVerifierWithEnv { ScriptVersion::V1 => EpochNumberWithFraction::new(self.version_1_enabled_at, 0, 1), ScriptVersion::V2 => EpochNumberWithFraction::new(self.version_2_enabled_at, 0, 1), }; - let header = HeaderView::new_advanced_builder().epoch(epoch).build(); + let header = HeaderView::new_advanced_builder() + .epoch(epoch.pack()) + .build(); let tx_env = Arc::new(TxVerifyEnv::new_commit(&header)); let verifier = TransactionScriptsVerifier::new( Arc::new(rtx.clone()), @@ -273,7 +275,9 @@ impl TransactionScriptsVerifierWithEnv { ScriptVersion::V1 => EpochNumberWithFraction::new(self.version_1_enabled_at, 0, 1), ScriptVersion::V2 => EpochNumberWithFraction::new(self.version_2_enabled_at, 0, 1), }; - let header = HeaderView::new_advanced_builder().epoch(epoch).build(); + let header = HeaderView::new_advanced_builder() + .epoch(epoch.pack()) + .build(); let tx_env = Arc::new(TxVerifyEnv::new_commit(&header)); let verifier = TransactionScriptsVerifier::new( Arc::new(rtx.clone()), @@ -305,7 +309,9 @@ impl TransactionScriptsVerifierWithEnv { ScriptVersion::V1 => EpochNumberWithFraction::new(self.version_1_enabled_at, 0, 1), ScriptVersion::V2 => EpochNumberWithFraction::new(self.version_2_enabled_at, 0, 1), }; - let header = HeaderView::new_advanced_builder().epoch(epoch).build(); + let header = HeaderView::new_advanced_builder() + .epoch(epoch.pack()) + .build(); let tx_env = Arc::new(TxVerifyEnv::new_commit(&header)); let mut verifier = TransactionScriptsVerifier::new( Arc::new(rtx.clone()), @@ -330,11 +336,11 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); - let input1 = CellInput::new(OutPoint::new(h256!("0x1234").into(), 0), 0); - let input2 = CellInput::new(OutPoint::new(h256!("0x1111").into(), 0), 0); + let input1 = CellInput::new(OutPoint::new(h256!("0x1234").pack(), 0), 0); + let input2 = CellInput::new(OutPoint::new(h256!("0x1111").pack(), 0), 0); let mut generator = Generator::non_crypto_safe_prng(42); let privkey = generator.gen_privkey(); @@ -345,23 +351,23 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { let lock_arg2 = Bytes::from((blake2b_256(pubkey_data2)[0..20]).to_owned()); let lock = Script::new_builder() - .args(lock_arg) - .code_hash(type_lock_script_code_hash()) - .hash_type(ScriptHashType::Type) + .args(lock_arg.pack()) + .code_hash(type_lock_script_code_hash().pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let lock2 = Script::new_builder() - .args(lock_arg2) - .code_hash(type_lock_script_code_hash()) - .hash_type(ScriptHashType::Type) + .args(lock_arg2.pack()) + .code_hash(type_lock_script_code_hash().pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let output1 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock.clone()) .build(); let output2 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock2.clone()) .build(); let tx = TransactionBuilder::default() @@ -370,15 +376,15 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { .input(input2.clone()) .output(output1) .output(output2) - .output_data(packed::Bytes::default()) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) + .output_data(Default::default()) .build(); - let tx_hash: H256 = tx.hash().into(); + let tx_hash: H256 = tx.hash().unpack(); // sign input1 let witness = { WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build() }; let witness_len: u64 = witness.as_bytes().len() as u64; @@ -393,11 +399,11 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { }; let sig = privkey.sign_recoverable(&message).expect("sign"); let witness = WitnessArgs::new_builder() - .lock(Some(Bytes::from(sig.serialize()))) + .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); // sign input2 let witness2 = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness2_len: u64 = witness2.as_bytes().len() as u64; let mut hasher = new_blake2b(); @@ -411,12 +417,12 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { }; let sig2 = privkey2.sign_recoverable(&message2).expect("sign"); let witness2 = WitnessArgs::new_builder() - .lock(Some(Bytes::from(sig2.serialize()))) + .lock(Some(Bytes::from(sig2.serialize())).pack()) .build(); let tx = tx .as_advanced_builder() - .witness(witness.as_bytes()) - .witness(witness2.as_bytes()) + .witness(witness.as_bytes().pack()) + .witness(witness2.as_bytes().pack()) .build(); let serialized_size = tx.data().as_slice().len() as u64; @@ -432,7 +438,7 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { let (secp256k1_data_cell, secp256k1_data_cell_data) = secp256k1_data_cell(consensus); let input_cell1 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock) .build(); @@ -441,7 +447,7 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { .build(); let input_cell2 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock2) .build(); diff --git a/shared/src/shared.rs b/shared/src/shared.rs index 9687165186..2939230a5f 100644 --- a/shared/src/shared.rs +++ b/shared/src/shared.rs @@ -220,7 +220,7 @@ impl Shared { e })?; - let pack_number: packed::Uint64 = number.into(); + let pack_number: packed::Uint64 = number.pack(); let prefix = pack_number.as_slice(); for (key, value) in snapshot .get_iter( @@ -233,7 +233,7 @@ impl Shared { let block_hash = reader.block_hash().to_entity(); if &block_hash != hash { let txs = - packed::Uint32Reader::from_slice_should_be_ok(value.as_ref()).into(); + packed::Uint32Reader::from_slice_should_be_ok(value.as_ref()).unpack(); side.insert(block_hash, (reader.number().to_entity(), txs)); } } @@ -254,10 +254,12 @@ impl Shared { if !side.is_empty() { // Wipe out side chain for (hash, (number, txs)) in &side { - batch.delete_block(number.into(), hash, *txs).map_err(|e| { - ckb_logger::error!("Freezer delete_block_body failed {}", e); - e - })?; + batch + .delete_block(number.unpack(), hash, *txs) + .map_err(|e| { + ckb_logger::error!("Freezer delete_block_body failed {}", e); + e + })?; } self.store.write(&batch).map_err(|e| { @@ -277,12 +279,12 @@ impl Shared { fn compact_block_body(&self, start: &packed::Byte32, end: &packed::Byte32) { let start_t = packed::TransactionKey::new_builder() .block_hash(start.clone()) - .index(0u32) + .index(0u32.pack()) .build(); let end_t = packed::TransactionKey::new_builder() .block_hash(end.clone()) - .index(TX_INDEX_UPPER_BOUND) + .index(TX_INDEX_UPPER_BOUND.pack()) .build(); if let Err(e) = self.store.compact_range( diff --git a/shared/src/shared_builder.rs b/shared/src/shared_builder.rs index 1bb7537d31..155a564a0f 100644 --- a/shared/src/shared_builder.rs +++ b/shared/src/shared_builder.rs @@ -22,6 +22,7 @@ use ckb_tx_pool::{ service::TxVerificationResult, TokioRwLock, TxEntry, TxPool, TxPoolServiceBuilder, }; use ckb_types::core::hardfork::HardForks; +use ckb_types::prelude::Pack; use ckb_types::{ core::service::PoolTransactionEntry, core::tx_pool::Reject, core::EpochExt, core::HeaderView, }; @@ -343,7 +344,7 @@ impl SharedBuilder { snapshot: &Snapshot, ) -> bool { if let Some(ref target) = sync_config.assume_valid_target { - if snapshot.block_exists(&target.into()) { + if snapshot.block_exists(&target.pack()) { info!("assume valid target is already in db, CKB will do full verification from now on"); return true; } diff --git a/spec/src/consensus.rs b/spec/src/consensus.rs index 83f9b29af9..2d8a16c481 100644 --- a/spec/src/consensus.rs +++ b/spec/src/consensus.rs @@ -168,13 +168,13 @@ impl Default for ConsensusBuilder { let occupied = empty_output .occupied_capacity(Capacity::zero()) .expect("default occupied"); - empty_output.as_builder().capacity(occupied).build() + empty_output.as_builder().capacity(occupied.pack()).build() }; let witness = Script::default().into_witness(); let cellbase = TransactionBuilder::default() .input(input) .output(output) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .witness(witness) .build(); @@ -200,8 +200,8 @@ impl Default for ConsensusBuilder { .expect("genesis dao data calculation error!"); let genesis_block = BlockBuilder::default() - .compact_target(DIFF_TWO) - .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0)) + .compact_target(DIFF_TWO.pack()) + .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0).pack()) .dao(dao) .transaction(cellbase) .build(); @@ -964,7 +964,7 @@ impl Consensus { /// The network identify name, used for network identify protocol pub fn identify_name(&self) -> String { - let genesis_hash = format!("{:x}", Into::::into(&self.genesis_hash)); + let genesis_hash = format!("{:x}", Unpack::::unpack(&self.genesis_hash)); format!("/{}/{}", self.id, &genesis_hash[..8]) } @@ -1145,14 +1145,14 @@ impl From for ckb_jsonrpc_types::Consensus { }; Self { id: consensus.id, - genesis_hash: consensus.genesis_hash.into(), - dao_type_hash: consensus.dao_type_hash.into(), + genesis_hash: consensus.genesis_hash.unpack(), + dao_type_hash: consensus.dao_type_hash.unpack(), secp256k1_blake160_sighash_all_type_hash: consensus .secp256k1_blake160_sighash_all_type_hash - .map(|h| h.into()), + .map(|h| h.unpack()), secp256k1_blake160_multisig_all_type_hash: consensus .secp256k1_blake160_multisig_all_type_hash - .map(|h| h.into()), + .map(|h| h.unpack()), initial_primary_epoch_reward: consensus.initial_primary_epoch_reward.into(), secondary_epoch_reward: consensus.secondary_epoch_reward.into(), max_uncles_num: (consensus.max_uncles_num as u64).into(), diff --git a/spec/src/lib.rs b/spec/src/lib.rs index 588aa4657d..4e029bc6cb 100644 --- a/spec/src/lib.rs +++ b/spec/src/lib.rs @@ -500,7 +500,7 @@ impl ChainSpec { fn verify_genesis_hash(&self, genesis: &BlockView) -> Result<(), Box> { if let Some(ref expect) = self.genesis.hash { - let actual: H256 = genesis.hash().into(); + let actual: H256 = genesis.hash().unpack(); if &actual != expect { return Err(SpecLoadError::genesis_mismatch(expect.clone(), actual)); } @@ -609,7 +609,7 @@ impl ChainSpec { .raw() .outputs() .iter() - .map(|output| Into::::into(output.capacity())) + .map(|output| Unpack::::unpack(&output.capacity())) .try_fold(Capacity::zero(), Capacity::safe_add) }?; @@ -633,14 +633,14 @@ impl ChainSpec { ); let block = BlockBuilder::default() - .version(self.genesis.version) - .parent_hash(&self.genesis.parent_hash) - .timestamp(self.genesis.timestamp) - .compact_target(self.genesis.compact_target) - .extra_hash(&self.genesis.uncles_hash) - .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0)) + .version(self.genesis.version.pack()) + .parent_hash(self.genesis.parent_hash.pack()) + .timestamp(self.genesis.timestamp.pack()) + .compact_target(self.genesis.compact_target.pack()) + .extra_hash(self.genesis.uncles_hash.pack()) + .epoch(EpochNumberWithFraction::new_unchecked(0, 0, 0).pack()) .dao(dao) - .nonce(u128::from_le_bytes(self.genesis.nonce.to_le_bytes())) + .nonce(u128::from_le_bytes(self.genesis.nonce.to_le_bytes()).pack()) .transaction(cellbase_transaction) .transaction(dep_group_transaction) .build(); @@ -734,7 +734,7 @@ impl ChainSpec { // Check system cells data hash let check_cells_data_hash = |tx_index, output_index, hash: &H256| { - if data_hashes.get(&hash.into()) != Some(&(tx_index, output_index)) { + if data_hashes.get(&hash.pack()) != Some(&(tx_index, output_index)) { return Err(format!( "Invalid output data for tx-index: {tx_index}, output-index: {output_index}, expected data hash: {hash:x}", )); @@ -801,12 +801,12 @@ impl ChainSpec { outputs_data.extend(system_cells_data); let special_issued_lock = packed::Script::new_builder() - .args(secp_lock_arg(&Privkey::from(SPECIAL_CELL_PRIVKEY.clone()))) - .code_hash(CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL.clone()) - .hash_type(ScriptHashType::Data) + .args(secp_lock_arg(&Privkey::from(SPECIAL_CELL_PRIVKEY.clone())).pack()) + .code_hash(CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL.clone().pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let special_issued_cell = packed::CellOutput::new_builder() - .capacity(special_cell_capacity) + .capacity(special_cell_capacity.pack()) .lock(special_issued_lock) .build(); outputs.push(special_issued_cell); @@ -829,7 +829,7 @@ impl ChainSpec { .outputs_data( outputs_data .iter() - .map(|d| d.into()) + .map(|d| d.pack()) .collect::>(), ) .build(); @@ -872,11 +872,11 @@ impl ChainSpec { }) .collect::>>()?; - let data = Into::::into(out_points).as_bytes(); + let data = out_points.pack().as_bytes(); let cell = packed::CellOutput::new_builder() - .lock(self.genesis.system_cells_lock.clone()) + .lock(self.genesis.system_cells_lock.clone().into()) .build_exact_capacity(Capacity::bytes(data.len())?)?; - Ok((cell, data.into())) + Ok((cell, data.pack())) }) .collect::, Box>>()? .into_iter() @@ -887,17 +887,17 @@ impl ChainSpec { let input_out_point = cellbase_tx .outputs() .into_iter() - .position(|output| Into::::into(output.lock().args()) == lock_arg) + .position(|output| Unpack::::unpack(&output.lock().args()) == lock_arg) .map(|index| packed::OutPoint::new(cellbase_tx.hash(), index as u32)) .expect("Get special issued input failed"); let input = packed::CellInput::new(input_out_point, 0); let secp_data_out_point = - find_out_point_by_data_hash(cellbase_tx, &CODE_HASH_SECP256K1_DATA.into()) + find_out_point_by_data_hash(cellbase_tx, &CODE_HASH_SECP256K1_DATA.pack()) .ok_or_else(|| String::from("Get secp data out point failed"))?; let secp_blake160_out_point = find_out_point_by_data_hash( cellbase_tx, - &CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL.into(), + &CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL.pack(), ) .ok_or_else(|| String::from("Get secp blake160 out point failed"))?; let cell_deps = vec![ @@ -915,10 +915,10 @@ impl ChainSpec { .outputs_data(outputs_data.clone()) .build(); - let tx_hash: H256 = tx.hash().into(); + let tx_hash: H256 = tx.hash().unpack(); let message = H256::from(blake2b_256(tx_hash)); let sig = privkey.sign_recoverable(&message).expect("sign"); - let witness = Bytes::from(sig.serialize()); + let witness = Bytes::from(sig.serialize()).pack(); Ok(TransactionBuilder::default() .cell_deps(cell_deps) @@ -934,7 +934,7 @@ impl GenesisCell { fn build_output(&self) -> Result<(packed::CellOutput, Bytes), Box> { let data: Bytes = self.message.as_bytes().to_owned().into(); let cell = packed::CellOutput::new_builder() - .lock(self.lock.clone()) + .lock(self.lock.clone().into()) .build_exact_capacity(Capacity::bytes(data.len())?)?; Ok((cell, data)) } @@ -943,8 +943,8 @@ impl GenesisCell { impl IssuedCell { fn build_output(&self) -> packed::CellOutput { packed::CellOutput::new_builder() - .lock(self.lock.clone()) - .capacity(self.capacity) + .lock(self.lock.clone().into()) + .capacity(self.capacity.pack()) .build() } } @@ -963,12 +963,12 @@ impl SystemCell { None }; let builder = packed::CellOutput::new_builder() - .type_(type_script) - .lock(lock.clone()); + .type_(type_script.pack()) + .lock(lock.clone().into()); let data_len = Capacity::bytes(data.len())?; let cell = if let Some(capacity) = self.capacity { - let cell = builder.capacity(capacity).build(); + let cell = builder.capacity(capacity.pack()).build(); let occupied_capacity = cell.occupied_capacity(data_len)?.as_u64(); if occupied_capacity > capacity { return Err(format!( @@ -1004,9 +1004,9 @@ pub(crate) fn build_type_id_script(input: &packed::CellInput, output_index: u64) blake2b.finalize(&mut ret); let script_arg = Bytes::from(ret.to_vec()); packed::Script::new_builder() - .code_hash(TYPE_ID_CODE_HASH) - .hash_type(ScriptHashType::Type) - .args(script_arg) + .code_hash(TYPE_ID_CODE_HASH.pack()) + .hash_type(ScriptHashType::Type.into()) + .args(script_arg.pack()) .build() } diff --git a/spec/src/tests/consensus.rs b/spec/src/tests/consensus.rs index 4cbec57011..eaa250ad76 100644 --- a/spec/src/tests/consensus.rs +++ b/spec/src/tests/consensus.rs @@ -5,6 +5,7 @@ use ckb_types::{ HeaderView, TransactionBuilder, }, packed::{Byte32, Bytes}, + prelude::*, utilities::DIFF_TWO, }; @@ -52,8 +53,8 @@ fn test_halving_epoch_reward() { let header = |epoch: &EpochExt, number: u64| { HeaderBuilder::default() - .number(number) - .epoch(epoch.number_with_fraction(number)) + .number(number.pack()) + .epoch(epoch.number_with_fraction(number).pack()) .build() }; diff --git a/spec/src/tests/mod.rs b/spec/src/tests/mod.rs index e5f23bb5b7..ad621c1597 100644 --- a/spec/src/tests/mod.rs +++ b/spec/src/tests/mod.rs @@ -69,7 +69,7 @@ fn test_bundled_specs() { let consensus = consensus.unwrap(); let block = consensus.genesis_block(); let cellbase = block.transaction(0).unwrap(); - let cellbase_hash: H256 = cellbase.hash().into(); + let cellbase_hash: H256 = cellbase.hash().unpack(); assert_eq!(spec_hashes.cellbase, cellbase_hash); @@ -86,11 +86,11 @@ fn test_bundled_specs() { ) .enumerate() { - let data_hash: H256 = packed::CellOutput::calc_data_hash(&data.raw_data()).into(); + let data_hash: H256 = packed::CellOutput::calc_data_hash(&data.raw_data()).unpack(); let type_hash: Option = output .type_() .to_opt() - .map(|script| script.calc_script_hash().into()); + .map(|script| script.calc_script_hash().unpack()); assert_eq!(index_minus_one + 1, cell.index, "{bundled_spec_err}"); assert_eq!(cell.data_hash, data_hash, "{bundled_spec_err}"); assert_eq!(cell.type_hash, type_hash, "{bundled_spec_err}"); @@ -106,11 +106,11 @@ fn test_bundled_specs() { .output(dep_group_tx_input_index) .unwrap() .capacity() - .into(); + .unpack(); let outputs_capacity = dep_group_tx .outputs() .into_iter() - .map(|output| Into::::into(&output.capacity())) + .map(|output| Unpack::::unpack(&output.capacity())) .try_fold(Capacity::zero(), Capacity::safe_add) .unwrap(); // capacity for input and outputs should be same @@ -130,7 +130,7 @@ fn test_bundled_specs() { let dep_group = &spec_hashes.dep_groups[i]; // check the tx hashes of dep groups in spec file - let tx_hash = Into::::into(&dep_group.tx_hash); + let tx_hash = dep_group.tx_hash.pack(); assert_eq!(tx_hash, dep_group_tx.hash(), "{bundled_spec_err}"); let out_point_vec = packed::OutPointVec::from_slice(&output_data.raw_data()).unwrap(); @@ -148,7 +148,7 @@ fn test_bundled_specs() { // dep groups out_point should point to cellbase assert_eq!(cellbase.hash(), out_point.tx_hash(), "{bundled_spec_err}"); - let index_in_cellbase: usize = out_point.index().into(); + let index_in_cellbase: usize = out_point.index().unpack(); // check index for included cells in dep groups assert_eq!( diff --git a/spec/src/tests/versionbits.rs b/spec/src/tests/versionbits.rs index 898a17b97a..bcbb3aea57 100644 --- a/spec/src/tests/versionbits.rs +++ b/spec/src/tests/versionbits.rs @@ -162,8 +162,8 @@ impl MockChain { let cellbase = TransactionBuilder::default().build(); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) .transaction(cellbase) .build() } @@ -175,16 +175,16 @@ impl MockChain { let version = self.compute_versionbits(parent).unwrap(); let cellbase_witness = CellbaseWitness::new_builder() - .message(version.to_le_bytes().as_slice()) + .message(version.to_le_bytes().as_slice().pack()) .build(); - let witness = cellbase_witness.as_bytes(); + let witness = cellbase_witness.as_bytes().pack(); let cellbase = TransactionBuilder::default().witness(witness).build(); BlockBuilder::default() .parent_hash(parent.hash()) - .number(parent.number() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) + .number((parent.number() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) .transaction(cellbase) .build() } @@ -208,7 +208,7 @@ fn test_versionbits_active() { DEFAULT_ORPHAN_RATE_TARGET, ); let genesis = BlockBuilder::default() - .epoch(epoch_ext.number_with_fraction(0)) + .epoch(epoch_ext.number_with_fraction(0).pack()) .transaction(cellbase) .build(); @@ -316,7 +316,7 @@ fn test_versionbits_failed() { DEFAULT_ORPHAN_RATE_TARGET, ); let genesis = BlockBuilder::default() - .epoch(epoch_ext.number_with_fraction(0)) + .epoch(epoch_ext.number_with_fraction(0).pack()) .transaction(cellbase) .build(); diff --git a/store/src/cell.rs b/store/src/cell.rs index 182fb06459..88c6e49e17 100644 --- a/store/src/cell.rs +++ b/store/src/cell.rs @@ -41,23 +41,23 @@ pub fn attach_block_cell(txn: &StoreTransaction, block: &BlockView) -> Result<() .map(move |(index, (cell_output, data))| { let out_point = packed::OutPoint::new_builder() .tx_hash(tx_hash.clone()) - .index(index) + .index(index.pack()) .build(); let entry = packed::CellEntryBuilder::default() .output(cell_output) .block_hash(block_hash.clone()) - .block_number(block_number) - .block_epoch(block_epoch) - .index(tx_index) - .data_size(data.len() as u64) + .block_number(block_number.pack()) + .block_epoch(block_epoch.pack()) + .index(tx_index.pack()) + .data_size((data.len() as u64).pack()) .build(); let data_entry = if !data.is_empty() { let data_hash = packed::CellOutput::calc_data_hash(&data); Some( packed::CellDataEntryBuilder::default() - .output_data(data) + .output_data(data.pack()) .output_data_hash(data_hash) .build(), ) @@ -89,7 +89,7 @@ pub fn detach_block_cell(txn: &StoreTransaction, block: &BlockView) -> Result<() for tx in transactions.iter().skip(1) { for pts in tx.input_pts_iter() { let tx_hash = pts.tx_hash(); - let index: usize = pts.index().into(); + let index: usize = pts.index().unpack(); let indexes = input_pts.entry(tx_hash).or_insert_with(Vec::new); indexes.push(index); } @@ -111,23 +111,23 @@ pub fn detach_block_cell(txn: &StoreTransaction, block: &BlockView) -> Result<() tx.output_with_data(*index).map(|(cell_output, data)| { let out_point = packed::OutPoint::new_builder() .tx_hash(tx_hash.clone()) - .index(index) + .index(index.pack()) .build(); let entry = packed::CellEntryBuilder::default() .output(cell_output) .block_hash(block_hash.clone()) - .block_number(block_number) - .block_epoch(block_epoch) - .index(tx_index) - .data_size(data.len() as u64) + .block_number(block_number.pack()) + .block_epoch(block_epoch.pack()) + .index(tx_index.pack()) + .data_size((data.len() as u64).pack()) .build(); let data_entry = if !data.is_empty() { let data_hash = packed::CellOutput::calc_data_hash(&data); Some( packed::CellDataEntryBuilder::default() - .output_data(data) + .output_data(data.pack()) .output_data_hash(data_hash) .build(), ) diff --git a/store/src/store.rs b/store/src/store.rs index 90657c5017..8e9b69a6d9 100644 --- a/store/src/store.rs +++ b/store/src/store.rs @@ -75,7 +75,7 @@ pub trait ChainStore: Send + Sync + Sized { }; let ret = self.get(COLUMN_BLOCK_HEADER, hash.as_slice()).map(|slice| { let reader = packed::HeaderViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }); if let Some(cache) = self.cache() { @@ -98,7 +98,7 @@ pub trait ChainStore: Send + Sync + Sized { .take_while(|(key, _)| key.starts_with(prefix)) .map(|(_key, value)| { let reader = packed::TransactionViewReader::from_slice_should_be_ok(value.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }) .collect() } @@ -109,7 +109,7 @@ pub trait ChainStore: Send + Sync + Sized { .get(COLUMN_BLOCK_HEADER, hash.as_slice()) .map(|slice| { let reader = packed::HeaderViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) })?; let body = self.get_block_body(hash); @@ -119,7 +119,7 @@ pub trait ChainStore: Send + Sync + Sized { .map(|slice| { let reader = packed::UncleBlockVecViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }) .expect("block uncles must be stored"); @@ -210,7 +210,7 @@ pub trait ChainStore: Send + Sync + Sized { let ret = self.get(COLUMN_BLOCK_UNCLE, hash.as_slice()).map(|slice| { let reader = packed::UncleBlockVecViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }); if let Some(cache) = self.cache() { @@ -250,8 +250,8 @@ pub trait ChainStore: Send + Sync + Sized { let reader = packed::BlockExtReader::from_compatible_slice_should_be_ok(slice.as_ref()); match reader.count_extra_fields() { - 0 => reader.into(), - 2 => packed::BlockExtV1Reader::from_slice_should_be_ok(slice.as_ref()).into(), + 0 => reader.unpack(), + 2 => packed::BlockExtV1Reader::from_slice_should_be_ok(slice.as_ref()).unpack(), _ => { panic!( "BlockExt storage field count doesn't match, expect 7 or 5, actual {}", @@ -264,7 +264,7 @@ pub trait ChainStore: Send + Sync + Sized { /// Get block header hash by block number fn get_block_hash(&self, number: BlockNumber) -> Option { - let block_number: packed::Uint64 = number.into(); + let block_number: packed::Uint64 = number.pack(); self.get(COLUMN_INDEX, block_number.as_slice()) .map(|raw| packed::Byte32Reader::from_slice_should_be_ok(raw.as_ref()).to_entity()) } @@ -272,7 +272,7 @@ pub trait ChainStore: Send + Sync + Sized { /// Get block number by block header hash fn get_block_number(&self, hash: &packed::Byte32) -> Option { self.get(COLUMN_INDEX, hash.as_slice()) - .map(|raw| packed::Uint64Reader::from_slice_should_be_ok(raw.as_ref()).into()) + .map(|raw| packed::Uint64Reader::from_slice_should_be_ok(raw.as_ref()).unpack()) } /// TODO(doc): @quake @@ -310,7 +310,7 @@ pub trait ChainStore: Send + Sync + Sized { self.get(COLUMN_TRANSACTION_INFO, hash.as_slice()) .map(|slice| { let reader = packed::TransactionInfoReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }) } @@ -334,7 +334,7 @@ pub trait ChainStore: Send + Sync + Sized { self.get(COLUMN_BLOCK_BODY, tx_info.key().as_slice()) .map(|slice| { let reader = packed::TransactionViewReader::from_slice_should_be_ok(slice.as_ref()); - (reader.into(), tx_info) + (reader.unpack(), tx_info) }) } @@ -365,7 +365,7 @@ pub trait ChainStore: Send + Sync + Sized { let ret = self.get(COLUMN_CELL_DATA, &key).map(|slice| { if !slice.as_ref().is_empty() { let reader = packed::CellDataEntryReader::from_slice_should_be_ok(slice.as_ref()); - let data = reader.output_data().into(); + let data = reader.output_data().unpack(); let data_hash = reader.output_data_hash().to_entity(); (data, data_hash) } else { @@ -413,18 +413,18 @@ pub trait ChainStore: Send + Sync + Sized { /// Gets current epoch ext fn get_current_epoch_ext(&self) -> Option { self.get(COLUMN_META, META_CURRENT_EPOCH_KEY) - .map(|slice| packed::EpochExtReader::from_slice_should_be_ok(slice.as_ref()).into()) + .map(|slice| packed::EpochExtReader::from_slice_should_be_ok(slice.as_ref()).unpack()) } /// Gets epoch ext by epoch index fn get_epoch_ext(&self, hash: &packed::Byte32) -> Option { self.get(COLUMN_EPOCH, hash.as_slice()) - .map(|slice| packed::EpochExtReader::from_slice_should_be_ok(slice.as_ref()).into()) + .map(|slice| packed::EpochExtReader::from_slice_should_be_ok(slice.as_ref()).unpack()) } /// Gets epoch index by epoch number fn get_epoch_index(&self, number: EpochNumber) -> Option { - let epoch_number: packed::Uint64 = number.into(); + let epoch_number: packed::Uint64 = number.pack(); self.get(COLUMN_EPOCH, epoch_number.as_slice()) .map(|raw| packed::Byte32Reader::from_slice_should_be_ok(raw.as_ref()).to_entity()) } @@ -450,7 +450,7 @@ pub trait ChainStore: Send + Sync + Sized { fn get_uncle_header(&self, hash: &packed::Byte32) -> Option { self.get(COLUMN_UNCLES, hash.as_slice()).map(|slice| { let reader = packed::HeaderViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }) } @@ -471,7 +471,7 @@ pub trait ChainStore: Send + Sync + Sized { .build(); self.get(COLUMN_BLOCK_BODY, key.as_slice()).map(|slice| { let reader = packed::TransactionViewReader::from_slice_should_be_ok(slice.as_ref()); - Into::::into(reader) + Unpack::::unpack(&reader) }) } @@ -513,8 +513,7 @@ pub trait ChainStore: Send + Sync + Sized { let reader = packed::TransactionViewReader::from_slice_should_be_ok(value.as_ref()); reader.data().to_entity() }) - .collect::>() - .into(); + .pack(); let uncles = self.get_block_uncles(hash)?; let proposals = self.get_block_proposal_txs_ids(hash)?; @@ -551,7 +550,7 @@ pub trait ChainStore: Send + Sync + Sized { /// Gets a header digest. fn get_header_digest(&self, position_u64: u64) -> Option { - let position: packed::Uint64 = position_u64.into(); + let position: packed::Uint64 = position_u64.pack(); self.get(COLUMN_CHAIN_ROOT_MMR, position.as_slice()) .map(|slice| { let reader = packed::HeaderDigestReader::from_slice_should_be_ok(slice.as_ref()); @@ -580,12 +579,12 @@ fn build_cell_meta_from_reader(out_point: OutPoint, reader: packed::CellEntryRea out_point, cell_output: reader.output().to_entity(), transaction_info: Some(TransactionInfo { - block_number: reader.block_number().into(), + block_number: reader.block_number().unpack(), block_hash: reader.block_hash().to_entity(), - block_epoch: reader.block_epoch().into(), - index: reader.index().into(), + block_epoch: reader.block_epoch().unpack(), + index: reader.index().unpack(), }), - data_bytes: reader.data_size().into(), + data_bytes: reader.data_size().unpack(), mem_cell_data: None, mem_cell_data_hash: None, } diff --git a/store/src/tests/db.rs b/store/src/tests/db.rs index 5372d0f27e..39e1d24d61 100644 --- a/store/src/tests/db.rs +++ b/store/src/tests/db.rs @@ -31,7 +31,8 @@ fn save_and_get_block_with_transactions() { .transactions( (0..3) .map(|_| packed::Transaction::new_builder().build()) - .collect::>(), + .collect::>() + .pack(), ) .build() .into_view(); @@ -97,7 +98,7 @@ fn freeze_blockv0() { let freezer = Freezer::open_in(&tmp_dir2).expect("tmp freezer"); let store = ChainDB::new_with_freezer(db, freezer.clone(), Default::default()); - let raw = packed::RawHeader::new_builder().number(1u64).build(); + let raw = packed::RawHeader::new_builder().number(1u64.pack()).build(); let block = packed::Block::new_builder() .header(packed::Header::new_builder().raw(raw).build()) .build() @@ -110,7 +111,7 @@ fn freeze_blockv0() { txn.insert_raw( COLUMN_BLOCK_HEADER, block_hash.as_slice(), - Into::::into(header).as_slice(), + header.pack().as_slice(), ) .expect("insert header"); txn.commit().expect("commit"); @@ -130,8 +131,8 @@ fn freeze_blockv1_with_extension() { let freezer = Freezer::open_in(&tmp_dir2).expect("tmp freezer"); let store = ChainDB::new_with_freezer(db, freezer.clone(), Default::default()); - let extension: packed::Bytes = [1u8; 96].as_slice().into(); - let raw = packed::RawHeader::new_builder().number(1u64).build(); + let extension: packed::Bytes = [1u8; 96].pack(); + let raw = packed::RawHeader::new_builder().number(1u64.pack()).build(); let block = packed::BlockV1::new_builder() .header(packed::Header::new_builder().raw(raw).build()) .extension(extension) @@ -146,7 +147,7 @@ fn freeze_blockv1_with_extension() { txn.insert_raw( COLUMN_BLOCK_HEADER, block_hash.as_slice(), - Into::::into(header).as_slice(), + header.pack().as_slice(), ) .expect("insert header"); txn.commit().expect("commit"); diff --git a/store/src/transaction.rs b/store/src/transaction.rs index 51388d3091..62ba110b0f 100644 --- a/store/src/transaction.rs +++ b/store/src/transaction.rs @@ -173,10 +173,10 @@ impl StoreTransaction { /// TODO(doc): @quake pub fn insert_block(&self, block: &BlockView) -> Result<(), Error> { let hash = block.hash(); - let header = Into::::into(block.header()); - let uncles = Into::::into(block.uncles()); + let header = block.header().pack(); + let uncles = block.uncles().pack(); let proposals = block.data().proposals(); - let txs_len: packed::Uint32 = (block.transactions().len() as u32).into(); + let txs_len: packed::Uint32 = (block.transactions().len() as u32).pack(); self.insert_raw(COLUMN_BLOCK_HEADER, hash.as_slice(), header.as_slice())?; self.insert_raw(COLUMN_BLOCK_UNCLE, hash.as_slice(), uncles.as_slice())?; if let Some(extension) = block.extension() { @@ -189,7 +189,7 @@ impl StoreTransaction { self.insert_raw( COLUMN_NUMBER_HASH, packed::NumberHash::new_builder() - .number(block.number()) + .number(block.number().pack()) .block_hash(hash.clone()) .build() .as_slice(), @@ -203,9 +203,9 @@ impl StoreTransaction { for (index, tx) in block.transactions().into_iter().enumerate() { let key = packed::TransactionKey::new_builder() .block_hash(hash.clone()) - .index(index) + .index(index.pack()) .build(); - let tx_data = Into::::into(tx); + let tx_data = tx.pack(); self.insert_raw(COLUMN_BLOCK_BODY, key.as_slice(), tx_data.as_slice())?; } Ok(()) @@ -222,7 +222,7 @@ impl StoreTransaction { self.delete( COLUMN_NUMBER_HASH, packed::NumberHash::new_builder() - .number(block.number()) + .number(block.number().pack()) .block_hash(hash.clone()) .build() .as_slice(), @@ -232,7 +232,7 @@ impl StoreTransaction { for index in 0..txs_len { let key = packed::TransactionKey::new_builder() .block_hash(hash.clone()) - .index(index) + .index(index.pack()) .build(); self.delete(COLUMN_BLOCK_BODY, key.as_slice())?; } @@ -245,7 +245,7 @@ impl StoreTransaction { block_hash: &packed::Byte32, ext: &BlockExt, ) -> Result<(), Error> { - let packed_ext: packed::BlockExtV1 = ext.into(); + let packed_ext: packed::BlockExtV1 = ext.pack(); self.insert_raw( COLUMN_BLOCK_EXT, block_hash.as_slice(), @@ -260,7 +260,7 @@ impl StoreTransaction { for (index, tx_hash) in block.tx_hashes().iter().enumerate() { let key = packed::TransactionKey::new_builder() .block_hash(block_hash.clone()) - .index(index) + .index(index.pack()) .build(); let info = packed::TransactionInfo::new_builder() .key(key) @@ -269,13 +269,13 @@ impl StoreTransaction { .build(); self.insert_raw(COLUMN_TRANSACTION_INFO, tx_hash.as_slice(), info.as_slice())?; } - let block_number: packed::Uint64 = block.number().into(); + let block_number: packed::Uint64 = block.number().pack(); self.insert_raw(COLUMN_INDEX, block_number.as_slice(), block_hash.as_slice())?; for uncle in block.uncles().into_iter() { self.insert_raw( COLUMN_UNCLES, uncle.hash().as_slice(), - Into::::into(uncle.header()).as_slice(), + uncle.header().pack().as_slice(), )?; } self.insert_raw(COLUMN_INDEX, block_hash.as_slice(), block_number.as_slice()) @@ -309,22 +309,14 @@ impl StoreTransaction { /// TODO(doc): @quake pub fn insert_epoch_ext(&self, hash: &packed::Byte32, epoch: &EpochExt) -> Result<(), Error> { - self.insert_raw( - COLUMN_EPOCH, - hash.as_slice(), - Into::::into(epoch).as_slice(), - )?; - let epoch_number: packed::Uint64 = epoch.number().into(); + self.insert_raw(COLUMN_EPOCH, hash.as_slice(), epoch.pack().as_slice())?; + let epoch_number: packed::Uint64 = epoch.number().pack(); self.insert_raw(COLUMN_EPOCH, epoch_number.as_slice(), hash.as_slice()) } /// TODO(doc): @quake pub fn insert_current_epoch_ext(&self, epoch: &EpochExt) -> Result<(), Error> { - self.insert_raw( - COLUMN_META, - META_CURRENT_EPOCH_KEY, - Into::::into(epoch).as_slice(), - ) + self.insert_raw(COLUMN_META, META_CURRENT_EPOCH_KEY, epoch.pack().as_slice()) } /// TODO(doc): @quake @@ -376,7 +368,7 @@ impl StoreTransaction { position_u64: u64, header_digest: &packed::HeaderDigest, ) -> Result<(), Error> { - let position: packed::Uint64 = position_u64.into(); + let position: packed::Uint64 = position_u64.pack(); self.insert_raw( COLUMN_CHAIN_ROOT_MMR, position.as_slice(), @@ -386,7 +378,7 @@ impl StoreTransaction { /// Deletes a header digest. pub fn delete_header_digest(&self, position_u64: u64) -> Result<(), Error> { - let position: packed::Uint64 = position_u64.into(); + let position: packed::Uint64 = position_u64.pack(); self.delete(COLUMN_CHAIN_ROOT_MMR, position.as_slice()) } diff --git a/store/src/write_batch.rs b/store/src/write_batch.rs index a2568505d2..65d74e2dc1 100644 --- a/store/src/write_batch.rs +++ b/store/src/write_batch.rs @@ -100,7 +100,7 @@ impl StoreWriteBatch { self.inner.delete( COLUMN_NUMBER_HASH, packed::NumberHash::new_builder() - .number(number) + .number(number.pack()) .block_hash(hash.clone()) .build() .as_slice(), @@ -109,7 +109,7 @@ impl StoreWriteBatch { let key_range = (0u32..txs_len).map(|i| { packed::TransactionKey::new_builder() .block_hash(hash.clone()) - .index(i) + .index(i.pack()) .build() }); diff --git a/sync/src/filter/get_block_filter_check_points_process.rs b/sync/src/filter/get_block_filter_check_points_process.rs index e7b36d58be..a194525052 100644 --- a/sync/src/filter/get_block_filter_check_points_process.rs +++ b/sync/src/filter/get_block_filter_check_points_process.rs @@ -33,7 +33,7 @@ impl<'a> GetBlockFilterCheckPointsProcess<'a> { pub fn execute(self) -> Status { let active_chain = self.filter.shared.active_chain(); - let start_number: BlockNumber = self.message.to_entity().start_number().into(); + let start_number: BlockNumber = self.message.to_entity().start_number().unpack(); let latest: BlockNumber = active_chain.get_latest_built_filter_block_number(); let mut block_filter_hashes = Vec::new(); @@ -52,8 +52,8 @@ impl<'a> GetBlockFilterCheckPointsProcess<'a> { } } let content = packed::BlockFilterCheckPoints::new_builder() - .start_number(start_number) - .block_filter_hashes(block_filter_hashes) + .start_number(start_number.pack()) + .block_filter_hashes(block_filter_hashes.pack()) .build(); let message = packed::BlockFilterMessage::new_builder() diff --git a/sync/src/filter/get_block_filter_hashes_process.rs b/sync/src/filter/get_block_filter_hashes_process.rs index 3576ca0119..c1a3f5a6e0 100644 --- a/sync/src/filter/get_block_filter_hashes_process.rs +++ b/sync/src/filter/get_block_filter_hashes_process.rs @@ -31,7 +31,7 @@ impl<'a> GetBlockFilterHashesProcess<'a> { pub fn execute(self) -> Status { let active_chain = self.filter.shared.active_chain(); - let start_number: BlockNumber = self.message.to_entity().start_number().into(); + let start_number: BlockNumber = self.message.to_entity().start_number().unpack(); let latest: BlockNumber = active_chain.get_latest_built_filter_block_number(); let mut block_filter_hashes = Vec::new(); @@ -60,9 +60,9 @@ impl<'a> GetBlockFilterHashesProcess<'a> { } } let content = packed::BlockFilterHashes::new_builder() - .start_number(start_number) + .start_number(start_number.pack()) .parent_block_filter_hash(parent_block_filter_hash) - .block_filter_hashes(block_filter_hashes) + .block_filter_hashes(block_filter_hashes.pack()) .build(); let message = packed::BlockFilterMessage::new_builder() diff --git a/sync/src/filter/get_block_filters_process.rs b/sync/src/filter/get_block_filters_process.rs index e5e6f38d31..22e527f0e5 100644 --- a/sync/src/filter/get_block_filters_process.rs +++ b/sync/src/filter/get_block_filters_process.rs @@ -32,7 +32,7 @@ impl<'a> GetBlockFiltersProcess<'a> { pub fn execute(self) -> Status { let active_chain = self.filter.shared.active_chain(); - let start_number: BlockNumber = self.message.to_entity().start_number().into(); + let start_number: BlockNumber = self.message.to_entity().start_number().unpack(); let latest: BlockNumber = active_chain.get_latest_built_filter_block_number(); if latest >= start_number { @@ -51,9 +51,9 @@ impl<'a> GetBlockFiltersProcess<'a> { } } let content = packed::BlockFilters::new_builder() - .start_number(start_number) - .block_hashes(block_hashes) - .filters(filters) + .start_number(start_number.pack()) + .block_hashes(block_hashes.pack()) + .filters(filters.pack()) .build(); let message = packed::BlockFilterMessage::new_builder() diff --git a/sync/src/net_time_checker.rs b/sync/src/net_time_checker.rs index aa384f9151..259a2eae57 100644 --- a/sync/src/net_time_checker.rs +++ b/sync/src/net_time_checker.rs @@ -118,7 +118,7 @@ impl CKBProtocolHandler for NetTimeProtocol { // send local time to inbound peers if let Some(true) = nc.get_peer(peer_index).map(|peer| peer.is_inbound()) { let now = ckb_systemtime::unix_time_as_millis(); - let time = packed::Time::new_builder().timestamp(now).build(); + let time = packed::Time::new_builder().timestamp(now.pack()).build(); let _status = send_message_to(nc.as_ref(), peer_index, &time); } } @@ -137,7 +137,7 @@ impl CKBProtocolHandler for NetTimeProtocol { } let timestamp: u64 = match packed::TimeReader::from_slice(&data) - .map(|time| time.timestamp().into()) + .map(|time| time.timestamp().unpack()) .ok() { Some(timestamp) => timestamp, diff --git a/sync/src/relayer/block_transactions_process.rs b/sync/src/relayer/block_transactions_process.rs index c2c10077a4..fa5522e349 100644 --- a/sync/src/relayer/block_transactions_process.rs +++ b/sync/src/relayer/block_transactions_process.rs @@ -162,8 +162,8 @@ impl<'a> BlockTransactionsProcess<'a> { let content = packed::GetBlockTransactions::new_builder() .block_hash(block_hash.clone()) - .indexes(missing_transactions.as_slice()) - .uncle_indexes(missing_uncles.as_slice()) + .indexes(missing_transactions.pack()) + .uncle_indexes(missing_uncles.pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/sync/src/relayer/compact_block_process.rs b/sync/src/relayer/compact_block_process.rs index 9ee0d40918..b46dcca1ef 100644 --- a/sync/src/relayer/compact_block_process.rs +++ b/sync/src/relayer/compact_block_process.rs @@ -112,7 +112,7 @@ impl<'a> CompactBlockProcess<'a> { // use epoch as the judgment condition because we accept // all block in current epoch as uncle block pending_compact_blocks.retain(|_, (v, _, _)| { - Into::::into(v.header().as_reader().raw().epoch()) + Unpack::::unpack(&v.header().as_reader().raw().epoch()) .number() >= block.epoch().number() }); @@ -359,8 +359,8 @@ fn missing_or_collided_post_process( let content = packed::GetBlockTransactions::new_builder() .block_hash(block_hash) - .indexes(missing_transactions.as_slice()) - .uncle_indexes(missing_uncles.as_slice()) + .indexes(missing_transactions.pack()) + .uncle_indexes(missing_uncles.pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let sending = send_message_to(nc.as_ref(), peer, &message); diff --git a/sync/src/relayer/compact_block_verifier.rs b/sync/src/relayer/compact_block_verifier.rs index 61ce34772e..549735c1cb 100644 --- a/sync/src/relayer/compact_block_verifier.rs +++ b/sync/src/relayer/compact_block_verifier.rs @@ -1,5 +1,5 @@ use crate::{attempt, Status, StatusCode}; -use ckb_types::packed; +use ckb_types::{packed, prelude::*}; use std::collections::HashSet; // we assume that all the short_ids and prefilled transactions @@ -28,7 +28,7 @@ impl PrefilledVerifier { return StatusCode::CompactBlockHasNotPrefilledCellbase.into(); } else { // Check first prefilled index is zero - let index: usize = prefilled_transactions.get(0).unwrap().index().into(); + let index: usize = prefilled_transactions.get(0).unwrap().index().unpack(); if index != 0 { return StatusCode::CompactBlockHasNotPrefilledCellbase.into(); } @@ -38,7 +38,7 @@ impl PrefilledVerifier { .get(prefilled_transactions.len() - 1) .unwrap() .index() - .into(); + .unpack(); if index >= txs_len { return StatusCode::CompactBlockHasOutOfIndexPrefilledTransactions.into(); } @@ -46,8 +46,8 @@ impl PrefilledVerifier { // Check indices order of prefilled transactions for i in 0..(prefilled_transactions.len() - 1) { - let idx0: usize = prefilled_transactions.get(i).unwrap().index().into(); - let idx1: usize = prefilled_transactions.get(i + 1).unwrap().index().into(); + let idx0: usize = prefilled_transactions.get(i).unwrap().index().unpack(); + let idx1: usize = prefilled_transactions.get(i + 1).unwrap().index().unpack(); if idx0 >= idx1 { return StatusCode::CompactBlockHasOutOfOrderPrefilledTransactions.into(); } diff --git a/sync/src/relayer/get_block_proposal_process.rs b/sync/src/relayer/get_block_proposal_process.rs index 59fd24189c..b7321ba1c3 100644 --- a/sync/src/relayer/get_block_proposal_process.rs +++ b/sync/src/relayer/get_block_proposal_process.rs @@ -97,7 +97,7 @@ impl<'a> GetBlockProposalProcess<'a> { fn send_block_proposals(&self, txs: Vec) -> Status { let content = packed::BlockProposal::new_builder() - .transactions(txs) + .transactions(txs.into_iter().pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); send_message_to(self.nc.as_ref(), self.peer, &message) diff --git a/sync/src/relayer/get_block_transactions_process.rs b/sync/src/relayer/get_block_transactions_process.rs index b6c249c2aa..bfff3ebc11 100644 --- a/sync/src/relayer/get_block_transactions_process.rs +++ b/sync/src/relayer/get_block_transactions_process.rs @@ -4,7 +4,6 @@ use crate::{attempt, Status, StatusCode}; use ckb_logger::debug_target; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_store::ChainStore; -use ckb_types::packed::{Transaction, UncleBlock}; use ckb_types::{packed, prelude::*}; use std::sync::Arc; @@ -66,7 +65,7 @@ impl<'a> GetBlockTransactionsProcess<'a> { .filter_map(|i| { block .transactions() - .get(Into::::into(i) as usize) + .get(Unpack::::unpack(&i) as usize) .cloned() }) .collect::>(); @@ -75,23 +74,13 @@ impl<'a> GetBlockTransactionsProcess<'a> { .message .uncle_indexes() .iter() - .filter_map(|i| block.uncles().get(Into::::into(i) as usize)) + .filter_map(|i| block.uncles().get(Unpack::::unpack(&i) as usize)) .collect::>(); let content = packed::BlockTransactions::new_builder() .block_hash(block_hash) - .transactions( - transactions - .into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) - .uncles( - uncles - .into_iter() - .map(|uncle| uncle.data()) - .collect::>(), - ) + .transactions(transactions.into_iter().map(|tx| tx.data()).pack()) + .uncles(uncles.into_iter().map(|uncle| uncle.data()).pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/sync/src/relayer/get_transactions_process.rs b/sync/src/relayer/get_transactions_process.rs index 766ff2af4d..60e8067455 100644 --- a/sync/src/relayer/get_transactions_process.rs +++ b/sync/src/relayer/get_transactions_process.rs @@ -76,7 +76,7 @@ impl<'a> GetTransactionsProcess<'a> { .into_iter() .map(|(_, (tx, cycles))| { packed::RelayTransaction::new_builder() - .cycles(cycles) + .cycles(cycles.pack()) .transaction(tx.data()) .build() }) diff --git a/sync/src/relayer/mod.rs b/sync/src/relayer/mod.rs index 366bd8e292..0a143e9770 100644 --- a/sync/src/relayer/mod.rs +++ b/sync/src/relayer/mod.rs @@ -38,7 +38,6 @@ use ckb_shared::block_status::BlockStatus; use ckb_shared::Shared; use ckb_systemtime::unix_time_as_millis; use ckb_tx_pool::service::TxVerificationResult; -use ckb_types::packed::Transaction; use ckb_types::BlockNumberAndHash; use ckb_types::{ core::{self, BlockView}, @@ -272,7 +271,7 @@ impl Relayer { if !to_ask_proposals.is_empty() { let content = packed::GetBlockProposal::new_builder() .block_hash(block_hash_and_number.hash) - .proposals(to_ask_proposals.clone()) + .proposals(to_ask_proposals.clone().pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); if !send_message_to(nc, peer, &message).is_ok() { @@ -416,7 +415,7 @@ impl Relayer { .prefilled_transactions() .into_iter() .for_each(|pt| { - let index: usize = pt.index().into(); + let index: usize = pt.index().unpack(); let gap = index - block_transactions.len(); if gap > 0 { short_ids_iter @@ -496,12 +495,8 @@ impl Relayer { let block = if let Some(extension) = compact_block.extension() { packed::BlockV1::new_builder() .header(compact_block.header()) - .uncles(uncles) - .transactions( - txs.into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .uncles(uncles.pack()) + .transactions(txs.into_iter().map(|tx| tx.data()).pack()) .proposals(compact_block.proposals()) .extension(extension) .build() @@ -509,12 +504,8 @@ impl Relayer { } else { packed::Block::new_builder() .header(compact_block.header()) - .uncles(uncles) - .transactions( - txs.into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .uncles(uncles.pack()) + .transactions(txs.into_iter().map(|tx| tx.data()).pack()) .proposals(compact_block.proposals()) .build() } @@ -602,7 +593,7 @@ impl Relayer { let send_block_proposals = |nc: &dyn CKBProtocolContext, peer_index: PeerIndex, txs: Vec| { let content = packed::BlockProposal::new_builder() - .transactions(txs) + .transactions(txs.into_iter().pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let status = send_message_to(nc, peer_index, &message); @@ -648,7 +639,7 @@ impl Relayer { ); tx_hashes.truncate(MAX_RELAY_TXS_NUM_PER_BATCH); let content = packed::GetRelayTransactions::new_builder() - .tx_hashes(tx_hashes) + .tx_hashes(tx_hashes.pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let status = send_message_to(nc, peer, &message); @@ -730,7 +721,7 @@ impl Relayer { } for (peer, hashes) in selected { let content = packed::RelayTransactionHashes::new_builder() - .tx_hashes(hashes) + .tx_hashes(hashes.pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); @@ -799,7 +790,7 @@ fn build_and_broadcast_compact_block( let tip_header = packed::VerifiableHeader::new_builder() .header(block.header().data()) .uncles_hash(block.calc_uncles_hash()) - .extension(block.extension()) + .extension(Pack::pack(&block.extension())) .parent_chain_root(parent_chain_root) .build(); let light_client_message = { diff --git a/sync/src/relayer/tests/block_proposal_process.rs b/sync/src/relayer/tests/block_proposal_process.rs index fb56fa01ce..e88ec876ad 100644 --- a/sync/src/relayer/tests/block_proposal_process.rs +++ b/sync/src/relayer/tests/block_proposal_process.rs @@ -1,7 +1,7 @@ use crate::relayer::block_proposal_process::BlockProposalProcess; use crate::relayer::tests::helper::{build_chain, new_transaction}; use crate::Status; -use ckb_types::packed::{self, ProposalShortId, Transaction}; +use ckb_types::packed::{self, ProposalShortId}; use ckb_types::prelude::*; #[test] @@ -16,12 +16,7 @@ fn test_no_unknown() { relayer.shared.state().mark_as_known_tx(transaction.hash()); } let content = packed::BlockProposal::new_builder() - .transactions( - transactions - .into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .transactions(transactions.into_iter().map(|tx| tx.data()).pack()) .build(); let process = BlockProposalProcess::new(content.as_reader(), &relayer); @@ -36,12 +31,7 @@ fn test_no_asked() { let transactions = vec![transaction.clone()]; let content = packed::BlockProposal::new_builder() - .transactions( - transactions - .into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .transactions(transactions.into_iter().map(|tx| tx.data()).pack()) .build(); let process = BlockProposalProcess::new(content.as_reader(), &relayer); @@ -70,12 +60,7 @@ fn test_ok() { } let content = packed::BlockProposal::new_builder() - .transactions( - transactions - .into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .transactions(transactions.into_iter().map(|tx| tx.data()).pack()) .build(); let process = BlockProposalProcess::new(content.as_reader(), &relayer); @@ -104,12 +89,7 @@ fn test_clear_expired_inflight_proposals() { } let content = packed::BlockProposal::new_builder() - .transactions( - transactions - .into_iter() - .map(|tx| tx.data()) - .collect::>(), - ) + .transactions(transactions.into_iter().map(|tx| tx.data()).pack()) .build(); let process = BlockProposalProcess::new(content.as_reader(), &relayer); diff --git a/sync/src/relayer/tests/block_transactions_process.rs b/sync/src/relayer/tests/block_transactions_process.rs index 247baae90a..8b106b7d3f 100644 --- a/sync/src/relayer/tests/block_transactions_process.rs +++ b/sync/src/relayer/tests/block_transactions_process.rs @@ -26,24 +26,22 @@ fn test_accept_block() { let tx2 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1).unwrap()) + .capacity(Capacity::bytes(1).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let tx3 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(2).unwrap()) + .capacity(Capacity::bytes(2).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let uncle = BlockBuilder::default() - .proposals(Into::::into(vec![ - tx3.proposal_short_id() - ])) + .proposals(vec![tx3.proposal_short_id()].pack()) .build(); let block = BlockBuilder::default() @@ -72,8 +70,8 @@ fn test_accept_block() { let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder() .block_hash(block.header().hash()) - .transactions(vec![tx2.data()]) - .uncles(vec![uncle.as_uncle().data()]) + .transactions(vec![tx2.data()].pack()) + .uncles(vec![uncle.as_uncle().data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -106,10 +104,10 @@ fn test_unknown_request() { let tx2 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1).unwrap()) + .capacity(Capacity::bytes(1).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let block = BlockBuilder::default() @@ -135,7 +133,7 @@ fn test_unknown_request() { let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder() .block_hash(block.header().hash()) - .transactions(vec![tx2.data()]) + .transactions(vec![tx2.data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -159,14 +157,14 @@ fn test_invalid_transaction_root() { let tx2 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1).unwrap()) + .capacity(Capacity::bytes(1).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let prefilled = IndexTransaction::new_builder() - .index(0u32) + .index(0u32.pack()) .transaction(tx1.data()) .build(); @@ -180,8 +178,8 @@ fn test_invalid_transaction_root() { let compact_block = packed::CompactBlock::new_builder() .header(header_with_invalid_tx_root) - .short_ids(vec![tx2.proposal_short_id()]) - .prefilled_transactions(vec![prefilled]) + .short_ids(vec![tx2.proposal_short_id()].pack()) + .prefilled_transactions(vec![prefilled].pack()) .build(); let block_hash = compact_block.header().calc_header_hash(); @@ -200,7 +198,7 @@ fn test_invalid_transaction_root() { let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder() .block_hash(block_hash) - .transactions(vec![tx2.data()]) + .transactions(vec![tx2.data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -236,28 +234,28 @@ fn test_collision_and_send_missing_indexes() { let tx2 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1000).unwrap()) + .capacity(Capacity::bytes(1000).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let tx3 = TransactionBuilder::default() .input(CellInput::new(OutPoint::new(last_cellbase.hash(), 0), 0)) .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(2).unwrap()) + .capacity(Capacity::bytes(2).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let fake_hash = tx3 .hash() .as_builder() - .nth31(0u8) - .nth30(0u8) - .nth29(0u8) - .nth28(0u8) + .nth31(0u8.into()) + .nth30(0u8.into()) + .nth29(0u8.into()) + .nth28(0u8.into()) .build(); // Fake tx with the same ProposalShortId but different hash with tx3 let fake_tx = tx3.clone().fake_hash(fake_hash); @@ -296,7 +294,7 @@ fn test_collision_and_send_missing_indexes() { let block_transactions = packed::BlockTransactions::new_builder() .block_hash(block.header().hash()) - .transactions(vec![tx2.data()]) + .transactions(vec![tx2.data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -315,7 +313,7 @@ fn test_collision_and_send_missing_indexes() { let content = packed::GetBlockTransactions::new_builder() .block_hash(block.header().hash()) - .indexes([1u32, 2u32]) + .indexes([1u32, 2u32].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let data = message.as_bytes(); @@ -339,7 +337,7 @@ fn test_collision_and_send_missing_indexes() { // resend BlockTransactions with all the transactions without prefilled let new_block_transactions = packed::BlockTransactions::new_builder() .block_hash(block.header().hash()) - .transactions(vec![tx2.data(), tx3.data()]) + .transactions(vec![tx2.data(), tx3.data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -372,18 +370,18 @@ fn test_missing() { let tx2 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1).unwrap()) + .capacity(Capacity::bytes(1).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let tx3 = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(2).unwrap()) + .capacity(Capacity::bytes(2).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let block = BlockBuilder::default() @@ -410,7 +408,7 @@ fn test_missing() { let block_transactions = packed::BlockTransactions::new_builder() .block_hash(block.header().hash()) - .transactions(vec![tx2.data()]) + .transactions(vec![tx2.data()].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); @@ -429,7 +427,7 @@ fn test_missing() { let content = packed::GetBlockTransactions::new_builder() .block_hash(block.header().hash()) - .indexes([1, 2u32]) + .indexes([1, 2u32].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/sync/src/relayer/tests/block_transactions_verifier.rs b/sync/src/relayer/tests/block_transactions_verifier.rs index 6934c1f5af..16d49ac962 100644 --- a/sync/src/relayer/tests/block_transactions_verifier.rs +++ b/sync/src/relayer/tests/block_transactions_verifier.rs @@ -1,25 +1,21 @@ use super::helper::new_index_transaction; use crate::relayer::block_transactions_verifier::BlockTransactionsVerifier; use crate::{Status, StatusCode}; -use ckb_types::packed::{self, CompactBlock, CompactBlockBuilder}; +use ckb_types::packed::{CompactBlock, CompactBlockBuilder}; use ckb_types::prelude::*; // block_short_ids: vec![None, Some(1), None, Some(3), Some(4), None] fn build_compact_block() -> CompactBlock { - let prefilled_iter = vec![0, 2, 5] - .into_iter() - .map(new_index_transaction) - .collect::>(); + let prefilled_iter = vec![0, 2, 5].into_iter().map(new_index_transaction); let short_ids = vec![1, 3, 4] .into_iter() .map(new_index_transaction) - .map(|tx| tx.transaction().proposal_short_id()) - .collect::>(); + .map(|tx| tx.transaction().proposal_short_id()); CompactBlockBuilder::default() - .short_ids(short_ids) - .prefilled_transactions(prefilled_iter) + .short_ids(short_ids.pack()) + .prefilled_transactions(prefilled_iter.pack()) .build() } diff --git a/sync/src/relayer/tests/compact_block.rs b/sync/src/relayer/tests/compact_block.rs index 72b6169a81..12845293f8 100644 --- a/sync/src/relayer/tests/compact_block.rs +++ b/sync/src/relayer/tests/compact_block.rs @@ -13,18 +13,18 @@ fn test_block_short_ids() { ]; let prefilled_transactions = vec![ IndexTransactionBuilder::default() - .index(0u32) + .index(0u32.pack()) .transaction(TransactionBuilder::default().build().data()) .build(), IndexTransactionBuilder::default() - .index(2u32) + .index(2u32.pack()) .transaction(TransactionBuilder::default().build().data()) .build(), ]; let compact_block = compact_block_builder - .short_ids(short_ids) - .prefilled_transactions(prefilled_transactions) + .short_ids(short_ids.into_iter().pack()) + .prefilled_transactions(prefilled_transactions.into_iter().pack()) .build(); assert_eq!( diff --git a/sync/src/relayer/tests/compact_block_process.rs b/sync/src/relayer/tests/compact_block_process.rs index 1948a47e81..3473b8e405 100644 --- a/sync/src/relayer/tests/compact_block_process.rs +++ b/sync/src/relayer/tests/compact_block_process.rs @@ -113,9 +113,9 @@ fn test_unknow_parent() { let block = BlockBuilder::default() .header( HeaderBuilder::default() - .number(5) - .epoch(EpochNumberWithFraction::new(1, 5, 1000)) - .timestamp(unix_time_as_millis()) + .number(5.pack()) + .epoch(EpochNumberWithFraction::new(1, 5, 1000).pack()) + .timestamp(unix_time_as_millis().pack()) .build(), ) .transaction(TransactionBuilder::default().build()) @@ -145,7 +145,7 @@ fn test_unknow_parent() { let locator_hash = active_chain.get_locator((&header).into()); let content = packed::GetHeaders::new_builder() - .block_locator_hashes(locator_hash) + .block_locator_hashes(locator_hash.pack()) .hash_stop(packed::Byte32::zero()) .build(); let message = packed::SyncMessage::new_builder().set(content).build(); @@ -227,7 +227,7 @@ fn test_header_invalid() { // Better block but block number is invalid let header = new_header_builder(relayer.shared.shared(), &parent) - .number(4) + .number(4.pack()) .build(); let block = BlockBuilder::default() @@ -285,10 +285,10 @@ fn test_send_missing_indexes() { TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1).unwrap()) + .capacity(Capacity::bytes(1).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(), ) .uncle(uncle.as_uncle()) @@ -321,8 +321,8 @@ fn test_send_missing_indexes() { let content = packed::GetBlockTransactions::new_builder() .block_hash(block.header().hash()) - .indexes([1u32]) - .uncle_indexes([0u32]) + .indexes([1u32].pack()) + .uncle_indexes([0u32].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let data = message.as_bytes(); @@ -338,7 +338,7 @@ fn test_send_missing_indexes() { let content = packed::GetBlockProposal::new_builder() .block_hash(block.header().hash()) - .proposals(vec![proposal_id]) + .proposals(vec![proposal_id].into_iter().pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let data = message.as_bytes(); @@ -368,12 +368,12 @@ fn test_accept_block() { ); let mock_block_1 = BlockBuilder::default() - .number(4) - .epoch(EpochNumberWithFraction::new(1, 4, 1000)) + .number(4.pack()) + .epoch(EpochNumberWithFraction::new(1, 4, 1000).pack()) .build(); let mock_compact_block_1 = CompactBlock::build_from_block(&mock_block_1, &Default::default()); - let mock_block_2 = block.as_advanced_builder().number(7).build(); + let mock_block_2 = block.as_advanced_builder().number(7.pack()).build(); let mock_compact_block_2 = CompactBlock::build_from_block(&mock_block_2, &Default::default()); { let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks(); @@ -522,20 +522,20 @@ fn test_collision() { let missing_tx = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(1000).unwrap()) + .capacity(Capacity::bytes(1000).unwrap().pack()) .build(), ) .input(CellInput::new(OutPoint::new(last_cellbase.hash(), 0), 0)) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let fake_hash = missing_tx .hash() .as_builder() - .nth31(0u8) - .nth30(0u8) - .nth29(0u8) - .nth28(0u8) + .nth31(0u8.into()) + .nth30(0u8.into()) + .nth29(0u8.into()) + .nth28(0u8.into()) .build(); // Fake tx with the same ProposalShortId but different hash with missing_tx let fake_tx = missing_tx.clone().fake_hash(fake_hash); @@ -589,7 +589,7 @@ fn test_collision() { let content = packed::GetBlockTransactions::new_builder() .block_hash(block.header().hash()) - .indexes([1u32]) + .indexes([1u32].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); let data = message.as_bytes(); diff --git a/sync/src/relayer/tests/compact_block_verifier.rs b/sync/src/relayer/tests/compact_block_verifier.rs index e85da0c024..e0d7f3125d 100644 --- a/sync/src/relayer/tests/compact_block_verifier.rs +++ b/sync/src/relayer/tests/compact_block_verifier.rs @@ -1,17 +1,14 @@ use super::helper::new_index_transaction; use crate::relayer::compact_block_verifier::{PrefilledVerifier, ShortIdsVerifier}; use crate::{Status, StatusCode}; -use ckb_types::packed::{self, CompactBlockBuilder, ProposalShortId}; +use ckb_types::packed::{CompactBlockBuilder, ProposalShortId}; use ckb_types::prelude::*; #[test] fn test_unordered_prefilled() { - let prefilled = vec![0, 1, 2, 4, 3] - .into_iter() - .map(new_index_transaction) - .collect::>(); + let prefilled = vec![0, 1, 2, 4, 3].into_iter().map(new_index_transaction); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) + .prefilled_transactions(prefilled.pack()) .build(); assert_eq!( PrefilledVerifier::verify(&block), @@ -21,23 +18,18 @@ fn test_unordered_prefilled() { #[test] fn test_ordered_prefilled() { - let prefilled = (0..5) - .map(new_index_transaction) - .collect::>(); + let prefilled = (0..5).map(new_index_transaction); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) + .prefilled_transactions(prefilled.pack()) .build(); assert_eq!(PrefilledVerifier::verify(&block), Status::ok()); } #[test] fn test_overflow_prefilled() { - let prefilled = vec![0, 1, 2, 5] - .into_iter() - .map(new_index_transaction) - .collect::>(); + let prefilled = vec![0, 1, 2, 5].into_iter().map(new_index_transaction); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) + .prefilled_transactions(prefilled.pack()) .build(); assert_eq!( PrefilledVerifier::verify(&block), @@ -53,11 +45,9 @@ fn test_cellbase_not_prefilled() { StatusCode::CompactBlockHasNotPrefilledCellbase.into(), ); - let prefilled = (1..5) - .map(new_index_transaction) - .collect::>(); + let prefilled = (1..5).map(new_index_transaction); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) + .prefilled_transactions(prefilled.pack()) .build(); assert_eq!( PrefilledVerifier::verify(&block), @@ -72,7 +62,9 @@ fn test_duplicated_short_ids() { .collect(); short_ids.push(short_ids[0].clone()); - let block = CompactBlockBuilder::default().short_ids(short_ids).build(); + let block = CompactBlockBuilder::default() + .short_ids(short_ids.into_iter().pack()) + .build(); assert_eq!( ShortIdsVerifier::verify(&block), StatusCode::CompactBlockHasDuplicatedShortIds.into(), @@ -81,16 +73,12 @@ fn test_duplicated_short_ids() { #[test] fn test_intersected_short_ids() { - let prefilled = (0..=5) - .map(new_index_transaction) - .collect::>(); - let short_ids = (5..9) - .map(|i| new_index_transaction(i).transaction().proposal_short_id()) - .collect::>(); + let prefilled = (0..=5).map(new_index_transaction); + let short_ids = (5..9).map(|i| new_index_transaction(i).transaction().proposal_short_id()); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) - .short_ids(short_ids) + .prefilled_transactions(prefilled.pack()) + .short_ids(short_ids.pack()) .build(); assert_eq!( ShortIdsVerifier::verify(&block), @@ -100,17 +88,13 @@ fn test_intersected_short_ids() { #[test] fn test_normal() { - let prefilled = vec![1, 2, 5] - .into_iter() - .map(new_index_transaction) - .collect::>(); + let prefilled = vec![1, 2, 5].into_iter().map(new_index_transaction); let short_ids = vec![0, 3, 4] .into_iter() - .map(|i| new_index_transaction(i).transaction().proposal_short_id()) - .collect::>(); + .map(|i| new_index_transaction(i).transaction().proposal_short_id()); let block = CompactBlockBuilder::default() - .prefilled_transactions(prefilled) - .short_ids(short_ids) + .prefilled_transactions(prefilled.pack()) + .short_ids(short_ids.pack()) .build(); assert_eq!(ShortIdsVerifier::verify(&block), Status::ok()); } diff --git a/sync/src/relayer/tests/get_block_proposal_process.rs b/sync/src/relayer/tests/get_block_proposal_process.rs index f38308dc06..568ba83dc7 100644 --- a/sync/src/relayer/tests/get_block_proposal_process.rs +++ b/sync/src/relayer/tests/get_block_proposal_process.rs @@ -17,7 +17,7 @@ fn test_duplicate() { let content = packed::GetBlockProposal::new_builder() .block_hash(hash) - .proposals(vec![id.clone(), id]) + .proposals(vec![id.clone(), id].into_iter().pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); let nc = Arc::new(mock_protocol_context); diff --git a/sync/src/relayer/tests/get_transactions_process.rs b/sync/src/relayer/tests/get_transactions_process.rs index 6839daf7bb..7f38edf5ad 100644 --- a/sync/src/relayer/tests/get_transactions_process.rs +++ b/sync/src/relayer/tests/get_transactions_process.rs @@ -13,7 +13,7 @@ fn test_duplicate() { let tx = new_transaction(&relayer, 1, &always_success_out_point); let tx_hash = tx.hash(); let content = packed::GetRelayTransactions::new_builder() - .tx_hashes(vec![tx_hash.clone(), tx_hash]) + .tx_hashes(vec![tx_hash.clone(), tx_hash].pack()) .build(); let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2); let nc = Arc::new(mock_protocol_context); diff --git a/sync/src/relayer/tests/helper.rs b/sync/src/relayer/tests/helper.rs index 72d85709cd..a11ceb1fe8 100644 --- a/sync/src/relayer/tests/helper.rs +++ b/sync/src/relayer/tests/helper.rs @@ -38,14 +38,14 @@ pub(crate) fn new_index_transaction(index: usize) -> IndexTransaction { let transaction = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(index).unwrap()) + .capacity(Capacity::bytes(index).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); IndexTransactionBuilder::default() - .index(index) + .index(index.pack()) .transaction(transaction.data()) .build() } @@ -60,10 +60,10 @@ pub(crate) fn new_header_builder(shared: &Shared, parent: &HeaderView) -> Header .epoch(); HeaderBuilder::default() .parent_hash(parent_hash) - .number(parent.number() + 1) - .timestamp(parent.timestamp() + 1) - .epoch(epoch.number_with_fraction(parent.number() + 1)) - .compact_target(epoch.compact_target()) + .number((parent.number() + 1).pack()) + .timestamp((parent.timestamp() + 1).pack()) + .epoch(epoch.number_with_fraction(parent.number() + 1).pack()) + .compact_target(epoch.compact_target().pack()) } pub(crate) fn new_transaction( @@ -89,10 +89,10 @@ pub(crate) fn new_transaction( .input(CellInput::new(previous_output, 0)) .output( CellOutputBuilder::default() - .capacity(Capacity::bytes(500 + index).unwrap() ) // use capacity to identify transactions + .capacity(Capacity::bytes(500 + index).unwrap().pack()) // use capacity to identify transactions .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .cell_dep( CellDep::new_builder() .out_point(always_success_out_point.to_owned()) @@ -138,7 +138,7 @@ pub(crate) fn build_chain(tip: BlockNumber) -> (Relayer, OutPoint) { let always_success_tx = TransactionBuilder::default() .input(CellInput::new(OutPoint::null(), 0)) .output(always_success_cell.clone()) - .output_data(always_success_cell_data) + .output_data(always_success_cell_data.pack()) .witness(always_success_script.clone().into_witness()) .build(); let always_success_out_point = OutPoint::new(always_success_tx.hash(), 0); @@ -146,9 +146,9 @@ pub(crate) fn build_chain(tip: BlockNumber) -> (Relayer, OutPoint) { let (shared, mut pack) = { let dao = genesis_dao_data(vec![&always_success_tx]).unwrap(); let genesis = BlockBuilder::default() - .timestamp(unix_time_as_millis()) + .timestamp(unix_time_as_millis().pack()) .dao(dao) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .transaction(always_success_tx) .build(); let epoch_ext = build_genesis_epoch_ext( @@ -188,11 +188,11 @@ pub(crate) fn build_chain(tip: BlockNumber) -> (Relayer, OutPoint) { .input(CellInput::new_cellbase_input(parent.header().number() + 1)) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(50000)) + .capacity(capacity_bytes!(50000).pack()) .lock(always_success_script.to_owned()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .witness(Script::default().into_witness()) .build(); let header = new_header_builder(&shared, &parent.header()).build(); @@ -273,20 +273,22 @@ pub(crate) fn gen_block( let mut block_builder = BlockBuilder::default() .parent_hash(parent_header.hash()) .timestamp( - parent_header + (parent_header .timestamp() .checked_add_signed(timestamp_delta) - .unwrap(), + .unwrap()) + .pack(), ) - .number(number) + .number(number.pack()) .compact_target( - epoch + (epoch .compact_target() .checked_add_signed(target_delta) - .unwrap(), + .unwrap()) + .pack(), ) .dao(dao) - .epoch(epoch.number_with_fraction(number)) + .epoch(epoch.number_with_fraction(number).pack()) .transactions(txs); if let Some(uncle) = uncle_opt { block_builder = block_builder.uncle(uncle) diff --git a/sync/src/relayer/tests/reconstruct_block.rs b/sync/src/relayer/tests/reconstruct_block.rs index 167356b822..a7e55ec1a7 100644 --- a/sync/src/relayer/tests/reconstruct_block.rs +++ b/sync/src/relayer/tests/reconstruct_block.rs @@ -20,12 +20,9 @@ fn test_missing_txs() { // Case: miss tx.0 { let compact_block_builder = CompactBlockBuilder::default(); - let short_ids = prepare - .iter() - .map(|tx| tx.proposal_short_id()) - .collect::>(); + let short_ids = prepare.iter().map(|tx| tx.proposal_short_id()); let transactions: Vec = prepare.iter().skip(1).cloned().collect(); - let compact = compact_block_builder.short_ids(short_ids).build(); + let compact = compact_block_builder.short_ids(short_ids.pack()).build(); assert_eq!( relayer.reconstruct_block( &relayer.shared().active_chain(), @@ -41,10 +38,7 @@ fn test_missing_txs() { // Case: miss multiple txs { let compact_block_builder = CompactBlockBuilder::default(); - let short_ids = prepare - .iter() - .map(|tx| tx.proposal_short_id()) - .collect::>(); + let short_ids = prepare.iter().map(|tx| tx.proposal_short_id()); let transactions: Vec = prepare.iter().skip(1).step_by(2).cloned().collect(); let missing = prepare @@ -53,7 +47,7 @@ fn test_missing_txs() { .step_by(2) .map(|(i, _)| i) .collect(); - let compact = compact_block_builder.short_ids(short_ids).build(); + let compact = compact_block_builder.short_ids(short_ids.pack()).build(); assert_eq!( relayer.reconstruct_block( &relayer.shared().active_chain(), @@ -110,7 +104,7 @@ fn test_reconstruct_transactions_and_uncles() { // BLOCK_VALID let ext = packed::BlockExtBuilder::default() - .verified(Some(true)) + .verified(Some(true).pack()) .build(); let compact = packed::CompactBlock::build_from_block(&block, &prefilled); @@ -133,7 +127,7 @@ fn test_reconstruct_transactions_and_uncles() { { let db_txn = relayer.shared().shared().store().begin_transaction(); db_txn.insert_block(&uncle).unwrap(); - db_txn.insert_block_ext(&uncle_hash, &ext.into()).unwrap(); + db_txn.insert_block_ext(&uncle_hash, &ext.unpack()).unwrap(); db_txn.commit().unwrap(); } relayer.shared().shared().refresh_snapshot(); @@ -155,7 +149,7 @@ fn test_reconstruct_invalid_uncles() { let uncle = BlockBuilder::default().build(); // BLOCK_VALID let ext = packed::BlockExtBuilder::default() - .verified(Some(false)) + .verified(Some(false).pack()) .build(); let block = BlockBuilder::default() @@ -169,7 +163,7 @@ fn test_reconstruct_invalid_uncles() { let db_txn = relayer.shared().shared().store().begin_transaction(); db_txn.insert_block(&uncle).unwrap(); db_txn.attach_block(&uncle).unwrap(); - db_txn.insert_block_ext(&uncle_hash, &ext.into()).unwrap(); + db_txn.insert_block_ext(&uncle_hash, &ext.unpack()).unwrap(); db_txn.commit().unwrap(); } relayer.shared().shared().refresh_snapshot(); diff --git a/sync/src/relayer/transactions_process.rs b/sync/src/relayer/transactions_process.rs index 146cb41be0..11ad489500 100644 --- a/sync/src/relayer/transactions_process.rs +++ b/sync/src/relayer/transactions_process.rs @@ -45,7 +45,12 @@ impl<'a> TransactionsProcess<'a> { self.message .transactions() .iter() - .map(|tx| (tx.transaction().to_entity().into_view(), tx.cycles().into())) + .map(|tx| { + ( + tx.transaction().to_entity().into_view(), + tx.cycles().unpack(), + ) + }) .filter(|(tx, _)| { !tx_filter.contains(&tx.hash()) && unknown_tx_hashes diff --git a/sync/src/synchronizer/get_headers_process.rs b/sync/src/synchronizer/get_headers_process.rs index d5e8d7e4d7..12c5041413 100644 --- a/sync/src/synchronizer/get_headers_process.rs +++ b/sync/src/synchronizer/get_headers_process.rs @@ -81,12 +81,7 @@ impl<'a> GetHeadersProcess<'a> { debug!("headers len={}", headers.len()); let content = packed::SendHeaders::new_builder() - .headers( - headers - .into_iter() - .map(|x| x.data()) - .collect::>(), - ) + .headers(headers.into_iter().map(|x| x.data()).pack()) .build(); let message = packed::SyncMessage::new_builder().set(content).build(); diff --git a/sync/src/synchronizer/mod.rs b/sync/src/synchronizer/mod.rs index fe1bee8004..83aa1213c3 100644 --- a/sync/src/synchronizer/mod.rs +++ b/sync/src/synchronizer/mod.rs @@ -236,7 +236,7 @@ impl BlockFetchCMD { let assume_valid_target_find = |flag: &mut CanStart| { let mut assume_valid_target = shared.assume_valid_target(); if let Some(ref target) = *assume_valid_target { - match shared.header_map().get(&target.into()) { + match shared.header_map().get(&target.pack()) { Some(header) => { *flag = CanStart::Ready; info!("assume valid target found in header_map; CKB will start fetch blocks now"); @@ -281,7 +281,7 @@ impl BlockFetchCMD { fn send_getblocks(v_fetch: Vec, nc: &ServiceControl, peer: PeerIndex) { let content = packed::GetBlocks::new_builder() - .block_hashes(v_fetch.clone()) + .block_hashes(v_fetch.clone().pack()) .build(); let message = packed::SyncMessage::new_builder().set(content).build(); @@ -790,7 +790,7 @@ impl Synchronizer { peer: PeerIndex, ) { let content = packed::GetBlocks::new_builder() - .block_hashes(v_fetch.clone()) + .block_hashes(v_fetch.clone().pack()) .build(); let message = packed::SyncMessage::new_builder().set(content).build(); diff --git a/sync/src/tests/inflight_blocks.rs b/sync/src/tests/inflight_blocks.rs index 6f793bfaa7..4511a85821 100644 --- a/sync/src/tests/inflight_blocks.rs +++ b/sync/src/tests/inflight_blocks.rs @@ -1,6 +1,7 @@ use crate::types::InflightBlocks; use ckb_constant::sync::BLOCK_DOWNLOAD_TIMEOUT; use ckb_types::h256; +use ckb_types::prelude::*; use ckb_types::BlockNumberAndHash; use std::collections::HashSet; @@ -9,24 +10,24 @@ fn inflight_blocks_count() { let mut inflight_blocks = InflightBlocks::default(); // don't allow 2 peer for one block - assert!(inflight_blocks.insert(2.into(), (1, h256!("0x1").into()).into())); - assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); + assert!(inflight_blocks.insert(2.into(), (1, h256!("0x1").pack()).into())); + assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); // peer 1 inflight - assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); + assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); - assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").into()).into())); + assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").pack()).into())); assert_eq!(inflight_blocks.total_inflight_count(), 2); // 0x1 0x2 assert_eq!(inflight_blocks.peer_inflight_count(1.into()), 1); assert_eq!(inflight_blocks.peer_inflight_count(2.into()), 1); // one block inflight assert_eq!( inflight_blocks.inflight_block_by_peer(1.into()).cloned(), - Some(HashSet::from_iter(vec![(2, h256!("0x2").into()).into()])) + Some(HashSet::from_iter(vec![(2, h256!("0x2").pack()).into()])) ); // receive block 0x1 - inflight_blocks.remove_by_block((1, h256!("0x1").into()).into()); + inflight_blocks.remove_by_block((1, h256!("0x1").pack()).into()); assert_eq!(inflight_blocks.total_inflight_count(), 1); // 0x2 assert_eq!(inflight_blocks.peer_inflight_count(1.into()), 1); @@ -35,7 +36,7 @@ fn inflight_blocks_count() { inflight_blocks .inflight_block_by_peer(1.into()) .map(|set| set.iter().collect()), - Some(vec![&(2, h256!("0x2").into()).into()]) + Some(vec![&(2, h256!("0x2").pack()).into()]) ); } @@ -43,19 +44,19 @@ fn inflight_blocks_count() { fn inflight_blocks_state() { let mut inflight_blocks = InflightBlocks::default(); - assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); - assert!(!inflight_blocks.insert(2.into(), (1, h256!("0x1").into()).into())); - assert!(!inflight_blocks.insert(3.into(), (1, h256!("0x1").into()).into())); + assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); + assert!(!inflight_blocks.insert(2.into(), (1, h256!("0x1").pack()).into())); + assert!(!inflight_blocks.insert(3.into(), (1, h256!("0x1").pack()).into())); // peer 1 inflight - assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); - assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").into()).into())); + assert!(!inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); + assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").pack()).into())); - assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").into()).into())); + assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").pack()).into())); assert_eq!( inflight_blocks - .inflight_state_by_block(&(1, h256!("0x1").into()).into()) + .inflight_state_by_block(&(1, h256!("0x1").pack()).into()) .cloned() .map(|state| { state.peer }), Some(1.into()) @@ -63,7 +64,7 @@ fn inflight_blocks_state() { assert_eq!( inflight_blocks - .inflight_state_by_block(&(3, h256!("0x3").into()).into()) + .inflight_state_by_block(&(3, h256!("0x3").pack()).into()) .map(|state| state.peer), Some(3.into()) ); @@ -74,14 +75,14 @@ fn inflight_blocks_state() { assert_eq!( inflight_blocks - .inflight_state_by_block(&(1, h256!("0x1").into()).into()) + .inflight_state_by_block(&(1, h256!("0x1").pack()).into()) .map(|state| state.peer), None ); assert_eq!( inflight_blocks - .inflight_state_by_block(&(3, h256!("0x3").into()).into()) + .inflight_state_by_block(&(3, h256!("0x3").pack()).into()) .map(|state| state.peer), Some(3.into()) ); @@ -94,45 +95,45 @@ fn inflight_blocks_timeout() { let mut inflight_blocks = InflightBlocks::default(); inflight_blocks.protect_num = 0; - assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); - assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").into()).into())); - assert!(inflight_blocks.insert(2.into(), (3, h256!("0x3").into()).into())); - assert!(!inflight_blocks.insert(1.into(), (3, h256!("0x3").into()).into())); - assert!(inflight_blocks.insert(1.into(), (4, h256!("0x4").into()).into())); - assert!(inflight_blocks.insert(2.into(), (5, h256!("0x5").into()).into())); - assert!(!inflight_blocks.insert(2.into(), (5, h256!("0x5").into()).into())); + assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); + assert!(inflight_blocks.insert(1.into(), (2, h256!("0x2").pack()).into())); + assert!(inflight_blocks.insert(2.into(), (3, h256!("0x3").pack()).into())); + assert!(!inflight_blocks.insert(1.into(), (3, h256!("0x3").pack()).into())); + assert!(inflight_blocks.insert(1.into(), (4, h256!("0x4").pack()).into())); + assert!(inflight_blocks.insert(2.into(), (5, h256!("0x5").pack()).into())); + assert!(!inflight_blocks.insert(2.into(), (5, h256!("0x5").pack()).into())); _faketime_guard.set_faketime(BLOCK_DOWNLOAD_TIMEOUT + 1); - assert!(!inflight_blocks.insert(3.into(), (3, h256!("0x3").into()).into())); - assert!(!inflight_blocks.insert(3.into(), (2, h256!("0x2").into()).into())); - assert!(inflight_blocks.insert(4.into(), (6, h256!("0x6").into()).into())); - assert!(inflight_blocks.insert(1.into(), (7, h256!("0x7").into()).into())); + assert!(!inflight_blocks.insert(3.into(), (3, h256!("0x3").pack()).into())); + assert!(!inflight_blocks.insert(3.into(), (2, h256!("0x2").pack()).into())); + assert!(inflight_blocks.insert(4.into(), (6, h256!("0x6").pack()).into())); + assert!(inflight_blocks.insert(1.into(), (7, h256!("0x7").pack()).into())); let peers = inflight_blocks.prune(0); assert_eq!(peers, HashSet::from_iter(vec![1.into()])); - assert!(inflight_blocks.insert(3.into(), (2, h256!("0x2").into()).into())); - assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").into()).into())); + assert!(inflight_blocks.insert(3.into(), (2, h256!("0x2").pack()).into())); + assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").pack()).into())); assert_eq!(inflight_blocks.peer_can_fetch_count(2.into()), 32 >> 4); assert_eq!( inflight_blocks - .inflight_state_by_block(&(3, h256!("0x3").into()).into()) + .inflight_state_by_block(&(3, h256!("0x3").pack()).into()) .map(|state| state.peer), Some(3.into()) ); assert_eq!( inflight_blocks - .inflight_state_by_block(&(2, h256!("0x2").into()).into()) + .inflight_state_by_block(&(2, h256!("0x2").pack()).into()) .map(|state| state.peer), Some(3.into()) ); assert_eq!( inflight_blocks - .inflight_state_by_block(&(6, h256!("0x6").into()).into()) + .inflight_state_by_block(&(6, h256!("0x6").pack()).into()) .cloned() .map(|state| state.peer), Some(4.into()) @@ -147,13 +148,13 @@ fn inflight_trace_number_state() { let mut inflight_blocks = InflightBlocks::default(); inflight_blocks.protect_num = 0; - assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").into()).into())); - assert!(inflight_blocks.insert(2.into(), (2, h256!("0x2").into()).into())); - assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").into()).into())); - assert!(inflight_blocks.insert(4.into(), (3, h256!("0x33").into()).into())); - assert!(inflight_blocks.insert(5.into(), (4, h256!("0x4").into()).into())); - assert!(inflight_blocks.insert(6.into(), (5, h256!("0x5").into()).into())); - assert!(inflight_blocks.insert(7.into(), (5, h256!("0x55").into()).into())); + assert!(inflight_blocks.insert(1.into(), (1, h256!("0x1").pack()).into())); + assert!(inflight_blocks.insert(2.into(), (2, h256!("0x2").pack()).into())); + assert!(inflight_blocks.insert(3.into(), (3, h256!("0x3").pack()).into())); + assert!(inflight_blocks.insert(4.into(), (3, h256!("0x33").pack()).into())); + assert!(inflight_blocks.insert(5.into(), (4, h256!("0x4").pack()).into())); + assert!(inflight_blocks.insert(6.into(), (5, h256!("0x5").pack()).into())); + assert!(inflight_blocks.insert(7.into(), (5, h256!("0x55").pack()).into())); let list = inflight_blocks.prune(2); assert!(list.is_empty()); @@ -171,10 +172,10 @@ fn inflight_trace_number_state() { .cloned() .collect::>(), HashSet::from_iter(vec![ - (1, h256!("0x1").into()).into(), - (2, h256!("0x2").into()).into(), - (3, h256!("0x3").into()).into(), - (3, h256!("0x33").into()).into() + (1, h256!("0x1").pack()).into(), + (2, h256!("0x2").pack()).into(), + (3, h256!("0x3").pack()).into(), + (3, h256!("0x33").pack()).into() ]) ); @@ -186,10 +187,10 @@ fn inflight_trace_number_state() { assert!(inflight_blocks.restart_number == 3); assert!(inflight_blocks - .inflight_state_by_block(&(3, h256!("0x3").into()).into()) + .inflight_state_by_block(&(3, h256!("0x3").pack()).into()) .is_none()); assert!(inflight_blocks - .inflight_state_by_block(&(3, h256!("0x33").into()).into()) + .inflight_state_by_block(&(3, h256!("0x33").pack()).into()) .is_none()); assert_eq!(inflight_blocks.peer_can_fetch_count(3.into()), 32 >> 1); diff --git a/sync/src/tests/sync_shared.rs b/sync/src/tests/sync_shared.rs index 6219bc3eb5..da9dea6e83 100644 --- a/sync/src/tests/sync_shared.rs +++ b/sync/src/tests/sync_shared.rs @@ -102,7 +102,7 @@ fn test_insert_parent_unknown_block() { let invalid_orphan = block .as_advanced_builder() .header(block.header()) - .number(1000) + .number(1000.pack()) .build(); Arc::new(invalid_orphan) @@ -256,7 +256,7 @@ fn test_switch_valid_fork() { .unwrap(); for _ in 3..shared.active_chain().tip_number() { let block = inherit_block(fork_shared.shared(), &parent_header.hash()) - .timestamp(parent_header.timestamp() + 3) + .timestamp((parent_header.timestamp() + 3).pack()) .build(); let arc_block = Arc::new(block.clone()); assert!(fork_shared @@ -281,7 +281,7 @@ fn test_switch_valid_fork() { // Make the fork switch as the main chain. for _ in tip_number..tip_number + 2 { let block = inherit_block(fork_shared.shared(), &parent_header.hash()) - .timestamp(parent_header.timestamp() + 3) + .timestamp((parent_header.timestamp() + 3).pack()) .build(); let arc_block = Arc::new(block.clone()); assert!(fork_shared @@ -330,7 +330,7 @@ fn test_sync_relay_collaboration() { packed::CompactBlock::build_from_block(&new_block, &std::collections::HashSet::new()); let headers_content = packed::SendHeaders::new_builder() - .headers(vec![new_block.header().data()]) + .headers([new_block.header()].map(|x| x.data()).pack()) .build(); // keep header process snapshot on old state, this is the bug reason @@ -404,7 +404,7 @@ fn test_sync_relay_collaboration2() { let next_timestamp = next_block.timestamp() + 2; let new_block = new_block .as_advanced_builder() - .timestamp(next_timestamp) + .timestamp(next_timestamp.pack()) .build(); Arc::new(new_block) @@ -417,7 +417,7 @@ fn test_sync_relay_collaboration2() { packed::CompactBlock::build_from_block(&new_block_1, &std::collections::HashSet::new()); let headers_content = packed::SendHeaders::new_builder() - .headers(vec![new_block.header().data()]) + .headers([new_block.header()].map(|x| x.data()).pack()) .build(); // keep header process snapshot on old state, this is the bug reason diff --git a/sync/src/tests/synchronizer/basic_sync.rs b/sync/src/tests/synchronizer/basic_sync.rs index 4337fb5312..1eaa2c3bc9 100644 --- a/sync/src/tests/synchronizer/basic_sync.rs +++ b/sync/src/tests/synchronizer/basic_sync.rs @@ -98,14 +98,14 @@ fn setup_node(height: u64) -> (TestNode, Shared) { .witness(always_success_script.clone().into_witness()) .input(CellInput::new(OutPoint::null(), 0)) .output(always_success_cell.clone()) - .output_data(always_success_cell_data) + .output_data(always_success_cell_data.pack()) .build(); let dao = genesis_dao_data(vec![&always_success_tx]).unwrap(); let mut block = BlockBuilder::default() - .timestamp(unix_time_as_millis()) - .compact_target(difficulty_to_compact(U256::from(1000u64))) + .timestamp(unix_time_as_millis().pack()) + .compact_target(difficulty_to_compact(U256::from(1000u64)).pack()) .dao(dao) .transaction(always_success_tx) .build(); @@ -150,11 +150,11 @@ fn setup_node(height: u64) -> (TestNode, Shared) { builder .output( CellOutputBuilder::default() - .capacity(reward.total) + .capacity(reward.total.pack()) .lock(always_success_script.to_owned()) .build(), ) - .output_data(Bytes::default()) + .output_data(Bytes::default().pack()) .build() }; @@ -176,15 +176,15 @@ fn setup_node(height: u64) -> (TestNode, Shared) { .chain_root_mmr(block.header().number()) .get_root() .expect("chain root_mmr"); - let bytes = chain_root.calc_mmr_hash().as_bytes().into(); + let bytes = chain_root.calc_mmr_hash().as_bytes().pack(); block = BlockBuilder::default() .transaction(cellbase) .parent_hash(block.header().hash()) - .number(number) - .epoch(epoch.number_with_fraction(number)) - .timestamp(timestamp) - .compact_target(epoch.compact_target()) + .number(number.pack()) + .epoch(epoch.number_with_fraction(number).pack()) + .timestamp(timestamp.pack()) + .compact_target(epoch.compact_target().pack()) .dao(dao) .extension(Some(bytes)) .build(); diff --git a/sync/src/tests/synchronizer/functions.rs b/sync/src/tests/synchronizer/functions.rs index 45892f1663..a63937d727 100644 --- a/sync/src/tests/synchronizer/functions.rs +++ b/sync/src/tests/synchronizer/functions.rs @@ -81,8 +81,12 @@ fn create_cellbase( builder.build() } else { builder - .output(CellOutputBuilder::default().capacity(reward.total).build()) - .output_data(Bytes::new()) + .output( + CellOutputBuilder::default() + .capacity(reward.total.pack()) + .build(), + ) + .output_data(Bytes::new().pack()) .build() } } @@ -110,16 +114,16 @@ fn gen_block( .chain_root_mmr(parent_header.number()) .get_root() .expect("chain root_mmr"); - let bytes = chain_root.calc_mmr_hash().as_bytes().into(); + let bytes = chain_root.calc_mmr_hash().as_bytes().pack(); BlockBuilder::default() .transaction(cellbase) .parent_hash(parent_header.hash()) - .timestamp(now) - .epoch(epoch.number_with_fraction(number)) - .number(number) - .compact_target(epoch.compact_target()) - .nonce(nonce) + .timestamp(now.pack()) + .epoch(epoch.number_with_fraction(number).pack()) + .number(number.pack()) + .compact_target(epoch.compact_target().pack()) + .nonce(nonce.pack()) .dao(dao) .extension(Some(bytes)) .build() @@ -626,12 +630,7 @@ fn test_sync_process() { ); let sendheaders = SendHeadersBuilder::default() - .headers( - headers - .iter() - .map(|h| h.data()) - .collect::>(), - ) + .headers(headers.iter().map(|h| h.data()).pack()) .build(); let mock_nc = mock_network_context(4); @@ -690,12 +689,7 @@ fn test_sync_process() { insert_block(&synchronizer2.chain, &shared2, 201u128, 201); let headers = vec![synchronizer2.shared.active_chain().tip_header()]; let sendheaders = SendHeadersBuilder::default() - .headers( - headers - .iter() - .map(|h| h.data()) - .collect::>(), - ) + .headers(headers.iter().map(|h| h.data()).pack()) .build(); assert_eq!( HeadersProcess::new(sendheaders.as_reader(), &synchronizer1, peer1, &mock_nc).execute(), @@ -772,7 +766,7 @@ fn test_chain_sync_timeout() { let consensus = Consensus::default(); let block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(3u64))) + .compact_target(difficulty_to_compact(U256::from(3u64)).pack()) .transaction(consensus.genesis_block().transactions()[0].clone()) .build(); let consensus = ConsensusBuilder::default().genesis_block(block).build(); @@ -969,7 +963,7 @@ fn test_n_sync_started() { let consensus = Consensus::default(); let block = BlockBuilder::default() - .compact_target(difficulty_to_compact(U256::from(3u64))) + .compact_target(difficulty_to_compact(U256::from(3u64)).pack()) .transaction(consensus.genesis_block().transactions()[0].clone()) .build(); let consensus = ConsensusBuilder::default().genesis_block(block).build(); @@ -1116,7 +1110,9 @@ fn test_fix_last_common_header() { .map(|number| graph.get(&f_(number)).cloned().unwrap()) .map(|block| block.header().data()) .collect::>(); - let sendheaders = SendHeadersBuilder::default().headers(fork_headers).build(); + let sendheaders = SendHeadersBuilder::default() + .headers(fork_headers.pack()) + .build(); synchronizer.on_connected(&nc, peer); assert!( HeadersProcess::new(sendheaders.as_reader(), &synchronizer, peer, &nc) @@ -1191,7 +1187,7 @@ fn get_blocks_process() { let genesis_hash = shared.consensus().genesis_hash(); let message_with_genesis = packed::GetBlocks::new_builder() - .block_hashes(vec![genesis_hash]) + .block_hashes(vec![genesis_hash].pack()) .build(); let nc = mock_network_context(1); @@ -1204,7 +1200,7 @@ fn get_blocks_process() { let hash = shared.snapshot().get_block_hash(1).unwrap(); let message_with_dup = packed::GetBlocks::new_builder() - .block_hashes(vec![hash.clone(), hash]) + .block_hashes(vec![hash.clone(), hash].pack()) .build(); let nc = mock_network_context(1); diff --git a/sync/src/tests/types.rs b/sync/src/tests/types.rs index 83d23cc69e..e41c0827d1 100644 --- a/sync/src/tests/types.rs +++ b/sync/src/tests/types.rs @@ -2,6 +2,7 @@ use ckb_shared::types::HeaderIndexView; use ckb_types::{ core::{BlockNumber, EpochNumberWithFraction, HeaderBuilder}, packed::Byte32, + prelude::*, U256, }; use rand::{thread_rng, Rng}; @@ -24,14 +25,9 @@ fn test_get_ancestor_use_skip_list() { let mut parent_hash = None; for number in 0..SKIPLIST_LENGTH { - let mut header_builder = - HeaderBuilder::default() - .number(number) - .epoch(EpochNumberWithFraction::new( - number / 1000, - number % 1000, - 1000, - )); + let mut header_builder = HeaderBuilder::default() + .number(number.pack()) + .epoch(EpochNumberWithFraction::new(number / 1000, number % 1000, 1000).pack()); if let Some(parent_hash) = parent_hash.take() { header_builder = header_builder.parent_hash(parent_hash); } diff --git a/sync/src/tests/util.rs b/sync/src/tests/util.rs index 4a314a3832..8f37b7e7bf 100644 --- a/sync/src/tests/util.rs +++ b/sync/src/tests/util.rs @@ -71,14 +71,14 @@ pub fn inherit_block(shared: &Shared, parent_hash: &Byte32) -> BlockBuilder { .chain_root_mmr(parent_number) .get_root() .expect("chain root_mmr"); - let bytes = chain_root.calc_mmr_hash().as_bytes().into(); + let bytes = chain_root.calc_mmr_hash().as_bytes().pack(); BlockBuilder::default() .parent_hash(parent_hash.to_owned()) - .number(parent.header().number() + 1) - .timestamp(parent.header().timestamp() + 1) - .epoch(epoch.number_with_fraction(parent_number + 1)) - .compact_target(epoch.compact_target()) + .number((parent.header().number() + 1).pack()) + .timestamp((parent.header().timestamp() + 1).pack()) + .epoch(epoch.number_with_fraction(parent_number + 1).pack()) + .compact_target(epoch.compact_target().pack()) .dao(dao) .transaction(cellbase) .extension(Some(bytes)) diff --git a/sync/src/types/mod.rs b/sync/src/types/mod.rs index 873882efc9..476a5c308b 100644 --- a/sync/src/types/mod.rs +++ b/sync/src/types/mod.rs @@ -1946,7 +1946,7 @@ impl ActiveChain { ); let locator_hash = self.get_locator(block_number_and_hash); let content = packed::GetHeaders::new_builder() - .block_locator_hashes(locator_hash) + .block_locator_hashes(locator_hash.pack()) .hash_stop(packed::Byte32::zero()) .build(); let message = packed::SyncMessage::new_builder().set(content).build(); diff --git a/test/src/assertion/reward_assertion.rs b/test/src/assertion/reward_assertion.rs index 6825700c5a..229bf9bd3f 100644 --- a/test/src/assertion/reward_assertion.rs +++ b/test/src/assertion/reward_assertion.rs @@ -1,6 +1,7 @@ use crate::Node; use ckb_types::core::{BlockEconomicState, BlockView, Capacity, Ratio, TransactionView}; use ckb_types::packed::{Byte32, OutPoint, ProposalShortId}; +use ckb_types::prelude::*; use std::collections::HashMap; pub fn check_fee(node: &Node) { @@ -112,7 +113,7 @@ impl RewardChecker { fn apply_new_transaction(&mut self, tx: &TransactionView) { for (index, output) in tx.outputs().into_iter().enumerate() { let out_point = OutPoint::new(tx.hash(), index as u32); - let capacity: u64 = output.capacity().into(); + let capacity: u64 = output.capacity().unpack(); self.cells_capacity.insert(out_point, capacity); } diff --git a/test/src/node.rs b/test/src/node.rs index 1931666e95..ad25d7fe89 100644 --- a/test/src/node.rs +++ b/test/src/node.rs @@ -19,9 +19,7 @@ use ckb_types::{ self, capacity_bytes, BlockBuilder, BlockNumber, BlockView, Capacity, HeaderView, ScriptHashType, TransactionView, }, - packed::{ - self, Block, Byte32, CellDep, CellInput, CellOutput, CellOutputBuilder, OutPoint, Script, - }, + packed::{Block, Byte32, CellDep, CellInput, CellOutput, CellOutputBuilder, OutPoint, Script}, prelude::*, }; use std::borrow::{Borrow, BorrowMut}; @@ -239,7 +237,7 @@ impl Node { let always_success_code_hash = CellOutput::calc_data_hash(&always_success_raw); Script::new_builder() .code_hash(always_success_code_hash) - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build() } @@ -265,7 +263,7 @@ impl Node { let always_failure_code_hash = CellOutput::calc_data_hash(&always_failure_raw); Script::new_builder() .code_hash(always_failure_code_hash) - .hash_type(ScriptHashType::Data) + .hash_type(ScriptHashType::Data.into()) .build() } @@ -368,7 +366,10 @@ impl Node { // the new block in main fork which timestamp is greater than // or equal to the current time. let timestamp = block.timestamp(); - let uncle = block.as_advanced_builder().timestamp(timestamp + 1).build(); + let uncle = block + .as_advanced_builder() + .timestamp((timestamp - 1).pack()) + .build(); (block, uncle) } @@ -403,7 +404,7 @@ impl Node { let res = self .rpc_client() .send_transaction_result(transaction.data().into())? - .into(); + .pack(); Ok(res) } @@ -595,11 +596,11 @@ impl Node { .cell_dep(always_success_cell_dep) .output( CellOutputBuilder::default() - .capacity(capacity) + .capacity(capacity.pack()) .lock(always_success_script) .build(), ) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .input(CellInput::new(OutPoint::new(hash, index), since)) .build() } @@ -621,11 +622,11 @@ impl Node { .cell_dep(always_failure_cell_dep) .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(always_failure_script) .build(), ) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .input(CellInput::new(OutPoint::new(hash, 0), 0)) .build() } diff --git a/test/src/rpc.rs b/test/src/rpc.rs index e1634141f4..bb4b9a81dc 100644 --- a/test/src/rpc.rs +++ b/test/src/rpc.rs @@ -15,7 +15,7 @@ use ckb_types::core::{ BlockNumber as CoreBlockNumber, Capacity as CoreCapacity, EpochNumber as CoreEpochNumber, Version as CoreVersion, }; -use ckb_types::{packed::Byte32, H256}; +use ckb_types::{packed::Byte32, prelude::*, H256}; use lazy_static::lazy_static; lazy_static! { @@ -42,13 +42,13 @@ impl RpcClient { pub fn get_block(&self, hash: Byte32) -> Option { self.inner - .get_block(hash.into()) + .get_block(hash.unpack()) .expect("rpc call get_block") } pub fn get_fork_block(&self, hash: Byte32) -> Option { self.inner - .get_fork_block(hash.into()) + .get_fork_block(hash.unpack()) .expect("rpc call get_fork_block") } @@ -60,7 +60,7 @@ impl RpcClient { pub fn get_header(&self, hash: Byte32) -> Option { self.inner - .get_header(hash.into()) + .get_header(hash.unpack()) .expect("rpc call get_header") } @@ -72,7 +72,7 @@ impl RpcClient { pub fn get_block_filter(&self, hash: Byte32) -> Option { self.inner - .get_block_filter(hash.into()) + .get_block_filter(hash.unpack()) .expect("rpc call get_block_filter") } @@ -86,13 +86,13 @@ impl RpcClient { verbosity: u32, ) -> TransactionWithStatusResponse { self.inner - .get_transaction(hash.into(), Some(verbosity.into()), None) + .get_transaction(hash.unpack(), Some(verbosity.into()), None) .expect("rpc call get_transaction") } pub fn get_pool_tx_detail_info(&self, hash: Byte32) -> PoolTxDetailInfo { self.inner - .get_pool_tx_detail_info(hash.into()) + .get_pool_tx_detail_info(hash.unpack()) .expect("rpc call get_transaction_tx_pool_details") } @@ -100,7 +100,7 @@ impl RpcClient { self.inner .get_block_hash(number.into()) .expect("rpc call get_block_hash") - .map(|x| x.into()) + .map(|x| x.pack()) } pub fn get_tip_header(&self) -> HeaderView { @@ -209,7 +209,7 @@ impl RpcClient { } pub fn submit_block(&self, work_id: String, block: Block) -> Result { - self.inner.submit_block(work_id, block).map(|x| x.into()) + self.inner.submit_block(work_id, block).map(|x| x.pack()) } pub fn get_blockchain_info(&self) -> ChainInfo { @@ -220,14 +220,14 @@ impl RpcClient { pub fn get_block_median_time(&self, block_hash: Byte32) -> Option { self.inner - .get_block_median_time(block_hash.into()) + .get_block_median_time(block_hash.unpack()) .expect("rpc call get_block_median_time") } pub fn send_transaction(&self, tx: Transaction) -> Byte32 { self.send_transaction_result(tx) .expect("rpc call send_transaction") - .into() + .pack() } pub fn send_transaction_result(&self, tx: Transaction) -> Result { @@ -237,7 +237,7 @@ impl RpcClient { pub fn remove_transaction(&self, tx_hash: Byte32) -> bool { self.inner - .remove_transaction(tx_hash.into()) + .remove_transaction(tx_hash.unpack()) .expect("rpc call remove_transaction") } @@ -277,12 +277,12 @@ impl RpcClient { self.inner .process_block_without_verify(block, broadcast) .expect("rpc call process_block_without verify") - .map(|x| x.into()) + .map(|x| x.pack()) } pub fn truncate(&self, target_tip_hash: Byte32) { self.inner() - .truncate(target_tip_hash.into()) + .truncate(target_tip_hash.unpack()) .expect("rpc call truncate") } @@ -290,14 +290,14 @@ impl RpcClient { self.inner() .generate_block() .expect("rpc call generate_block") - .into() + .pack() } pub fn generate_block_with_template(&self, block_template: BlockTemplate) -> Byte32 { self.inner() .generate_block_with_template(block_template) .expect("rpc call generate_block_with_template") - .into() + .pack() } pub fn calculate_dao_maximum_withdraw( @@ -306,14 +306,14 @@ impl RpcClient { hash: Byte32, ) -> CoreCapacity { self.inner() - .calculate_dao_maximum_withdraw(out_point, hash.into()) + .calculate_dao_maximum_withdraw(out_point, hash.unpack()) .expect("rpc call calculate_dao_maximum_withdraw") .into() } pub fn get_block_economic_state(&self, hash: Byte32) -> Option { self.inner() - .get_block_economic_state(hash.into()) + .get_block_economic_state(hash.unpack()) .expect("rpc call get_block_economic_state") } @@ -321,7 +321,7 @@ impl RpcClient { self.inner() .notify_transaction(tx) .expect("rpc call send_transaction") - .into() + .pack() } pub fn tx_pool_ready(&self) -> bool { diff --git a/test/src/specs/alert/alert_propagation.rs b/test/src/specs/alert/alert_propagation.rs index 3af797ecd1..d5e8164753 100644 --- a/test/src/specs/alert/alert_propagation.rs +++ b/test/src/specs/alert/alert_propagation.rs @@ -44,9 +44,9 @@ impl Spec for AlertPropagation { let id1: u32 = 42; let warning1: Bytes = b"pretend we are in dangerous status".to_vec().into(); let raw_alert = RawAlert::new_builder() - .id(id1) - .message(&warning1) - .notice_until(notice_until) + .id(id1.pack()) + .message(warning1.pack()) + .notice_until(notice_until.pack()) .build(); let alert = create_alert(raw_alert, &self.privkeys); node0.rpc_client().send_alert(alert.clone().into()); @@ -74,10 +74,10 @@ impl Spec for AlertPropagation { let id2: u32 = 43; let warning2: Bytes = b"alert is canceled".to_vec().into(); let raw_alert2 = RawAlert::new_builder() - .id(id2) - .cancel(id1) - .message(&warning2) - .notice_until(notice_until) + .id(id2.pack()) + .cancel(id1.pack()) + .message(warning2.pack()) + .notice_until(notice_until.pack()) .build(); let alert2 = create_alert(raw_alert2, &self.privkeys); node0.rpc_client().send_alert(alert2.into()); @@ -141,7 +141,7 @@ impl Spec for AlertPropagation { } fn create_alert(raw_alert: RawAlert, privkeys: &[Privkey]) -> Alert { - let msg: Message = raw_alert.calc_alert_hash().into(); + let msg: Message = raw_alert.calc_alert_hash().unpack(); let signatures = privkeys .iter() .take(2) @@ -151,11 +151,11 @@ fn create_alert(raw_alert: RawAlert, privkeys: &[Privkey]) -> Alert { .expect("Sign failed") .serialize() .into(); - data.into() + data.pack() }) .collect::>(); Alert::new_builder() .raw(raw_alert) - .signatures(signatures) + .signatures(signatures.pack()) .build() } diff --git a/test/src/specs/consensus/insufficient_reward.rs b/test/src/specs/consensus/insufficient_reward.rs index 831759eccd..45d1e6bf3d 100644 --- a/test/src/specs/consensus/insufficient_reward.rs +++ b/test/src/specs/consensus/insufficient_reward.rs @@ -2,7 +2,6 @@ use crate::global::VENDOR_PATH; use crate::specs::spec_name; use crate::{Node, Spec}; -use ckb_types::packed::Script; use ckb_types::{ core::{capacity_bytes, Capacity}, packed::CellOutput, @@ -47,8 +46,8 @@ impl Spec for InsufficientReward { // build a block with insufficient reward let output = CellOutput::new_builder() - .capacity(capacity_bytes!(1)) - .lock(Script::default()) + .capacity(capacity_bytes!(1).pack()) + .lock(Default::default()) .build(); let cellbase = new_block_builder.clone().build().transactions()[0] .as_advanced_builder() diff --git a/test/src/specs/dao/dao_tx.rs b/test/src/specs/dao/dao_tx.rs index af9f4f8db5..64eec88332 100644 --- a/test/src/specs/dao/dao_tx.rs +++ b/test/src/specs/dao/dao_tx.rs @@ -27,7 +27,7 @@ impl Spec for WithdrawDAO { let withdrawal = user.withdraw(); let since = EpochNumberWithFraction::from_full_value( - withdrawal.inputs().get(0).unwrap().since().into(), + withdrawal.inputs().get(0).unwrap().since().unpack(), ); goto_target_point(node, since); ensure_committed(node, &withdrawal); @@ -59,9 +59,12 @@ impl Spec for WithdrawDAOWithOverflowCapacity { .outputs() .into_iter() .map(|cell_output| { - let old_capacity: Capacity = cell_output.capacity().into(); + let old_capacity: Capacity = cell_output.capacity().unpack(); let new_capacity = old_capacity.safe_add(Capacity::one()).unwrap(); - cell_output.as_builder().capacity(new_capacity).build() + cell_output + .as_builder() + .capacity(new_capacity.pack()) + .build() }) .collect(); withdrawal @@ -70,7 +73,7 @@ impl Spec for WithdrawDAOWithOverflowCapacity { .build() }; let since = EpochNumberWithFraction::from_full_value( - withdrawal.inputs().get(0).unwrap().since().into(), + withdrawal.inputs().get(0).unwrap().since().unpack(), ); goto_target_point(node, since); assert_send_transaction_fail(node, &invalid_withdrawal, "Overflow"); diff --git a/test/src/specs/dao/dao_user.rs b/test/src/specs/dao/dao_user.rs index b54fd1c7d9..aa729e8476 100644 --- a/test/src/specs/dao/dao_user.rs +++ b/test/src/specs/dao/dao_user.rs @@ -2,7 +2,7 @@ use crate::utils::since_from_absolute_epoch_number; use crate::{Node, TXOSet, TXO}; use ckb_chain_spec::OUTPUT_INDEX_DAO; use ckb_types::core::{EpochNumberWithFraction, HeaderView}; -use ckb_types::packed::{self, WitnessArgs}; +use ckb_types::packed::WitnessArgs; use ckb_types::{ bytes::Bytes, core::{ScriptHashType, TransactionBuilder, TransactionView}, @@ -41,7 +41,7 @@ impl<'a> DAOUser<'a> { .iter() .map(|txo| CellInput::new(txo.out_point(), 0)) .collect::>(); - let output_data: packed::Bytes = Bytes::from(&[0u8; 8][..]).into(); + let output_data = Bytes::from(&[0u8; 8][..]).pack(); let outputs = { // TRICK: When we change the always_outputs to deposit_outputs, the always_output's // capacity will be insufficient. So here uses part of always_outputs' capacity @@ -51,9 +51,9 @@ impl<'a> DAOUser<'a> { (0..outputs_len) .map(|_| { CellOutput::new_builder() - .capacity(capacity) + .capacity(capacity.pack()) .lock(node.always_success_script()) - .type_(Some(self.dao_type_script())) + .type_(Some(self.dao_type_script()).pack()) .build() }) .collect::>() @@ -68,7 +68,7 @@ impl<'a> DAOUser<'a> { .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data) - .witness(packed::Bytes::default()) + .witness(Default::default()) .build(); self.deposit_utxo = TXOSet::from(&tx); tx @@ -83,14 +83,14 @@ impl<'a> DAOUser<'a> { .map(|(txo, _)| CellInput::new(txo.out_point(), 0)); let outputs = deposit_utxo_headers.iter().map(|(txo, _)| { CellOutput::new_builder() - .capacity(txo.capacity()) + .capacity(txo.capacity().pack()) .lock(txo.lock()) .type_(txo.type_()) .build() }); let outputs_data = deposit_utxo_headers.iter().map(|(_, header)| { let deposit_number = header.number(); - Bytes::from(deposit_number.to_le_bytes().to_vec()).into() + Bytes::from(deposit_number.to_le_bytes().to_vec()).pack() }); let cell_deps = vec![node.always_success_cell_dep(), self.dao_cell_dep()]; // NOTE: dao.c uses `deposit_header` to ensure the prepare_output.capacity == deposit_output.capacity @@ -108,10 +108,10 @@ impl<'a> DAOUser<'a> { .position(|hash| hash == &header.hash()) .unwrap() as u64; WitnessArgs::new_builder() - .input_type(Some(Bytes::from(index.to_le_bytes().to_vec()))) + .input_type(Some(Bytes::from(index.to_le_bytes().to_vec())).pack()) .build() .as_bytes() - .into() + .pack() }) .collect::>(); let tx = TransactionBuilder::default() @@ -148,7 +148,7 @@ impl<'a> DAOUser<'a> { }) .sum::(); let output = CellOutput::new_builder() - .capacity(output_capacity) + .capacity(output_capacity.pack()) .lock(node.always_success_script()) .build(); let cell_deps = vec![node.always_success_cell_dep(), self.dao_cell_dep()]; @@ -167,10 +167,10 @@ impl<'a> DAOUser<'a> { .position(|hash| hash == &header.hash()) .unwrap() as u64; WitnessArgs::new_builder() - .input_type(Some(Bytes::from(index.to_le_bytes().to_vec()))) + .input_type(Some(Bytes::from(index.to_le_bytes().to_vec())).pack()) .build() .as_bytes() - .into() + .pack() }) .collect::>(); let tx = TransactionBuilder::default() @@ -179,7 +179,7 @@ impl<'a> DAOUser<'a> { .cell_deps(cell_deps) .header_deps(header_deps) .witnesses(witnesses) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.withdraw_utxo = TXOSet::from(&tx); tx @@ -188,7 +188,7 @@ impl<'a> DAOUser<'a> { pub fn dao_type_script(&self) -> Script { Script::new_builder() .code_hash(self.node.consensus().dao_type_hash()) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .build() } @@ -220,7 +220,7 @@ impl<'a> DAOUser<'a> { let header = self .node .rpc_client() - .get_header(block_hash.into()) + .get_header(block_hash.pack()) .expect("get utxo transaction block header") .into(); (txo, header) @@ -240,7 +240,7 @@ impl<'a> DAOUser<'a> { .expect("get deposit transaction block hash"); let deposit_header = node .rpc_client() - .get_header(deposit_hash.into()) + .get_header(deposit_hash.pack()) .expect("get deposit transaction block header"); EpochNumberWithFraction::from_full_value(deposit_header.inner.epoch.value()) }; diff --git a/test/src/specs/dao/dao_verifier.rs b/test/src/specs/dao/dao_verifier.rs index 989a321180..b2b1fab86a 100644 --- a/test/src/specs/dao/dao_verifier.rs +++ b/test/src/specs/dao/dao_verifier.rs @@ -5,6 +5,7 @@ use ckb_dao_utils::extract_dao_data; use ckb_jsonrpc_types::EpochView; use ckb_types::core::{BlockEconomicState, BlockNumber, BlockView, Capacity, TransactionView}; use ckb_types::packed::{Byte32, CellOutput, OutPoint}; +use ckb_types::prelude::Unpack; use ckb_util::Mutex; use std::collections::HashMap; @@ -147,7 +148,7 @@ impl DAOVerifier { && tx_index == 0 && output.lock().args().raw_data() == satoshi_pubkey_hash.0[..] { - sum += Into::::into(&output.capacity()) + sum += Unpack::::unpack(&output.capacity()) .safe_mul_ratio(satoshi_cell_occupied_ratio) .unwrap() .as_u64(); @@ -218,7 +219,7 @@ impl DAOVerifier { let prepare_tx = self.get_transaction(&o.tx_hash()); let deposit_out_point = prepare_tx .inputs() - .get(o.index().into()) + .get(o.index().unpack()) .unwrap() .previous_output(); let deposit_header_number = @@ -245,7 +246,7 @@ impl DAOVerifier { let input_tx = self.get_transaction(&out_point.tx_hash()); let input_data = input_tx .outputs_data() - .get(out_point.index().into()) + .get(out_point.index().unpack()) .unwrap(); if input_data.len() != 8 { return false; @@ -332,12 +333,12 @@ impl DAOVerifier { fn get_output(&self, out_point: &OutPoint) -> CellOutput { self.get_transaction(&out_point.tx_hash()) - .output(out_point.index().into()) + .output(out_point.index().unpack()) .expect("exist") } fn get_output_capacity(&self, out_point: &OutPoint) -> u64 { - self.get_output(out_point).capacity().into() + self.get_output(out_point).capacity().unpack() } fn get_output_occupied_capacity(&self, out_point: &OutPoint) -> u64 { @@ -345,12 +346,12 @@ impl DAOVerifier { let satoshi_cell_occupied_ratio = self.consensus.satoshi_cell_occupied_ratio; let (output, data) = self .get_transaction(&out_point.tx_hash()) - .output_with_data(out_point.index().into()) + .output_with_data(out_point.index().unpack()) .expect("exist"); - if Into::::into(&out_point.index()) == 0 + if Unpack::::unpack(&out_point.index()) == 0 && output.lock().args().raw_data() == satoshi_pubkey_hash.0[..] { - Into::::into(&output.capacity()) + Unpack::::unpack(&output.capacity()) .safe_mul_ratio(satoshi_cell_occupied_ratio) .unwrap() .as_u64() diff --git a/test/src/specs/dao/satoshi_dao_occupied.rs b/test/src/specs/dao/satoshi_dao_occupied.rs index 74ae15a3cc..5756d25ceb 100644 --- a/test/src/specs/dao/satoshi_dao_occupied.rs +++ b/test/src/specs/dao/satoshi_dao_occupied.rs @@ -35,7 +35,7 @@ impl Spec for DAOWithSatoshiCellOccupied { let withdrawal = user.withdraw(); let since = EpochNumberWithFraction::from_full_value( - withdrawal.inputs().get(0).unwrap().since().into(), + withdrawal.inputs().get(0).unwrap().since().unpack(), ); goto_target_point(node, since); ensure_committed(node, &withdrawal); @@ -95,7 +95,7 @@ impl Spec for SpendSatoshiCell { 0, ); let output = CellOutput::new_builder() - .capacity(satoshi_cell_occupied) + .capacity(satoshi_cell_occupied.pack()) .lock(always_success_cell().2.clone()) .build(); @@ -103,17 +103,20 @@ impl Spec for SpendSatoshiCell { .cell_deps(vec![node0.always_success_cell_dep()]) .input(satoshi_input) .output(output) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let tx_hash = transaction.hash(); let sig = self .privkey - .sign_recoverable(&(&tx_hash).into()) + .sign_recoverable(&tx_hash.unpack()) .expect("sign"); let mut witness_vec = sig.serialize(); witness_vec.extend_from_slice(&self.pubkey.serialize()); let witness = Bytes::from(witness_vec); - let transaction = transaction.as_advanced_builder().witness(witness).build(); + let transaction = transaction + .as_advanced_builder() + .witness(witness.pack()) + .build(); node0.mine(1); node0 @@ -149,7 +152,7 @@ fn issue_satoshi_cell() -> IssuedCell { .2 .clone() .as_builder() - .args(Bytes::from(&SATOSHI_PUBKEY_HASH.0[..])) + .args(Bytes::from(&SATOSHI_PUBKEY_HASH.0[..]).pack()) .build(); IssuedCell { capacity: SATOSHI_CELL_CAPACITY, diff --git a/test/src/specs/hardfork/v2021/cell_deps.rs b/test/src/specs/hardfork/v2021/cell_deps.rs index c6f66e9f71..929a2e2f54 100644 --- a/test/src/specs/hardfork/v2021/cell_deps.rs +++ b/test/src/specs/hardfork/v2021/cell_deps.rs @@ -169,12 +169,12 @@ impl NewScript { let original_data = node.always_success_raw_data(); let data = packed::Bytes::new_builder() .extend(original_data.as_ref().iter().map(|x| (*x).into())) - .push(id) + .push(id.into()) .build(); let tx = Self::deploy(node, &data, inputs, type_script_opt); let cell_dep = packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(core::DepType::Code) + .dep_type(core::DepType::Code.into()) .build(); let data_hash = packed::CellOutput::calc_data_hash(&data.raw_data()); let type_hash = tx @@ -219,7 +219,7 @@ impl NewScript { }; let cell_input = inputs.next().unwrap(); let cell_output = packed::CellOutput::new_builder() - .type_(Some(type_script)) + .type_(Some(type_script).pack()) .build_exact_capacity(core::Capacity::bytes(data.len()).unwrap()) .unwrap(); let tx = tx_template @@ -249,14 +249,14 @@ impl NewScript { }; packed::Script::new_builder() .code_hash(self.data_hash.clone()) - .hash_type(hash_type) + .hash_type(hash_type.into()) .build() } fn as_type_script(&self) -> packed::Script { packed::Script::new_builder() .code_hash(self.type_hash.clone()) - .hash_type(core::ScriptHashType::Type) + .hash_type(core::ScriptHashType::Type.into()) .build() } } @@ -375,7 +375,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { fn wait_block_assembler_reset(&self, block_hash: Byte32) { self.node - .new_block_with_blocking(|template| template.parent_hash != (&block_hash).into()); + .new_block_with_blocking(|template| template.parent_hash != block_hash.unpack()); } } @@ -443,7 +443,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { type_script: &NewScript, ) -> TransactionView { let output = packed::CellOutput::new_builder() - .type_(Some(type_script.as_data_script(0))) + .type_(Some(type_script.as_data_script(0)).pack()) .build_exact_capacity(core::Capacity::bytes(data_script.data().len()).unwrap()) .unwrap(); let tx = TransactionView::new_advanced_builder() @@ -460,7 +460,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { fn convert_tx_to_code_cellep(tx: &TransactionView) -> packed::CellDep { packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(core::DepType::Code) + .dep_type(core::DepType::Code.into()) .build() } @@ -469,14 +469,13 @@ impl<'a> CheckCellDepsTestRunner<'a> { inputs: &mut impl Iterator, dep_txs: &[&TransactionView], ) -> packed::CellDep { - let dep_data: packed::Bytes = Into::::into( - dep_txs - .iter() - .map(|tx| packed::OutPoint::new(tx.hash(), 0)) - .collect::>(), - ) - .as_bytes() - .into(); + let dep_data = dep_txs + .iter() + .map(|tx| packed::OutPoint::new(tx.hash(), 0)) + .collect::>() + .pack() + .as_bytes() + .pack(); let dep_output = packed::CellOutput::new_builder() .build_exact_capacity(core::Capacity::bytes(dep_data.len()).unwrap()) .unwrap(); @@ -489,7 +488,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { Self::submit_transaction_until_committed_to(node, &tx); packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(core::DepType::DepGroup) + .dep_type(core::DepType::DepGroup.into()) .build() } } @@ -504,7 +503,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { fn get_previous_output(&self, cell_input: &packed::CellInput) -> rpc::CellOutput { let previous_output = cell_input.previous_output(); - let previous_output_index: usize = previous_output.index().into(); + let previous_output_index: usize = previous_output.index().unpack(); if let Either::Left(tx) = self .node .rpc_client() @@ -526,7 +525,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { let new_script = &self.deps.default_script; let input_cell = self.get_previous_output(&cell_input); let cell_output = packed::CellOutput::new_builder() - .capacity(input_cell.capacity.value()) + .capacity(input_cell.capacity.value().pack()) .lock(new_script.as_data_script(0)) .build(); let tx = TransactionView::new_advanced_builder() @@ -534,7 +533,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { .cell_dep(new_script.cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.create_initial_input(tx) } @@ -546,16 +545,16 @@ impl<'a> CheckCellDepsTestRunner<'a> { let new_script = &self.deps.default_script; let input_cell = self.get_previous_output(&cell_input); let cell_output = packed::CellOutput::new_builder() - .capacity(input_cell.capacity.value()) + .capacity(input_cell.capacity.value().pack()) .lock(self.node.always_success_script()) - .type_(Some(new_script.as_data_script(0))) + .type_(Some(new_script.as_data_script(0)).pack()) .build(); let tx = TransactionView::new_advanced_builder() .cell_dep(self.node.always_success_cell_dep()) .cell_dep(new_script.cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.create_initial_input(tx) } @@ -567,7 +566,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { let new_script = &self.deps.default_script; let input_cell = self.get_previous_output(&cell_input); let cell_output = packed::CellOutput::new_builder() - .capacity(input_cell.capacity.value()) + .capacity(input_cell.capacity.value().pack()) .lock(new_script.as_type_script()) .build(); let tx = TransactionView::new_advanced_builder() @@ -575,7 +574,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { .cell_dep(new_script.cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.create_initial_input(tx) } @@ -587,16 +586,16 @@ impl<'a> CheckCellDepsTestRunner<'a> { let new_script = &self.deps.default_script; let input_cell = self.get_previous_output(&cell_input); let cell_output = packed::CellOutput::new_builder() - .capacity(input_cell.capacity.value()) + .capacity(input_cell.capacity.value().pack()) .lock(self.node.always_success_script()) - .type_(Some(new_script.as_type_script())) + .type_(Some(new_script.as_type_script()).pack()) .build(); let tx = TransactionView::new_advanced_builder() .cell_dep(self.node.always_success_cell_dep()) .cell_dep(new_script.cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.create_initial_input(tx) } @@ -627,11 +626,11 @@ impl<'a> CheckCellDepsTestRunner<'a> { (HT::Data, ST::Lock) => cob.lock(new_script.as_data_script(0)), (HT::Data, ST::Type) => cob .lock(self.node.always_success_script()) - .type_(Some(new_script.as_data_script(0))), + .type_(Some(new_script.as_data_script(0)).pack()), (HT::Type, ST::Lock) => cob.lock(new_script.as_type_script()), (HT::Type, ST::Type) => cob .lock(self.node.always_success_script()) - .type_(Some(new_script.as_type_script())), + .type_(Some(new_script.as_type_script()).pack()), } } } @@ -700,7 +699,7 @@ impl<'a> CheckCellDepsTestRunner<'a> { } .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); self.adjust_tip_before_test(); if let Some(errmsg) = expected.error_message() { diff --git a/test/src/specs/hardfork/v2021/vm_b_extension.rs b/test/src/specs/hardfork/v2021/vm_b_extension.rs index 8c89d1d260..22882c4140 100644 --- a/test/src/specs/hardfork/v2021/vm_b_extension.rs +++ b/test/src/specs/hardfork/v2021/vm_b_extension.rs @@ -80,11 +80,11 @@ impl Spec for CheckVmBExtension { impl BExtScript { fn new(node: &Node, cell_input: packed::CellInput) -> Self { - let data: packed::Bytes = include_bytes!("../../../../../script/testdata/cpop_lock").into(); + let data: packed::Bytes = include_bytes!("../../../../../script/testdata/cpop_lock").pack(); let tx = Self::deploy(node, &data, cell_input); let cell_dep = packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .build(); let data_hash = packed::CellOutput::calc_data_hash(&data.raw_data()); let type_hash = tx @@ -105,7 +105,7 @@ impl BExtScript { let type_script = node.always_success_script(); let tx_template = TransactionView::new_advanced_builder(); let cell_output = packed::CellOutput::new_builder() - .type_(Some(type_script)) + .type_(Some(type_script).pack()) .build_exact_capacity(Capacity::bytes(data.len()).unwrap()) .unwrap(); let tx = tx_template @@ -131,7 +131,7 @@ impl BExtScript { }; packed::Script::new_builder() .code_hash(self.data_hash.clone()) - .hash_type(hash_type) + .hash_type(hash_type.into()) .args(args) .build() } @@ -139,7 +139,7 @@ impl BExtScript { fn as_type_script(&self, args: packed::Bytes) -> packed::Script { packed::Script::new_builder() .code_hash(self.type_hash.clone()) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .args(args) .build() } @@ -220,12 +220,12 @@ impl<'a> CheckVmBExtensionTestRunner<'a> { let mut vec = Vec::with_capacity(8 * 2); vec.extend_from_slice(&num0.to_le_bytes()); vec.extend_from_slice(&num1.to_le_bytes()); - vec.into() + vec.pack() }; let script = self.script.as_script(vm_opt, args); packed::CellOutput::new_builder() .lock(self.node.always_success_script()) - .type_(Some(script)) + .type_(Some(script).pack()) .build_exact_capacity(Capacity::shannons(0)) .unwrap() }; @@ -234,7 +234,7 @@ impl<'a> CheckVmBExtensionTestRunner<'a> { .cell_dep(self.script.cell_dep()) .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); if let Some(errmsg) = expected.error_message() { assert_send_transaction_fail(self.node, &tx, errmsg); diff --git a/test/src/specs/hardfork/v2021/vm_version1.rs b/test/src/specs/hardfork/v2021/vm_version1.rs index e4f935d168..f49d955275 100644 --- a/test/src/specs/hardfork/v2021/vm_version1.rs +++ b/test/src/specs/hardfork/v2021/vm_version1.rs @@ -96,12 +96,12 @@ impl NewScript { let original_data = node.always_success_raw_data(); let data = packed::Bytes::new_builder() .extend(original_data.as_ref().iter().map(|x| (*x).into())) - .push(id) + .push(id.into()) .build(); let tx = Self::deploy(node, &data, inputs); let cell_dep = packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .build(); let data_hash = packed::CellOutput::calc_data_hash(&data.raw_data()); let type_hash = tx @@ -127,7 +127,7 @@ impl NewScript { let tx_template = TransactionView::new_advanced_builder(); let cell_input = inputs.next().unwrap(); let cell_output = packed::CellOutput::new_builder() - .type_(Some(type_script)) + .type_(Some(type_script).pack()) .build_exact_capacity(Capacity::bytes(data.len()).unwrap()) .unwrap(); let tx = tx_template @@ -153,14 +153,14 @@ impl NewScript { }; packed::Script::new_builder() .code_hash(self.data_hash.clone()) - .hash_type(hash_type) + .hash_type(hash_type.into()) .build() } fn as_type_script(&self) -> packed::Script { packed::Script::new_builder() .code_hash(self.type_hash.clone()) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .build() } } @@ -218,7 +218,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { TransactionView::new_advanced_builder().cell_dep(cell_dep), packed::CellOutput::new_builder() .lock(self.node.always_success_script()) - .type_(Some(script)), + .type_(Some(script).pack()), ) } else { ( @@ -228,12 +228,14 @@ impl<'a> CheckVmVersionTestRunner<'a> { }; let cell_input = inputs.next().unwrap(); let input_cell = self.get_previous_output(&cell_input); - let cell_output = co_builder.capacity(input_cell.capacity.value() - 1).build(); + let cell_output = co_builder + .capacity((input_cell.capacity.value() - 1).pack()) + .build(); let tx = tx_builder .cell_dep(self.node.always_success_cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); if let Some(errmsg) = expected.error_message() { assert_send_transaction_fail(self.node, &tx, errmsg); @@ -264,7 +266,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { .cell_dep(cell_dep) .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); if let Some(errmsg) = expected.error_message() { assert_send_transaction_fail(self.node, &tx, errmsg); @@ -275,7 +277,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { fn get_previous_output(&self, cell_input: &packed::CellInput) -> rpc::CellOutput { let previous_output = cell_input.previous_output(); - let previous_output_index: usize = previous_output.index().into(); + let previous_output_index: usize = previous_output.index().unpack(); if let Either::Left(tx) = self .node .rpc_client() diff --git a/test/src/specs/hardfork/v2023/vm_version2.rs b/test/src/specs/hardfork/v2023/vm_version2.rs index aa727f6e89..972fb74f9e 100644 --- a/test/src/specs/hardfork/v2023/vm_version2.rs +++ b/test/src/specs/hardfork/v2023/vm_version2.rs @@ -116,12 +116,12 @@ impl NewScript { let original_data = node.always_success_raw_data(); let data = packed::Bytes::new_builder() .extend(original_data.as_ref().iter().map(|x| (*x).into())) - .push(id) + .push(id.into()) .build(); let tx = Self::deploy(node, &data, inputs); let cell_dep = packed::CellDep::new_builder() .out_point(packed::OutPoint::new(tx.hash(), 0)) - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .build(); let data_hash = packed::CellOutput::calc_data_hash(&data.raw_data()); let type_hash = tx @@ -147,7 +147,7 @@ impl NewScript { let tx_template = TransactionView::new_advanced_builder(); let cell_input = inputs.next().unwrap(); let cell_output = packed::CellOutput::new_builder() - .type_(Some(type_script)) + .type_(Some(type_script).pack()) .build_exact_capacity(Capacity::bytes(data.len()).unwrap()) .unwrap(); let tx = tx_template @@ -174,14 +174,14 @@ impl NewScript { }; packed::Script::new_builder() .code_hash(self.data_hash.clone()) - .hash_type(hash_type) + .hash_type(hash_type.into()) .build() } fn as_type_script(&self) -> packed::Script { packed::Script::new_builder() .code_hash(self.type_hash.clone()) - .hash_type(ScriptHashType::Type) + .hash_type(ScriptHashType::Type.into()) .build() } } @@ -239,7 +239,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { TransactionView::new_advanced_builder().cell_dep(cell_dep), packed::CellOutput::new_builder() .lock(self.node.always_success_script()) - .type_(Some(script)), + .type_(Some(script).pack()), ) } else { ( @@ -249,12 +249,14 @@ impl<'a> CheckVmVersionTestRunner<'a> { }; let cell_input = inputs.next().unwrap(); let input_cell = self.get_previous_output(&cell_input); - let cell_output = co_builder.capacity(input_cell.capacity.value() - 1).build(); + let cell_output = co_builder + .capacity((input_cell.capacity.value() - 1).pack()) + .build(); let tx = tx_builder .cell_dep(self.node.always_success_cell_dep()) .input(cell_input) .output(cell_output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); if let Some(errmsg) = expected.error_message() { assert_send_transaction_fail(self.node, &tx, errmsg); @@ -285,7 +287,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { .cell_dep(cell_dep) .input(input) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); if let Some(errmsg) = expected.error_message() { assert_send_transaction_fail(self.node, &tx, errmsg); @@ -296,7 +298,7 @@ impl<'a> CheckVmVersionTestRunner<'a> { fn get_previous_output(&self, cell_input: &packed::CellInput) -> rpc::CellOutput { let previous_output = cell_input.previous_output(); - let previous_output_index: usize = previous_output.index().into(); + let previous_output_index: usize = previous_output.index().unpack(); if let Either::Left(tx) = self .node diff --git a/test/src/specs/mining/basic.rs b/test/src/specs/mining/basic.rs index 930fe933fa..c08357e5b5 100644 --- a/test/src/specs/mining/basic.rs +++ b/test/src/specs/mining/basic.rs @@ -3,6 +3,7 @@ use crate::util::cell::gen_spendable; use crate::util::transaction::always_success_transaction; use crate::{Node, Spec}; use ckb_jsonrpc_types::BlockTemplate; +use ckb_types::prelude::*; pub struct MiningBasic; @@ -49,7 +50,7 @@ impl Spec for BlockTemplates { block1 .header() .as_advanced_builder() - .timestamp(block1.header().timestamp() + 1) + .timestamp((block1.header().timestamp() + 1).pack()) .build(), ) .build(); @@ -60,13 +61,13 @@ impl Spec for BlockTemplates { node.submit_block(&block2); assert_eq!( block1.hash(), - rpc_client.get_tip_header().hash.into(), + rpc_client.get_tip_header().hash.pack(), "Block1 should be the tip block according first-received policy" ); let template1 = rpc_client.get_block_template(None, None, None); assert_eq!( block1.hash(), - (&template1.parent_hash).into(), + template1.parent_hash.pack(), "Block1 should be block template's parent block since it's tip block" ); diff --git a/test/src/specs/mining/bootstrap.rs b/test/src/specs/mining/bootstrap.rs index d5ae37b989..0bf13bbfcd 100644 --- a/test/src/specs/mining/bootstrap.rs +++ b/test/src/specs/mining/bootstrap.rs @@ -20,9 +20,9 @@ impl Spec for BootstrapCellbase { node.mine(DEFAULT_TX_PROPOSAL_WINDOW.1 + 1); let miner = packed::Script::new_builder() - .args(Bytes::from(vec![2, 1])) - .code_hash(h256!("0xa2")) - .hash_type(ScriptHashType::Data) + .args(Bytes::from(vec![2, 1]).pack()) + .code_hash(h256!("0xa2").pack()) + .hash_type(ScriptHashType::Data.into()) .build(); let is_bootstrap_cellbase = |number| { diff --git a/test/src/specs/mining/fee.rs b/test/src/specs/mining/fee.rs index c7bd9be438..abadc4daf8 100644 --- a/test/src/specs/mining/fee.rs +++ b/test/src/specs/mining/fee.rs @@ -5,10 +5,14 @@ use crate::util::check::is_transaction_committed; use crate::util::transaction::always_success_transaction; use crate::{Node, Spec}; use crate::{DEFAULT_TX_PROPOSAL_WINDOW, FINALIZATION_DELAY_LENGTH}; +use ckb_types::core::TransactionBuilder; +use ckb_types::packed::CellInput; +use ckb_types::packed::CellOutput; +use ckb_types::packed::OutPoint; +use ckb_types::prelude::*; use ckb_types::{ - core::{capacity_bytes, Capacity, TransactionBuilder}, - packed::{self, CellInput, CellOutput, CellOutputBuilder, OutPoint}, - prelude::*, + core::{capacity_bytes, Capacity}, + packed::CellOutputBuilder, }; use rand::{thread_rng, Rng}; @@ -75,14 +79,14 @@ impl Spec for FeeOfMaxBlockProposalsLimit { let maximal_capacity = cell.capacity().as_u64(); let random_capacity = rng.gen_range(minimal_capacity..=maximal_capacity); let output = CellOutput::new_builder() - .capacity(random_capacity) + .capacity(random_capacity.pack()) .lock(cell.cell_output.lock()) .type_(cell.cell_output.type_()) .build(); TransactionBuilder::default() .input(as_input(&cell)) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(node.always_success_cell_dep()) .build() }) @@ -131,14 +135,14 @@ impl Spec for FeeOfMultipleMaxBlockProposalsLimit { let maximal_capacity = cell.capacity().as_u64(); let random_capacity = rng.gen_range(minimal_capacity..=maximal_capacity); let output = CellOutput::new_builder() - .capacity(random_capacity) + .capacity(random_capacity.pack()) .lock(cell.cell_output.lock()) .type_(cell.cell_output.type_()) .build(); TransactionBuilder::default() .input(as_input(&cell)) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(node.always_success_cell_dep()) .build() }) @@ -221,7 +225,7 @@ impl Spec for ProposeDuplicated { let uncle = node .new_block_builder(None, None, None) .proposal(tx.proposal_short_id()) - .nonce(99999) + .nonce(99999.pack()) .build() .as_uncle(); node.mine(1); @@ -252,7 +256,7 @@ impl Spec for MalformedTx { let tx0 = node0.new_transaction_spend_tip_cellbase(); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .build(); let child = tx0 diff --git a/test/src/specs/mining/proposal.rs b/test/src/specs/mining/proposal.rs index eb4abe8a2c..272252671c 100644 --- a/test/src/specs/mining/proposal.rs +++ b/test/src/specs/mining/proposal.rs @@ -2,6 +2,7 @@ use crate::generic::GetProposalTxIds; use crate::util::cell::gen_spendable; use crate::util::transaction::always_success_transaction; use crate::{Node, Spec}; +use ckb_types::prelude::*; pub struct AvoidDuplicatedProposalsWithUncles; @@ -20,7 +21,7 @@ impl Spec for AvoidDuplicatedProposalsWithUncles { let block = node.new_block(None, None, None); let uncle = block .as_advanced_builder() - .timestamp(block.timestamp() + 1) + .timestamp((block.timestamp() + 1).pack()) .set_proposals(vec![tx.proposal_short_id()]) .build(); node.submit_block(&block); diff --git a/test/src/specs/mining/uncle.rs b/test/src/specs/mining/uncle.rs index 6d51311d08..04d044421f 100644 --- a/test/src/specs/mining/uncle.rs +++ b/test/src/specs/mining/uncle.rs @@ -1,5 +1,6 @@ use crate::{Node, Spec}; use ckb_types::core::{BlockView, EpochNumberWithFraction}; +use ckb_types::prelude::*; // Convention: // main-block: a block on the main fork @@ -85,16 +86,19 @@ impl Spec for UncleInheritFromForkUncle { let uncle_child = uncle_parent .as_advanced_builder() - .number(uncle_parent.number() + 1) + .number((uncle_parent.number() + 1).pack()) .parent_hash(uncle_parent.hash()) - .timestamp(uncle_parent.timestamp() + 1) - .epoch({ - let parent_epoch = uncle_parent.epoch(); - let epoch_number = parent_epoch.number(); - let epoch_index = parent_epoch.index(); - let epoch_length = parent_epoch.length(); - EpochNumberWithFraction::new(epoch_number, epoch_index + 1, epoch_length) - }) + .timestamp((uncle_parent.timestamp() + 1).pack()) + .epoch( + { + let parent_epoch = uncle_parent.epoch(); + let epoch_number = parent_epoch.number(); + let epoch_index = parent_epoch.index(); + let epoch_length = parent_epoch.length(); + EpochNumberWithFraction::new(epoch_number, epoch_index + 1, epoch_length) + } + .pack(), + ) .build(); let longer_fork = (0..=target_node.get_tip_block_number()).map(|_| { diff --git a/test/src/specs/relay/block_relay.rs b/test/src/specs/relay/block_relay.rs index a3d054b98e..22569ce61e 100644 --- a/test/src/specs/relay/block_relay.rs +++ b/test/src/specs/relay/block_relay.rs @@ -3,6 +3,7 @@ use crate::util::mining::out_ibd_mode; use crate::utils::{now_ms, sleep, wait_until}; use crate::{Node, Spec}; use ckb_logger::info; +use ckb_types::prelude::*; use std::time::Duration; pub struct RelayTooNewBlock; @@ -21,7 +22,7 @@ impl Spec for RelayTooNewBlock { let future = Duration::from_secs(6_000).as_millis() as u64; let too_new_block = node0 .new_block_builder(None, None, None) - .timestamp(now_ms() + future) + .timestamp((now_ms() + future).pack()) .build(); let _too_new_hash = node0.process_block_without_verify(&too_new_block, true); diff --git a/test/src/specs/relay/compact_block.rs b/test/src/specs/relay/compact_block.rs index 0cd024796c..9b8c078b7f 100644 --- a/test/src/specs/relay/compact_block.rs +++ b/test/src/specs/relay/compact_block.rs @@ -40,7 +40,7 @@ impl Spec for CompactBlockEmptyParentUnknown { .new_block_builder(None, None, None) .header( HeaderBuilder::default() - .parent_hash(h256!("0x123456")) + .parent_hash(h256!("0x123456").pack()) .build(), ) .build(); @@ -297,7 +297,7 @@ impl Spec for CompactBlockMissingWithDropTx { .as_reader() .indexes() .iter() - .map(Into::::into) + .map(|i| Unpack::::unpack(&i)) .collect::>(); vec![2] == msg } else { @@ -316,7 +316,7 @@ impl Spec for CompactBlockMissingWithDropTx { let content = packed::BlockTransactions::new_builder() .block_hash(new_block.hash()) - .transactions(vec![new_tx_2.data()]) + .transactions(vec![new_tx_2.data()].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); @@ -331,7 +331,7 @@ impl Spec for CompactBlockMissingWithDropTx { .as_reader() .indexes() .iter() - .map(Into::::into) + .map(|i| Unpack::::unpack(&i)) .collect::>(); vec![1, 2] == msg } else { @@ -348,7 +348,7 @@ impl Spec for CompactBlockMissingWithDropTx { let content = packed::BlockTransactions::new_builder() .block_hash(new_block.hash()) - .transactions(vec![new_tx_1.data(), new_tx_2.data()]) + .transactions(vec![new_tx_1.data(), new_tx_2.data()].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/test/src/specs/relay/get_block_proposal_process.rs b/test/src/specs/relay/get_block_proposal_process.rs index 9f7083180f..f3e59b45e1 100644 --- a/test/src/specs/relay/get_block_proposal_process.rs +++ b/test/src/specs/relay/get_block_proposal_process.rs @@ -46,7 +46,7 @@ impl Spec for ProposalRespondSizelimit { let content = packed::GetBlockProposal::new_builder() .block_hash(tip_hash) - .proposals(proposal_ids) + .proposals(proposal_ids.pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/test/src/specs/relay/get_block_transactions_process.rs b/test/src/specs/relay/get_block_transactions_process.rs index b40b22b2da..e621ad336d 100644 --- a/test/src/specs/relay/get_block_transactions_process.rs +++ b/test/src/specs/relay/get_block_transactions_process.rs @@ -24,18 +24,21 @@ impl Spec for MissingUncleRequest { node.mine(1); let builder = node.new_block_builder(None, None, None); - let block1 = builder.clone().nonce(0).build(); - let block2 = builder.nonce(1).build(); + let block1 = builder.clone().nonce(0.pack()).build(); + let block2 = builder.nonce(1.pack()).build(); node.submit_block(&block1); node.submit_block(&block2); let builder = node.new_block_builder(None, None, None); - let block = builder.set_uncles(vec![block2.as_uncle()]).nonce(0).build(); + let block = builder + .set_uncles(vec![block2.as_uncle()]) + .nonce(0.pack()) + .build(); node.submit_block(&block); let content = packed::GetBlockTransactions::new_builder() .block_hash(block.hash()) - .uncle_indexes([0u32]) + .uncle_indexes([0u32].pack()) .build(); let message = packed::RelayMessage::new_builder().set(content).build(); diff --git a/test/src/specs/relay/transaction_relay.rs b/test/src/specs/relay/transaction_relay.rs index 28cd66a3fe..1a9512314c 100644 --- a/test/src/specs/relay/transaction_relay.rs +++ b/test/src/specs/relay/transaction_relay.rs @@ -241,7 +241,7 @@ impl Spec for TransactionRelayConflict { let tx1 = node0.new_transaction(tx_hash_0.clone()); let tx2_temp = node0.new_transaction(tx_hash_0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(80)) + .capacity(capacity_bytes!(80).pack()) .build(); let tx2 = tx2_temp diff --git a/test/src/specs/relay/transaction_relay_low_fee_rate.rs b/test/src/specs/relay/transaction_relay_low_fee_rate.rs index f172f4b569..1aad334416 100644 --- a/test/src/specs/relay/transaction_relay_low_fee_rate.rs +++ b/test/src/specs/relay/transaction_relay_low_fee_rate.rs @@ -5,10 +5,7 @@ use crate::util::log_monitor::monitor_log_until_expected_show; use crate::util::mining::out_ibd_mode; use crate::{Node, Spec}; use ckb_logger::debug; -use ckb_types::{ - core::{FeeRate, TransactionBuilder}, - packed, -}; +use ckb_types::core::{FeeRate, TransactionBuilder}; pub struct TransactionRelayLowFeeRate; @@ -26,7 +23,7 @@ impl Spec for TransactionRelayLowFeeRate { let low_fee = TransactionBuilder::default() .input(as_input(&cells[0])) .output(as_output(&cells[0])) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(node0.always_success_cell_dep()) .build(); diff --git a/test/src/specs/rpc/get_block_template.rs b/test/src/specs/rpc/get_block_template.rs index 46c509b44d..58a076e117 100644 --- a/test/src/specs/rpc/get_block_template.rs +++ b/test/src/specs/rpc/get_block_template.rs @@ -1,6 +1,6 @@ use crate::{Node, Spec}; use ckb_jsonrpc_types::AsEpochNumberWithFraction; -use ckb_types::packed; +use ckb_types::prelude::*; pub struct RpcGetBlockTemplate; @@ -48,10 +48,10 @@ impl Spec for RpcGetBlockTemplate { let parent_block_hash = node0.get_tip_block().hash(); assert_eq!( parent_block_hash, - (&genesis_block_template.parent_hash).into(), + genesis_block_template.parent_hash.pack(), "Parent block hash should be {}, but got {}", parent_block_hash, - Into::::into(&genesis_block_template.parent_hash) + genesis_block_template.parent_hash.pack() ); assert_eq!( 0, diff --git a/test/src/specs/rpc/submit_block.rs b/test/src/specs/rpc/submit_block.rs index 7e1bb10470..6a06fa8025 100644 --- a/test/src/specs/rpc/submit_block.rs +++ b/test/src/specs/rpc/submit_block.rs @@ -1,6 +1,9 @@ use crate::utils::now_ms; use crate::{Node, Spec}; -use ckb_types::core::{EpochNumberWithFraction, HeaderView}; +use ckb_types::{ + core::{EpochNumberWithFraction, HeaderView}, + prelude::*, +}; pub struct RpcSubmitBlock; @@ -14,7 +17,10 @@ impl Spec for RpcSubmitBlock { node1.mine_until_out_bootstrap_period(); // build block with wrong block number - let block = node0.new_block_builder(None, None, None).number(2).build(); + let block = node0 + .new_block_builder(None, None, None) + .number(2.pack()) + .build(); let block_err = node0 .rpc_client() .submit_block("".to_owned(), block.data().into()) @@ -35,7 +41,7 @@ impl Spec for RpcSubmitBlock { let epoch = EpochNumberWithFraction::new(tip_epoch.number() + 1, 0, 100); let block = node0 .new_block_builder(None, None, None) - .epoch(epoch) + .epoch(epoch.pack()) .build(); let block_err = node0 .rpc_client() @@ -81,7 +87,7 @@ impl Spec for RpcSubmitBlock { // so here plus another 15s to make sure when submit the block it still out of the limit let block = node0 .new_block_builder(None, None, None) - .timestamp(now_ms() + 30_000) + .timestamp((now_ms() + 30_000).pack()) .build(); let block_err = node0 .rpc_client() @@ -96,7 +102,7 @@ impl Spec for RpcSubmitBlock { let median_time = node0.rpc_client().get_blockchain_info().median_time.value(); let block = node0 .new_block_builder(None, None, None) - .timestamp(median_time - 1) + .timestamp((median_time - 1).pack()) .build(); let block_err = node0 .rpc_client() diff --git a/test/src/specs/rpc/transaction_proof.rs b/test/src/specs/rpc/transaction_proof.rs index d4eefcb4c4..0b5d83384e 100644 --- a/test/src/specs/rpc/transaction_proof.rs +++ b/test/src/specs/rpc/transaction_proof.rs @@ -1,4 +1,5 @@ use crate::{Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; +use ckb_types::prelude::*; pub struct RpcTransactionProof; @@ -9,7 +10,7 @@ impl Spec for RpcTransactionProof { let tx_hash = node0.generate_transaction(); node0.mine_until_transaction_confirm(&tx_hash); - let tx_hashes = vec![tx_hash.into()]; + let tx_hashes = vec![tx_hash.unpack()]; let proof = node0 .rpc_client() .inner() diff --git a/test/src/specs/sync/block_filter.rs b/test/src/specs/sync/block_filter.rs index 0c86a1cb57..0996da7935 100644 --- a/test/src/specs/sync/block_filter.rs +++ b/test/src/specs/sync/block_filter.rs @@ -31,7 +31,7 @@ impl Spec for GetBlockFilterCheckPoints { let start_number: u64 = 0; let request = { let content = packed::GetBlockFilterCheckPoints::new_builder() - .start_number(start_number) + .start_number(start_number.pack()) .build(); packed::BlockFilterMessage::new_builder() .set(content) @@ -45,7 +45,7 @@ impl Spec for GetBlockFilterCheckPoints { match packed::BlockFilterMessageReader::from_slice(&data) { Ok(msg) => match msg.to_enum() { packed::BlockFilterMessageUnionReader::BlockFilterCheckPoints(reader) => { - let resp_start_number: u64 = reader.start_number().into(); + let resp_start_number: u64 = reader.start_number().unpack(); assert_eq!(start_number, resp_start_number); info!("start_number matched"); @@ -113,7 +113,7 @@ impl Spec for GetBlockFilterHashes { let start_number: u64 = 2; let request = { let content = packed::GetBlockFilterHashes::new_builder() - .start_number(start_number) + .start_number(start_number.pack()) .build(); packed::BlockFilterMessage::new_builder() .set(content) @@ -127,7 +127,7 @@ impl Spec for GetBlockFilterHashes { match packed::BlockFilterMessageReader::from_slice(&data) { Ok(msg) => match msg.to_enum() { packed::BlockFilterMessageUnionReader::BlockFilterHashes(reader) => { - let resp_start_number: u64 = reader.start_number().into(); + let resp_start_number: u64 = reader.start_number().unpack(); assert_eq!(start_number, resp_start_number); info!("start_number matched"); @@ -205,7 +205,7 @@ impl Spec for GetBlockFilters { let start_number: u64 = 42; let request = { let content = packed::GetBlockFilters::new_builder() - .start_number(start_number) + .start_number(start_number.pack()) .build(); packed::BlockFilterMessage::new_builder() .set(content) @@ -219,7 +219,7 @@ impl Spec for GetBlockFilters { match packed::BlockFilterMessageReader::from_slice(&data) { Ok(msg) => match msg.to_enum() { packed::BlockFilterMessageUnionReader::BlockFilters(reader) => { - let resp_start_number: u64 = reader.start_number().into(); + let resp_start_number: u64 = reader.start_number().unpack(); assert_eq!(start_number, resp_start_number); info!("start_number matched"); @@ -231,7 +231,7 @@ impl Spec for GetBlockFilters { let filters: Vec = reader .filters() .iter() - .map(|item| item.to_entity().into()) + .map(|item| item.to_entity().unpack()) .collect(); assert_eq!( @@ -289,7 +289,7 @@ impl Spec for GetBlockFiltersNotReachBatch { info!("start_number: {start_number}"); let request = { let content = packed::GetBlockFilters::new_builder() - .start_number(start_number) + .start_number(start_number.pack()) .build(); packed::BlockFilterMessage::new_builder() .set(content) @@ -303,7 +303,7 @@ impl Spec for GetBlockFiltersNotReachBatch { match packed::BlockFilterMessageReader::from_slice(&data) { Ok(msg) => match msg.to_enum() { packed::BlockFilterMessageUnionReader::BlockFilters(reader) => { - let resp_start_number: u64 = reader.start_number().into(); + let resp_start_number: u64 = reader.start_number().unpack(); assert_eq!(start_number, resp_start_number); info!("start_number matched"); @@ -315,7 +315,7 @@ impl Spec for GetBlockFiltersNotReachBatch { let filters: Vec = reader .filters() .iter() - .map(|item| item.to_entity().into()) + .map(|item| item.to_entity().unpack()) .collect(); assert_eq!( diff --git a/test/src/specs/sync/block_sync.rs b/test/src/specs/sync/block_sync.rs index d283150a57..10f2ef9ffe 100644 --- a/test/src/specs/sync/block_sync.rs +++ b/test/src/specs/sync/block_sync.rs @@ -57,8 +57,8 @@ impl Spec for BlockSyncWithUncle { let node1 = &nodes[1]; let new_builder = node1.new_block_builder(None, None, None); - let new_block1 = new_builder.clone().nonce(0).build(); - let new_block2 = new_builder.nonce(1).build(); + let new_block1 = new_builder.clone().nonce(0.pack()).build(); + let new_block2 = new_builder.nonce(1.pack()).build(); node1.submit_block(&new_block1); node1.submit_block(&new_block2); @@ -329,7 +329,7 @@ impl Spec for BlockSyncNonAncestorBestBlocks { let b = a .data() .as_advanced_builder() - .timestamp(a.timestamp() + 1) + .timestamp((a.timestamp() + 1).pack()) .build(); assert_ne!(a.hash(), b.hash()); node1.submit_block(&b); @@ -432,7 +432,7 @@ impl Spec for SyncTooNewBlock { for _ in 0..3 { let too_new_block = node0 .new_block_builder(None, None, None) - .timestamp(now_ms() + future) + .timestamp((now_ms() + future).pack()) .build(); // node1 sync node1 with too new block @@ -471,7 +471,9 @@ impl Spec for HeaderSyncCycle { let mut net = Net::new(self.name(), node0.consensus(), vec![SupportProtocols::Sync]); net.connect(node0); - let send_headers = SendHeaders::new_builder().headers(Vec::new()).build(); + let send_headers = SendHeaders::new_builder() + .headers(Vec::new().pack()) + .build(); let msg = SyncMessage::new_builder() .set(send_headers) diff --git a/test/src/specs/sync/chain_forks.rs b/test/src/specs/sync/chain_forks.rs index 446de599be..b1d9132f6c 100644 --- a/test/src/specs/sync/chain_forks.rs +++ b/test/src/specs/sync/chain_forks.rs @@ -144,10 +144,10 @@ impl Spec for ChainFork3 { .get(0) .unwrap() .to_entity(); - let old_capacity: Capacity = old_output.capacity().into(); + let old_capacity: Capacity = old_output.capacity().unpack(); let new_output = old_output .as_builder() - .capacity(old_capacity.safe_add(capacity_bytes!(1)).unwrap()) + .capacity(old_capacity.safe_add(capacity_bytes!(1)).unwrap().pack()) .build(); transaction .as_advanced_builder() @@ -214,7 +214,7 @@ impl Spec for ChainFork4 { .unwrap() .to_entity() .as_builder() - .capacity(capacity_bytes!(1)) + .capacity(capacity_bytes!(1).pack()) .build(); transaction .as_advanced_builder() @@ -344,7 +344,7 @@ impl Spec for ChainFork6 { node1.mine(2); info!("Generate 1 block (F) with spending non-existent transaction on node1"); let block = node1.new_block(None, None, None); - let invalid_transaction = node1.new_transaction(h256!("0x1").into()); + let invalid_transaction = node1.new_transaction(h256!("0x1").pack()); let invalid_block = block .as_advanced_builder() .transaction(invalid_transaction) @@ -402,7 +402,11 @@ impl Spec for ChainFork7 { let block = node1.new_block(None, None, None); let transaction = node1.new_transaction_spend_tip_cellbase(); let input = transaction.inputs().as_reader().get(0).unwrap().to_entity(); - let previous_output = input.previous_output().as_builder().index(999u32).build(); + let previous_output = input + .previous_output() + .as_builder() + .index(999u32.pack()) + .build(); let input = input.as_builder().previous_output(previous_output).build(); let invalid_transaction = transaction .as_advanced_builder() @@ -572,7 +576,7 @@ impl Spec for ForksContainSameUncle { let block_b = node_b .new_block_builder(None, None, None) .set_uncles(vec![uncle.as_uncle()]) - .timestamp(block_a.timestamp() + 2) + .timestamp((block_a.timestamp() + 2).pack()) .build(); node_a.submit_block(&block_a); node_b.submit_block(&block_b); diff --git a/test/src/specs/sync/invalid_locator_size.rs b/test/src/specs/sync/invalid_locator_size.rs index ed7091959c..e11262ca30 100644 --- a/test/src/specs/sync/invalid_locator_size.rs +++ b/test/src/specs/sync/invalid_locator_size.rs @@ -21,13 +21,13 @@ impl Spec for InvalidLocatorSize { net.connect(node0); let hashes: Vec = (0..=MAX_LOCATOR_SIZE) - .map(|_| h256!("0x1").into()) + .map(|_| h256!("0x1").pack()) .collect(); let message = SyncMessage::new_builder() .set( GetHeaders::new_builder() - .block_locator_hashes(hashes) + .block_locator_hashes(hashes.pack()) .build(), ) .build() diff --git a/test/src/specs/tx_pool/collision.rs b/test/src/specs/tx_pool/collision.rs index 0f05d7f580..0d93697c03 100644 --- a/test/src/specs/tx_pool/collision.rs +++ b/test/src/specs/tx_pool/collision.rs @@ -4,11 +4,8 @@ use crate::util::check::{ use crate::utils::{assert_send_transaction_fail, blank, commit, propose}; use crate::{Node, Spec}; use ckb_types::bytes::Bytes; +use ckb_types::core::{capacity_bytes, Capacity, TransactionView}; use ckb_types::prelude::*; -use ckb_types::{ - core::{capacity_bytes, Capacity, TransactionView}, - packed, -}; // Convention: // * `tx1` and `tx2` are cousin transactions, with the same transaction content, except the @@ -197,7 +194,7 @@ fn conflict_transactions_with_capacity( .unwrap(); let txb = txa .as_advanced_builder() - .set_outputs_data(vec![output_data.into()]) + .set_outputs_data(vec![output_data.pack()]) .set_outputs(vec![output]) .build(); assert_ne!(txa.hash(), txb.hash()); @@ -216,7 +213,7 @@ fn cousin_txs_with_same_hash_different_witness_hash( let tx1 = node.new_transaction_spend_tip_cellbase(); let tx2 = tx1 .as_advanced_builder() - .witness(packed::Bytes::default()) + .witness(Default::default()) .build(); assert_eq!(tx1.hash(), tx2.hash()); assert_eq!(tx1.proposal_short_id(), tx2.proposal_short_id()); diff --git a/test/src/specs/tx_pool/dead_cell_deps.rs b/test/src/specs/tx_pool/dead_cell_deps.rs index 77ae8fb619..0b7816bf84 100644 --- a/test/src/specs/tx_pool/dead_cell_deps.rs +++ b/test/src/specs/tx_pool/dead_cell_deps.rs @@ -50,7 +50,7 @@ impl Spec for CellBeingCellDepThenSpentInSameBlockTestSubmitBlock { let tx_c = { let tx = always_success_transaction(node0, input_c); let cell_dep_to_tx_a = CellDepBuilder::default() - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .out_point(OutPoint::new(tx_a.hash(), 0)) .build(); tx.as_advanced_builder().cell_dep(cell_dep_to_tx_a).build() @@ -122,7 +122,7 @@ impl Spec for CellBeingSpentThenCellDepInSameBlockTestSubmitBlock { let tx_c = { let tx = always_success_transaction(node0, input_c); let cell_dep_to_tx_a = CellDepBuilder::default() - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .out_point(OutPoint::new(tx_a.hash(), 0)) .build(); tx.as_advanced_builder().cell_dep(cell_dep_to_tx_a).build() @@ -208,7 +208,7 @@ impl Spec for CellBeingCellDepAndSpentInSameBlockTestGetBlockTemplate { let mut tx_c = { let tx = always_success_transaction(node0, input_c); let cell_dep_to_tx_a = CellDepBuilder::default() - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .out_point(OutPoint::new(tx_a.hash(), 0)) .build(); tx.as_advanced_builder().cell_dep(cell_dep_to_tx_a).build() diff --git a/test/src/specs/tx_pool/different_txs_with_same_input.rs b/test/src/specs/tx_pool/different_txs_with_same_input.rs index cdd1abf8dd..f590f7ae81 100644 --- a/test/src/specs/tx_pool/different_txs_with_same_input.rs +++ b/test/src/specs/tx_pool/different_txs_with_same_input.rs @@ -22,7 +22,7 @@ impl Spec for DifferentTxsWithSameInputWithOutRBF { // Set tx2 fee to a higher value, tx1 capacity is 100, set tx2 capacity to 80 for +20 fee. let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(80)) + .capacity(capacity_bytes!(80).pack()) .build(); let tx2 = tx2_temp diff --git a/test/src/specs/tx_pool/limit.rs b/test/src/specs/tx_pool/limit.rs index 60e2090ba2..ba9a84df80 100644 --- a/test/src/specs/tx_pool/limit.rs +++ b/test/src/specs/tx_pool/limit.rs @@ -83,7 +83,7 @@ impl Spec for TxPoolLimitAncestorCount { }; let cell_dep = CellDepBuilder::default() - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .out_point(OutPoint::new(tx_a.hash(), 0)) .build(); diff --git a/test/src/specs/tx_pool/mod.rs b/test/src/specs/tx_pool/mod.rs index b8e1abc45c..436fc44b93 100644 --- a/test/src/specs/tx_pool/mod.rs +++ b/test/src/specs/tx_pool/mod.rs @@ -55,12 +55,12 @@ use ckb_app_config::BlockAssemblerConfig; use ckb_chain_spec::{build_genesis_type_id_script, OUTPUT_INDEX_SECP256K1_BLAKE160_SIGHASH_ALL}; use ckb_jsonrpc_types::JsonBytes; use ckb_resource::CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL; -use ckb_types::{bytes::Bytes, core::ScriptHashType, H256}; +use ckb_types::{bytes::Bytes, core::ScriptHashType, prelude::*, H256}; fn type_lock_script_code_hash() -> H256 { build_genesis_type_id_script(OUTPUT_INDEX_SECP256K1_BLAKE160_SIGHASH_ALL) .calc_script_hash() - .into() + .unpack() } fn new_block_assembler_config(lock_arg: Bytes, hash_type: ScriptHashType) -> BlockAssemblerConfig { diff --git a/test/src/specs/tx_pool/orphan_tx.rs b/test/src/specs/tx_pool/orphan_tx.rs index ac7605dc40..7e056380d5 100644 --- a/test/src/specs/tx_pool/orphan_tx.rs +++ b/test/src/specs/tx_pool/orphan_tx.rs @@ -136,7 +136,7 @@ fn build_tx_chain( let script = node0.always_success_script(); let new_output1 = CellOutputBuilder::default() - .capacity(capacity_bytes!(200)) + .capacity(capacity_bytes!(200).pack()) .lock(script.clone()) .build(); let new_output2 = new_output1.clone(); @@ -158,7 +158,7 @@ fn build_tx_chain( let cell_dep = node0.always_success_cell_dep(); let final_output = CellOutputBuilder::default() - .capacity(capacity_bytes!(80)) + .capacity(capacity_bytes!(80).pack()) .lock(script) .build(); let final_tx = TransactionBuilder::default() @@ -373,7 +373,7 @@ impl Spec for TxPoolOrphanDoubleSpend { let script = node0.always_success_script(); let new_output1 = CellOutputBuilder::default() - .capacity(capacity_bytes!(200)) + .capacity(capacity_bytes!(200).pack()) .lock(script) .build(); let new_output2 = new_output1.clone(); diff --git a/test/src/specs/tx_pool/pool_reconcile.rs b/test/src/specs/tx_pool/pool_reconcile.rs index 6377216689..280c506cc8 100644 --- a/test/src/specs/tx_pool/pool_reconcile.rs +++ b/test/src/specs/tx_pool/pool_reconcile.rs @@ -112,7 +112,7 @@ impl Spec for PoolResolveConflictAfterReorg { !(template .transactions .iter() - .any(|tx| tx.hash == tx1.hash().into())) + .any(|tx| tx.hash == tx1.hash().unpack())) }) .set_proposals(txs.iter().map(|tx| tx.proposal_short_id()).collect()) .build(); @@ -161,7 +161,7 @@ impl Spec for PoolResolveConflictAfterReorg { .build() }]) .set_outputs(vec![CellOutputBuilder::default() - .capacity(capacity_bytes!(99)) + .capacity(capacity_bytes!(99).pack()) .build()]) .build(); diff --git a/test/src/specs/tx_pool/replace.rs b/test/src/specs/tx_pool/replace.rs index dad1b5107f..b6ef175906 100644 --- a/test/src/specs/tx_pool/replace.rs +++ b/test/src/specs/tx_pool/replace.rs @@ -28,7 +28,7 @@ impl Spec for RbfEnable { let tx1 = node0.new_transaction(tx_hash_0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx1 = tx1.as_advanced_builder().set_outputs(vec![output]).build(); @@ -59,7 +59,7 @@ impl Spec for RbfBasic { let tx1 = node0.new_transaction(tx_hash_0.clone()); let tx2_temp = node0.new_transaction(tx_hash_0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(99)) + .capacity(capacity_bytes!(99).pack()) .build(); let tx1 = tx1.as_advanced_builder().set_outputs(vec![output]).build(); @@ -76,7 +76,7 @@ impl Spec for RbfBasic { // Set tx2 fee to a higher value, tx1 capacity is 99, set tx2 capacity to 95 for +4 fee. let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(95)) + .capacity(capacity_bytes!(95).pack()) .build(); let tx2 = tx2_temp @@ -88,7 +88,7 @@ impl Spec for RbfBasic { .rpc_client() .send_transaction_result(tx2.data().into()); assert!(res.is_ok(), "tx2 should replace with old tx"); - assert_eq!(get_tx_pool_conflicts(node0), vec![tx1.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx1.hash().unpack()]); let ret = node0 .rpc_client() @@ -141,7 +141,7 @@ impl Spec for RbfBasic { assert!(ret.transaction.is_none()); assert!(matches!(ret.tx_status.status, Status::Rejected)); assert!(ret.tx_status.reason.unwrap().contains("RBFRejected")); - assert_eq!(get_tx_pool_conflicts(node0), vec![tx1.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx1.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -230,14 +230,14 @@ impl Spec for RbfSameInputwithLessFee { let tx2_temp = node0.new_transaction(tx_hash_0); let output1 = CellOutputBuilder::default() - .capacity(capacity_bytes!(80)) + .capacity(capacity_bytes!(80).pack()) .build(); let tx1 = tx1.as_advanced_builder().set_outputs(vec![output1]).build(); // Set tx2 fee to a lower value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(90)) + .capacity(capacity_bytes!(90).pack()) .build(); let tx2 = tx2_temp @@ -256,7 +256,7 @@ impl Spec for RbfSameInputwithLessFee { )); // local submit tx RBF check failed, will be added into conflicts pool - assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -300,7 +300,7 @@ impl Spec for RbfTooManyDescendants { // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx2 = tx0_temp @@ -319,7 +319,7 @@ impl Spec for RbfTooManyDescendants { .contains("Tx conflict with too many txs")); // local submit tx RBF check failed, will not in conflicts pool - assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -363,7 +363,7 @@ impl Spec for RbfContainNewTx { let clone_tx = txs[2].clone(); // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx2 = clone_tx @@ -394,7 +394,7 @@ impl Spec for RbfContainNewTx { .contains("new Tx contains unconfirmed inputs")); // local submit tx RBF check failed, will be in conflicts pool - assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -438,7 +438,7 @@ impl Spec for RbfContainInvalidInput { let clone_tx = txs[2].clone(); // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx2 = clone_tx @@ -469,7 +469,7 @@ impl Spec for RbfContainInvalidInput { .contains("new Tx contains inputs in descendants of to be replaced Tx")); // local submit tx RBF check failed, will not in conflicts pool - assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![tx2.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -492,7 +492,7 @@ impl Spec for RbfChildPayForParent { let max_count = 5; let output5 = CellOutputBuilder::default() - .capacity(capacity_bytes!(50)) + .capacity(capacity_bytes!(50).pack()) .build(); while txs.len() <= max_count { @@ -524,7 +524,7 @@ impl Spec for RbfChildPayForParent { let clone_tx = txs[2].clone(); // Set tx2 fee to a higher value, but not enough to pay for tx4 let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let new_tx = clone_tx @@ -548,11 +548,11 @@ impl Spec for RbfChildPayForParent { .contains("RBF rejected: Tx's current fee is 3000000000, expect it to >= 5000000363 to replace old txs")); // local submit tx RBF check failed, will be in conflicts pool - assert_eq!(get_tx_pool_conflicts(node0), vec![new_tx.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![new_tx.hash().unpack()]); // let's try a new transaction with new higher fee let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(45)) + .capacity(capacity_bytes!(45).pack()) .build(); let new_tx_ok = clone_tx .as_advanced_builder() @@ -572,9 +572,9 @@ impl Spec for RbfChildPayForParent { // tx2 tx3 tx4 is replaced let mut expected: Vec = txs[2..=max_count - 1] .iter() - .map(|tx| tx.hash().into()) + .map(|tx| tx.hash().unpack()) .collect::>(); - expected.push(new_tx.hash().into()); + expected.push(new_tx.hash().unpack()); expected.sort_unstable(); let conflicts = get_tx_pool_conflicts(node0); assert_eq!(conflicts, expected); @@ -609,7 +609,7 @@ impl Spec for RbfContainInvalidCells { // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx2 = clone_tx .as_advanced_builder() @@ -688,7 +688,7 @@ impl Spec for RbfRejectReplaceProposed { let clone_tx = txs[2].clone(); // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx1_hash = txs[2].hash(); @@ -798,7 +798,7 @@ impl Spec for RbfReplaceProposedSuccess { let clone_tx = txs[2].clone(); // Set tx2 fee to a higher value let output2 = CellOutputBuilder::default() - .capacity(capacity_bytes!(70)) + .capacity(capacity_bytes!(70).pack()) .build(); let tx1_hash = txs[2].hash(); @@ -843,9 +843,9 @@ impl Spec for RbfReplaceProposedSuccess { assert_eq!(tx1_status.status, Status::Rejected); let mut expected = [ - txs[2].hash().into(), - txs[3].hash().into(), - txs[4].hash().into(), + txs[2].hash().unpack(), + txs[3].hash().unpack(), + txs[4].hash().unpack(), ]; expected.sort_unstable(); assert_eq!(get_tx_pool_conflicts(node0), expected); @@ -893,7 +893,7 @@ impl Spec for RbfConcurrency { ]; for fee in fees.iter() { let tx2_temp = node0.new_transaction(tx_hash_0.clone()); - let output = CellOutputBuilder::default().capacity(fee).build(); + let output = CellOutputBuilder::default().capacity(fee.pack()).build(); let tx2 = tx2_temp .as_advanced_builder() @@ -931,8 +931,11 @@ impl Spec for RbfConcurrency { assert_eq!(*s, Status::Rejected); } - let mut expected: Vec = - conflicts.iter().take(4).map(|x| x.hash().into()).collect(); + let mut expected: Vec = conflicts + .iter() + .take(4) + .map(|x| x.hash().unpack()) + .collect(); expected.sort_unstable(); assert_eq!(get_tx_pool_conflicts(node0), expected); } @@ -974,7 +977,7 @@ impl Spec for RbfCellDepsCheck { // Create a child transaction with celldep let tx = always_success_transaction(node0, input_c); let cell_dep_to_last = CellDepBuilder::default() - .dep_type(DepType::Code) + .dep_type(DepType::Code.into()) .out_point(OutPoint::new(prev.hash(), 0)) .build(); let tx_c = tx @@ -988,7 +991,7 @@ impl Spec for RbfCellDepsCheck { // Create a new transaction for cell dep with high fee let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(80)) + .capacity(capacity_bytes!(80).pack()) .build(); let new_tx = tx_a .as_advanced_builder() @@ -1002,7 +1005,7 @@ impl Spec for RbfCellDepsCheck { .unwrap() .to_string() .contains("new Tx contains cell deps from conflicts")); - assert_eq!(get_tx_pool_conflicts(node0), vec![new_tx.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node0), vec![new_tx.hash().unpack()]); } fn modify_app_config(&self, config: &mut ckb_app_config::CKBAppConfig) { @@ -1160,7 +1163,7 @@ fn run_spec_send_conflict_relay(nodes: &mut [Node]) { let tx1 = node0.new_transaction(tx_hash_0.clone()); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(90)) + .capacity(capacity_bytes!(90).pack()) .build(); let tx1 = tx1.as_advanced_builder().set_outputs(vec![output]).build(); @@ -1186,7 +1189,7 @@ fn run_spec_send_conflict_relay(nodes: &mut [Node]) { // node0 will accept it and node1 will reject it and put it in conflicts pool let tx2_temp = node0.new_transaction(tx_hash_0); let output = CellOutputBuilder::default() - .capacity(capacity_bytes!(95)) + .capacity(capacity_bytes!(95).pack()) .build(); let tx2 = tx2_temp @@ -1208,7 +1211,7 @@ fn run_spec_send_conflict_relay(nodes: &mut [Node]) { assert_eq!(res.status, Status::Rejected); let res = node1.get_transaction(tx1.hash()); assert_eq!(res.status, Status::Pending); - assert_eq!(get_tx_pool_conflicts(node1), vec![tx2.hash().into()]); + assert_eq!(get_tx_pool_conflicts(node1), vec![tx2.hash().unpack()]); } pub struct SendConflictTxToRelay; diff --git a/test/src/specs/tx_pool/send_defected_binary.rs b/test/src/specs/tx_pool/send_defected_binary.rs index cc5667af28..76dab8dbe3 100644 --- a/test/src/specs/tx_pool/send_defected_binary.rs +++ b/test/src/specs/tx_pool/send_defected_binary.rs @@ -55,10 +55,10 @@ impl Spec for SendDefectedBinary { let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(5000)) + .capacity(capacity_bytes!(5000).pack()) .lock(node.always_success_script()) .build(); let data = include_bytes!("../../../../script/testdata/defected_binary"); @@ -66,12 +66,12 @@ impl Spec for SendDefectedBinary { .cell_dep(cell_dep.clone()) .inputs(inputs.clone()) .output(output.clone()) - .output_data(&data[..]) + .output_data(data[..].pack()) .build(); let tx_hash = tx.hash(); let witness = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let message = { @@ -86,14 +86,14 @@ impl Spec for SendDefectedBinary { let sig = self.privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() - .lock(Some(Bytes::from(sig.serialize()))) + .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .inputs(inputs) .output(output) - .output_data(&data[..]) - .witness(witness.as_bytes()) + .output_data(data[..].pack()) + .witness(witness.as_bytes().pack()) .build(); info!("Send 1 secp tx with defected binary"); diff --git a/test/src/specs/tx_pool/send_large_cycles_tx.rs b/test/src/specs/tx_pool/send_large_cycles_tx.rs index 26e93c3761..ce4d4ec09e 100644 --- a/test/src/specs/tx_pool/send_large_cycles_tx.rs +++ b/test/src/specs/tx_pool/send_large_cycles_tx.rs @@ -13,7 +13,7 @@ use ckb_types::{ capacity_bytes, BlockView, Capacity, DepType, ScriptHashType, TransactionBuilder, TransactionView, }, - packed::{self, CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, + packed::{CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, prelude::*, H256, }; @@ -325,13 +325,13 @@ impl RandomKey { fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView { let secp_out_point = OutPoint::new(node.dep_group_tx_hash(), 0); let lock = Script::new_builder() - .args(lock_arg) - .code_hash(type_lock_script_code_hash()) - .hash_type(ScriptHashType::Type) + .args(lock_arg.pack()) + .code_hash(type_lock_script_code_hash().pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let input1 = { let block = node.get_tip_block(); @@ -339,18 +339,18 @@ fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView CellInput::new(OutPoint::new(cellbase_hash, 0), 0) }; let output1 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock) .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .input(input1) .output(output1) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); - let tx_hash: H256 = tx.hash().into(); + let tx_hash: H256 = tx.hash().unpack(); let witness = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let message = { @@ -365,7 +365,9 @@ fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView let sig = privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() - .lock(Some(Bytes::from(sig.serialize()))) + .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); - tx.as_advanced_builder().witness(witness.as_bytes()).build() + tx.as_advanced_builder() + .witness(witness.as_bytes().pack()) + .build() } diff --git a/test/src/specs/tx_pool/send_low_fee_rate_tx.rs b/test/src/specs/tx_pool/send_low_fee_rate_tx.rs index 40a3ebcc6a..befbf60722 100644 --- a/test/src/specs/tx_pool/send_low_fee_rate_tx.rs +++ b/test/src/specs/tx_pool/send_low_fee_rate_tx.rs @@ -44,7 +44,7 @@ impl Spec for SendLowFeeRateTx { .get(0) .unwrap() .as_builder() - .capacity(capacity) + .capacity(capacity.pack()) .build(); let tx_low_fee = tx_low_fee .data() @@ -64,7 +64,7 @@ impl Spec for SendLowFeeRateTx { .get(0) .unwrap() .as_builder() - .capacity(capacity.safe_sub(1000u32).unwrap()) + .capacity(capacity.safe_sub(1000u32).unwrap().pack()) .build(); let tx_high_fee = tx_high_fee .data() diff --git a/test/src/specs/tx_pool/send_multisig_secp_tx.rs b/test/src/specs/tx_pool/send_multisig_secp_tx.rs index 5eb2c96694..f0de38db6f 100644 --- a/test/src/specs/tx_pool/send_multisig_secp_tx.rs +++ b/test/src/specs/tx_pool/send_multisig_secp_tx.rs @@ -10,7 +10,7 @@ use ckb_resource::CODE_HASH_SECP256K1_BLAKE160_MULTISIG_ALL; use ckb_types::{ bytes::Bytes, core::{capacity_bytes, Capacity, DepType, ScriptHashType, TransactionBuilder}, - packed::{self, CellDep, CellInput, CellOutput, OutPoint, WitnessArgs}, + packed::{CellDep, CellInput, CellOutput, OutPoint, WitnessArgs}, prelude::*, H160, H256, }; @@ -50,10 +50,10 @@ impl Spec for SendMultiSigSecpTxUseDepGroup { let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(node.always_success_script()) .build(); let input = CellInput::new(OutPoint::new(cellbase_hash, 0), 0); @@ -61,7 +61,7 @@ impl Spec for SendMultiSigSecpTxUseDepGroup { .cell_dep(cell_dep.clone()) .input(input.clone()) .output(output.clone()) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); let multi_sign_script = gen_multi_sign_script(&self.keys, self.keys.len() as u8, 0); let tx_hash = tx.hash(); @@ -69,7 +69,7 @@ impl Spec for SendMultiSigSecpTxUseDepGroup { let mut lock = multi_sign_script.to_vec(); lock.extend(vec![0u8; 65 * self.keys.len()]); WitnessArgs::new_builder() - .lock(Some(Bytes::from(lock))) + .lock(Some(Bytes::from(lock)).pack()) .build() }; let witness_len = witness.as_slice().len() as u64; @@ -88,13 +88,16 @@ impl Spec for SendMultiSigSecpTxUseDepGroup { let sig = key.sign_recoverable(&message).expect("sign"); lock.extend_from_slice(&sig.serialize()); }); - let witness = witness.as_builder().lock(Some(Bytes::from(lock))).build(); + let witness = witness + .as_builder() + .lock(Some(Bytes::from(lock)).pack()) + .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .input(input) .output(output) - .output_data(packed::Bytes::default()) - .witness(witness.as_bytes()) + .output_data(Default::default()) + .witness(witness.as_bytes().pack()) .build(); info!("Send 1 multisig tx use dep group"); @@ -133,7 +136,7 @@ fn gen_multi_sign_script(keys: &[Privkey], threshold: u8, require_first_n: u8) - fn type_lock_script_code_hash() -> H256 { build_genesis_type_id_script(OUTPUT_INDEX_SECP256K1_BLAKE160_MULTISIG_ALL) .calc_script_hash() - .into() + .unpack() } fn new_block_assembler_config(lock_arg: Bytes, hash_type: ScriptHashType) -> BlockAssemblerConfig { diff --git a/test/src/specs/tx_pool/send_secp_tx.rs b/test/src/specs/tx_pool/send_secp_tx.rs index f8970c236c..7449c7454c 100644 --- a/test/src/specs/tx_pool/send_secp_tx.rs +++ b/test/src/specs/tx_pool/send_secp_tx.rs @@ -7,7 +7,7 @@ use ckb_logger::info; use ckb_types::{ bytes::Bytes, core::{capacity_bytes, Capacity, DepType, ScriptHashType, TransactionBuilder}, - packed::{self, CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, + packed::{CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, prelude::*, H256, }; @@ -47,10 +47,10 @@ impl Spec for SendSecpTxUseDepGroup { let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(node.always_success_script()) .build(); let input = CellInput::new(OutPoint::new(cellbase_hash, 0), 0); @@ -58,12 +58,12 @@ impl Spec for SendSecpTxUseDepGroup { .cell_dep(cell_dep.clone()) .input(input.clone()) .output(output.clone()) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); let tx_hash = tx.hash(); let witness = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let message = { @@ -78,14 +78,14 @@ impl Spec for SendSecpTxUseDepGroup { let sig = self.privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() - .lock(Some(Bytes::from(sig.serialize()))) + .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .input(input) .output(output) - .output_data(packed::Bytes::default()) - .witness(witness.as_bytes()) + .output_data(Default::default()) + .witness(witness.as_bytes().pack()) .build(); info!("Send 1 secp tx use dep group"); @@ -140,7 +140,7 @@ impl Spec for CheckTypical2In2OutTx { let cell_dep = CellDep::new_builder() .out_point(secp_out_point) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let input1 = { let block = node.get_tip_block(); @@ -154,16 +154,16 @@ impl Spec for CheckTypical2In2OutTx { CellInput::new(OutPoint::new(cellbase_hash, 0), 0) }; let lock = Script::new_builder() - .args(&self.lock_arg) - .code_hash(type_lock_script_code_hash()) - .hash_type(ScriptHashType::Type) + .args(self.lock_arg.pack()) + .code_hash(type_lock_script_code_hash().pack()) + .hash_type(ScriptHashType::Type.into()) .build(); let output1 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock.clone()) .build(); let output2 = CellOutput::new_builder() - .capacity(capacity_bytes!(100)) + .capacity(capacity_bytes!(100).pack()) .lock(lock) .build(); let tx = TransactionBuilder::default() @@ -172,13 +172,13 @@ impl Spec for CheckTypical2In2OutTx { .input(input2) .output(output1) .output(output2) - .output_data(packed::Bytes::default()) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) + .output_data(Default::default()) .build(); - let tx_hash: H256 = tx.hash().into(); + let tx_hash: H256 = tx.hash().unpack(); let witness = WitnessArgs::new_builder() - .lock(Some(Bytes::from(vec![0u8; 65]))) + .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let witness2 = Bytes::new(); @@ -197,19 +197,20 @@ impl Spec for CheckTypical2In2OutTx { let sig = self.privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() - .lock(Some(Bytes::from(sig.serialize()))) + .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); let tx = tx .as_advanced_builder() - .witness(witness.as_bytes()) - .witness(witness2) + .witness(witness.as_bytes().pack()) + .witness(witness2.pack()) .build(); info!("Send 1 secp tx use dep group"); node.rpc_client() .inner() .send_transaction(tx.data().into(), None) - .expect("should pass default outputs validator"); + .expect("should pass default outputs validator") + .pack(); node.mine(20); assert!(is_transaction_committed(node, &tx)); diff --git a/test/src/txo.rs b/test/src/txo.rs index 98bcc997ae..7d9868b6f4 100644 --- a/test/src/txo.rs +++ b/test/src/txo.rs @@ -1,5 +1,5 @@ use ckb_types::core::{Capacity, TransactionBuilder, TransactionView}; -use ckb_types::packed::{self, CellDep, CellInput, CellOutput, OutPoint, Script, ScriptOpt}; +use ckb_types::packed::{CellDep, CellInput, CellOutput, OutPoint, Script, ScriptOpt}; use ckb_types::prelude::*; use rand::{thread_rng, Rng}; use std::collections::HashMap; @@ -31,7 +31,7 @@ impl TXO { } pub fn capacity(&self) -> u64 { - self.output.capacity().into() + self.output.capacity().unpack() } pub fn lock(&self) -> Script { @@ -52,7 +52,7 @@ impl TXO { pub fn to_equivalent_output(&self) -> CellOutput { CellOutput::new_builder() .lock(self.lock()) - .capacity(self.capacity()) + .capacity(self.capacity().pack()) .build() } @@ -145,7 +145,7 @@ impl TXOSet { .cell_deps(cell_deps.clone()) .input(txo.to_input()) .output(txo.to_equivalent_output()) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build() }) .collect() @@ -161,18 +161,18 @@ impl TXOSet { self.iter() .map(|txo| { let maximal_capacity = txo.capacity(); - let minimal_capacity: u64 = txo.to_minimal_output().capacity().into(); + let minimal_capacity: u64 = txo.to_minimal_output().capacity().unpack(); let actual_capacity = rng.gen_range(minimal_capacity..=maximal_capacity); let output = txo .to_equivalent_output() .as_builder() - .capacity(actual_capacity) + .capacity(actual_capacity.pack()) .build(); TransactionBuilder::default() .cell_deps(cell_deps.clone()) .input(txo.to_input()) .output(output) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build() }) .collect() @@ -181,11 +181,11 @@ impl TXOSet { fn boom_to_minimals(&self) -> Vec { let mut input_capacity = self.total_capacity(); let minimal = self.iter().next().unwrap().to_minimal_output(); - let minimal_capacity: u64 = minimal.capacity().into(); + let minimal_capacity: u64 = minimal.capacity().unpack(); let mut outputs = Vec::new(); while outputs.len() < EXPLODE_LIMIT { if input_capacity < 2 * minimal_capacity || outputs.len() == EXPLODE_LIMIT { - outputs.push(minimal.as_builder().capacity(input_capacity).build()); + outputs.push(minimal.as_builder().capacity(input_capacity.pack()).build()); break; } else { input_capacity -= minimal_capacity; @@ -214,7 +214,7 @@ impl From<&TransactionView> for TXOSet { .map(move |(i, output)| { let out_point = OutPoint::new_builder() .tx_hash(tx_hash.clone()) - .index(i) + .index(i.pack()) .build(); TXO::new(out_point, output) }); diff --git a/test/src/util/cell.rs b/test/src/util/cell.rs index 37aaea9c03..78a2303235 100644 --- a/test/src/util/cell.rs +++ b/test/src/util/cell.rs @@ -102,6 +102,6 @@ pub fn as_output(cell: &CellMeta) -> CellOutput { CellOutput::new_builder() .lock(cell.cell_output.lock()) .type_(cell.cell_output.type_()) - .capacity(cell.capacity()) + .capacity(cell.capacity().pack()) .build() } diff --git a/test/src/util/mining.rs b/test/src/util/mining.rs index 17bd1ff87c..ebbf686522 100644 --- a/test/src/util/mining.rs +++ b/test/src/util/mining.rs @@ -147,7 +147,7 @@ impl Node { !template .transactions .iter() - .any(|tx| tx.hash == tx_hash.into()) + .any(|tx| tx.hash == tx_hash.unpack()) }); } diff --git a/test/src/util/transaction.rs b/test/src/util/transaction.rs index 230251d56c..35e640cd64 100644 --- a/test/src/util/transaction.rs +++ b/test/src/util/transaction.rs @@ -20,7 +20,7 @@ pub fn always_success_transaction(node: &Node, cell: &CellMeta) -> TransactionVi TransactionBuilder::default() .input(as_input(cell)) .output(as_output(cell)) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .cell_dep(node.always_success_cell_dep()) .build() } @@ -39,7 +39,7 @@ pub fn always_success_transactions_with_rand_data( (0..1600) .map(|_| rand::random::()) .collect::>() - .into() + .pack() }) .collect::>(), ) @@ -49,7 +49,7 @@ pub fn always_success_transactions_with_rand_data( pub fn send_tx(net: &Net, node: &Node, tx: TransactionView, cycles: u64) { let relay_tx = packed::RelayTransaction::new_builder() - .cycles(cycles) + .cycles(cycles.pack()) .transaction(tx.data()) .build(); @@ -71,7 +71,7 @@ pub fn relay_tx(net: &Net, node: &Node, tx: TransactionView, cycles: u64) { let tx_hashes_msg = packed::RelayMessage::new_builder() .set( packed::RelayTransactionHashes::new_builder() - .tx_hashes(vec![tx.hash()]) + .tx_hashes(vec![tx.hash()].pack()) .build(), ) .build(); @@ -85,7 +85,7 @@ pub fn relay_tx(net: &Net, node: &Node, tx: TransactionView, cycles: u64) { assert!(ret, "node should ask for tx"); let relay_tx = packed::RelayTransaction::new_builder() - .cycles(cycles) + .cycles(cycles.pack()) .transaction(tx.data()) .build(); diff --git a/test/src/utils.rs b/test/src/utils.rs index c566e874c9..57d9227ac9 100644 --- a/test/src/utils.rs +++ b/test/src/utils.rs @@ -5,7 +5,7 @@ use ckb_network::bytes::Bytes; use ckb_types::{ core::{BlockNumber, BlockView, EpochNumberWithFraction, HeaderView, TransactionView}, packed::{ - self, BlockFilterMessage, BlockTransactions, Byte32, CompactBlock, GetBlocks, RelayMessage, + BlockFilterMessage, BlockTransactions, Byte32, CompactBlock, GetBlocks, RelayMessage, RelayTransaction, RelayTransactionHashes, RelayTransactions, SendBlock, SendHeaders, SyncMessage, }, @@ -55,7 +55,7 @@ pub fn build_block_transactions(block: &BlockView) -> Bytes { .into_iter() .map(|view| view.data()) .skip(1) - .collect::>(), + .pack(), ) .build(); @@ -71,7 +71,13 @@ pub fn build_header(header: &HeaderView) -> Bytes { pub fn build_headers(headers: &[HeaderView]) -> Bytes { let send_headers = SendHeaders::new_builder() - .headers(headers.iter().map(|view| view.data()).collect::>()) + .headers( + headers + .iter() + .map(|view| view.data()) + .collect::>() + .pack(), + ) .build(); SyncMessage::new_builder() @@ -89,12 +95,7 @@ pub fn build_block(block: &BlockView) -> Bytes { pub fn build_get_blocks(hashes: &[Byte32]) -> Bytes { let get_blocks = GetBlocks::new_builder() - .block_hashes( - hashes - .iter() - .map(ToOwned::to_owned) - .collect::>(), - ) + .block_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); SyncMessage::new_builder() @@ -104,17 +105,14 @@ pub fn build_get_blocks(hashes: &[Byte32]) -> Bytes { } pub fn build_relay_txs(transactions: &[(TransactionView, u64)]) -> Bytes { - let transactions = transactions - .iter() - .map(|(tx, cycles)| { - RelayTransaction::new_builder() - .cycles(cycles) - .transaction(tx.data()) - .build() - }) - .collect::>(); + let transactions = transactions.iter().map(|(tx, cycles)| { + RelayTransaction::new_builder() + .cycles(cycles.pack()) + .transaction(tx.data()) + .build() + }); let txs = RelayTransactions::new_builder() - .transactions(transactions) + .transactions(transactions.pack()) .build(); RelayMessage::new_builder().set(txs).build().as_bytes() @@ -122,12 +120,7 @@ pub fn build_relay_txs(transactions: &[(TransactionView, u64)]) -> Bytes { pub fn build_relay_tx_hashes(hashes: &[Byte32]) -> Bytes { let content = RelayTransactionHashes::new_builder() - .tx_hashes( - hashes - .iter() - .map(ToOwned::to_owned) - .collect::>(), - ) + .tx_hashes(hashes.iter().map(ToOwned::to_owned).pack()) .build(); RelayMessage::new_builder().set(content).build().as_bytes() diff --git a/tx-pool/src/block_assembler/mod.rs b/tx-pool/src/block_assembler/mod.rs index dfa9ce3c02..81acca0951 100644 --- a/tx-pool/src/block_assembler/mod.rs +++ b/tx-pool/src/block_assembler/mod.rs @@ -459,9 +459,9 @@ impl BlockAssembler { ) -> CellbaseWitness { let hash_type: ScriptHashType = config.hash_type.clone().into(); let cellbase_lock = Script::new_builder() - .args(config.args.as_bytes()) - .code_hash(&config.code_hash) - .hash_type(hash_type) + .args(config.args.as_bytes().pack()) + .code_hash(config.code_hash.pack()) + .hash_type(hash_type.into()) .build(); let tip = snapshot.tip_header(); @@ -480,7 +480,7 @@ impl BlockAssembler { CellbaseWitness::new_builder() .lock(cellbase_lock) - .message(message) + .message(message.pack()) .build() } @@ -502,11 +502,11 @@ impl BlockAssembler { })?; let input = CellInput::new_cellbase_input(candidate_number); let output = CellOutput::new_builder() - .capacity(block_reward.total) + .capacity(block_reward.total.pack()) .lock(target_lock) .build(); - let witness = cellbase_witness.as_bytes(); + let witness = cellbase_witness.as_bytes().pack(); let no_finalization_target = candidate_number <= snapshot.consensus().finalization_delay_length(); let tx_builder = TransactionBuilder::default().input(input).witness(witness); @@ -536,7 +536,7 @@ impl BlockAssembler { .chain_root_mmr(tip_header.number()) .get_root() .map_err(|e| InternalErrorKind::MMR.other(e))?; - let bytes = chain_root.calc_mmr_hash().as_bytes().into(); + let bytes = chain_root.calc_mmr_hash().as_bytes().pack(); Ok(Some(bytes)) } else { Ok(None) @@ -564,28 +564,18 @@ impl BlockAssembler { let block = if let Some(extension) = extension_opt { packed::BlockV1::new_builder() .header(header) - .transactions(vec![cellbase]) - .uncles( - uncles - .iter() - .map(|u| u.data()) - .collect::>(), - ) - .proposals(proposals.cloned().collect::>()) + .transactions(vec![cellbase].pack()) + .uncles(uncles.iter().map(|u| u.data()).pack()) + .proposals(proposals.cloned().collect::>().pack()) .extension(extension) .build() .as_v0() } else { packed::Block::new_builder() .header(header) - .transactions(vec![cellbase]) - .uncles( - uncles - .iter() - .map(|u| u.data()) - .collect::>(), - ) - .proposals(proposals.cloned().collect::>()) + .transactions(vec![cellbase].pack()) + .uncles(uncles.iter().map(|u| u.data()).pack()) + .proposals(proposals.cloned().collect::>().pack()) .build() }; block.serialized_size_without_uncle_proposals() @@ -738,7 +728,7 @@ impl<'a> From<&'a BlockTemplate> for JsonBlockTemplate { compact_target: template.compact_target.into(), number: template.number.into(), epoch: template.epoch.into(), - parent_hash: (&template.parent_hash).into(), + parent_hash: template.parent_hash.unpack(), cycles_limit: template.cycles_limit.into(), bytes_limit: template.bytes_limit.into(), uncles_count_limit: u64::from(template.uncles_count_limit).into(), @@ -928,7 +918,7 @@ impl BlockTemplateBuilder { pub(crate) fn uncle_to_template(uncle: &UncleBlockView) -> UncleTemplate { UncleTemplate { - hash: uncle.hash().into(), + hash: uncle.hash().unpack(), required: false, proposals: uncle .data() @@ -942,7 +932,7 @@ pub(crate) fn uncle_to_template(uncle: &UncleBlockView) -> UncleTemplate { pub(crate) fn tx_entry_to_template(entry: &TxEntry) -> TransactionTemplate { TransactionTemplate { - hash: entry.transaction().hash().into(), + hash: entry.transaction().hash().unpack(), required: false, // unimplemented cycles: Some(entry.cycles.into()), depends: None, // unimplemented @@ -952,7 +942,7 @@ pub(crate) fn tx_entry_to_template(entry: &TxEntry) -> TransactionTemplate { pub(crate) fn cellbase_to_template(tx: &TransactionView) -> CellbaseTemplate { CellbaseTemplate { - hash: tx.hash().into(), + hash: tx.hash().unpack(), cycles: None, data: tx.data().into(), } diff --git a/tx-pool/src/block_assembler/tests.rs b/tx-pool/src/block_assembler/tests.rs index 4b9f15a5fd..6d39933ecb 100644 --- a/tx-pool/src/block_assembler/tests.rs +++ b/tx-pool/src/block_assembler/tests.rs @@ -1,4 +1,7 @@ -use ckb_types::core::{BlockBuilder, BlockNumber, EpochNumberWithFraction}; +use ckb_types::{ + core::{BlockBuilder, BlockNumber, EpochNumberWithFraction}, + prelude::*, +}; use crate::block_assembler::candidate_uncles::{ CandidateUncles, MAX_CANDIDATE_UNCLES, MAX_PER_HEIGHT, @@ -27,12 +30,8 @@ fn test_candidate_uncles_max_size() { for i in 0..(MAX_CANDIDATE_UNCLES + 3) { let number = i as BlockNumber; let block = BlockBuilder::default() - .number(number) - .epoch(EpochNumberWithFraction::new( - number / 1000, - number % 1000, - 10000, - )) + .number(number.pack()) + .epoch(EpochNumberWithFraction::new(number / 1000, number % 1000, 10000).pack()) .build() .as_uncle(); blocks.push(block); @@ -61,7 +60,7 @@ fn test_candidate_uncles_max_per_height() { let mut blocks = Vec::new(); for i in 0..(MAX_PER_HEIGHT + 3) { let block = BlockBuilder::default() - .timestamp(i as u64) + .timestamp((i as u64).pack()) .build() .as_uncle(); blocks.push(block); diff --git a/tx-pool/src/component/pool_map.rs b/tx-pool/src/component/pool_map.rs index b62f55d4c6..575452785c 100644 --- a/tx-pool/src/component/pool_map.rs +++ b/tx-pool/src/component/pool_map.rs @@ -11,6 +11,7 @@ use ckb_logger::{debug, error, trace}; use ckb_types::core::error::OutPointError; use ckb_types::core::Cycle; use ckb_types::packed::OutPoint; +use ckb_types::prelude::*; use ckb_types::{ bytes::Bytes, core::TransactionView, @@ -185,7 +186,7 @@ impl PoolMap { .and_then(|entry| { entry .transaction() - .output_with_data(out_point.index().into()) + .output_with_data(out_point.index().unpack()) }) } diff --git a/tx-pool/src/component/tests/chunk.rs b/tx-pool/src/component/tests/chunk.rs index 9f4f2f1a31..39df2dc1cd 100644 --- a/tx-pool/src/component/tests/chunk.rs +++ b/tx-pool/src/component/tests/chunk.rs @@ -2,6 +2,7 @@ use crate::component::tests::util::build_tx; use crate::component::verify_queue::{Entry, VerifyQueue}; use ckb_network::SessionId; use ckb_types::core::TransactionBuilder; +use ckb_types::prelude::Pack; use ckb_types::H256; use tokio::select; use tokio::sync::watch; @@ -94,22 +95,22 @@ async fn test_verify_different_cycles() { let remote = |cycles| Some((cycles, SessionId::default())); - let tx0 = build_tx(vec![(&H256([0; 32]).into(), 0)], 1); + let tx0 = build_tx(vec![(&H256([0; 32]).pack(), 0)], 1); assert!(queue.add_tx(tx0.clone(), remote(1001)).unwrap()); sleep(std::time::Duration::from_millis(100)).await; - let tx1 = build_tx(vec![(&H256([1; 32]).into(), 0)], 1); + let tx1 = build_tx(vec![(&H256([1; 32]).pack(), 0)], 1); assert!(queue .add_tx(tx1.clone(), remote(MAX_TX_VERIFY_CYCLES + 1)) .unwrap()); sleep(std::time::Duration::from_millis(100)).await; - let tx2 = build_tx(vec![(&H256([2; 32]).into(), 0)], 1); + let tx2 = build_tx(vec![(&H256([2; 32]).pack(), 0)], 1); assert!(queue.add_tx(tx2.clone(), remote(1001)).unwrap()); sleep(std::time::Duration::from_millis(100)).await; // now queue should be sorted by time (tx1, tx2) - let tx3 = build_tx(vec![(&H256([3; 32]).into(), 0)], 1); + let tx3 = build_tx(vec![(&H256([3; 32]).pack(), 0)], 1); assert!(queue.add_tx(tx3.clone(), remote(1001)).unwrap()); sleep(std::time::Duration::from_millis(100)).await; diff --git a/tx-pool/src/component/tests/pending.rs b/tx-pool/src/component/tests/pending.rs index bcef42ef01..e262248354 100644 --- a/tx-pool/src/component/tests/pending.rs +++ b/tx-pool/src/component/tests/pending.rs @@ -8,7 +8,7 @@ use crate::component::{ }; use ckb_types::core::Capacity; use ckb_types::packed::OutPoint; -use ckb_types::{h256, packed::Byte32}; +use ckb_types::{h256, packed::Byte32, prelude::*}; use std::collections::HashSet; use std::time::Duration; @@ -18,7 +18,7 @@ fn test_basic() { assert_eq!(pool.size(), 0); let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&Byte32::zero(), 2)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 2)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 2)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -51,21 +51,21 @@ fn test_basic() { #[test] fn test_resolve_conflict() { let mut pool = PoolMap::new(100); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let tx4 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x1").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x1").pack(), 1)], 3, ); - let tx5 = build_tx(vec![(&h256!("0x5").into(), 1)], 3); + let tx5 = build_tx(vec![(&h256!("0x5").pack(), 1)], 3); let entry1 = TxEntry::dummy_resolve(tx1, MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); let entry2 = TxEntry::dummy_resolve(tx2, MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -114,9 +114,9 @@ fn test_resolve_conflict_descendants() { fn test_resolve_conflict_header_dep() { let mut pool = PoolMap::new(1000); - let header: Byte32 = h256!("0x1").into(); + let header: Byte32 = h256!("0x1").pack(); let tx = build_tx_with_header_dep( - vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], + vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], vec![header.clone()], 1, ); @@ -143,9 +143,9 @@ fn test_resolve_conflict_header_dep() { #[test] fn test_remove_entry() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); - let header: Byte32 = h256!("0x1").into(); - let tx2 = build_tx_with_header_dep(vec![(&h256!("0x2").into(), 1)], vec![header], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); + let header: Byte32 = h256!("0x1").pack(); + let tx2 = build_tx_with_header_dep(vec![(&h256!("0x2").pack(), 1)], vec![header], 1); let entry1 = TxEntry::dummy_resolve(tx1.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); let entry2 = TxEntry::dummy_resolve(tx2.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -165,14 +165,14 @@ fn test_remove_entry() { #[test] fn test_get_proposals() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -214,14 +214,14 @@ fn test_get_proposals() { #[test] fn test_get_proposals_with_high_score() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -258,8 +258,8 @@ fn test_get_proposals_with_high_score() { #[test] fn test_edges() { - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); - let tx2 = build_tx(vec![(&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); + let tx2 = build_tx(vec![(&h256!("0x1").pack(), 1)], 1); let short_id1 = tx1.proposal_short_id(); let short_id2 = tx2.proposal_short_id(); @@ -277,14 +277,14 @@ fn test_edges() { #[test] fn test_pool_evict() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -315,14 +315,14 @@ fn test_pool_evict() { #[test] fn test_pool_min_weight_evict() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), 2, Capacity::shannons(100), 2); @@ -353,14 +353,14 @@ fn test_pool_min_weight_evict() { #[test] fn test_pool_max_size_evict() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 1)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 1)], 3, ); let tx3 = build_tx_with_dep( - vec![(&h256!("0x4").into(), 1)], - vec![(&h256!("0x5").into(), 1)], + vec![(&h256!("0x4").pack(), 1)], + vec![(&h256!("0x5").pack(), 1)], 3, ); let entry1 = TxEntry::dummy_resolve(tx1.clone(), 2, Capacity::shannons(100), 3); @@ -391,9 +391,9 @@ fn test_pool_max_size_evict() { #[test] fn test_pool_min_descendants_evict() { let mut pool = PoolMap::new(1000); - let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], 1); - let tx2 = build_tx(vec![(&tx1.hash(), 1), (&h256!("0x3").into(), 1)], 3); - let tx3 = build_tx_with_dep(vec![(&tx2.hash(), 1)], vec![(&h256!("0x5").into(), 1)], 3); + let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], 1); + let tx2 = build_tx(vec![(&tx1.hash(), 1), (&h256!("0x3").pack(), 1)], 3); + let tx3 = build_tx_with_dep(vec![(&tx2.hash(), 1)], vec![(&h256!("0x5").pack(), 1)], 3); let entry1 = TxEntry::dummy_resolve(tx1.clone(), 2, Capacity::shannons(100), 1); std::thread::sleep(Duration::from_millis(1)); let entry2 = TxEntry::dummy_resolve(tx2.clone(), 2, Capacity::shannons(100), 1); diff --git a/tx-pool/src/component/tests/proposed.rs b/tx-pool/src/component/tests/proposed.rs index ecac84398b..236d4b10a9 100644 --- a/tx-pool/src/component/tests/proposed.rs +++ b/tx-pool/src/component/tests/proposed.rs @@ -4,7 +4,7 @@ use crate::component::tests::util::{ MOCK_CYCLES, MOCK_FEE, MOCK_SIZE, }; use ckb_types::core::{capacity_bytes, ScriptHashType}; -use ckb_types::packed::{self, CellOutputBuilder, ScriptBuilder}; +use ckb_types::packed::{CellOutputBuilder, ScriptBuilder}; use ckb_types::H256; use std::time::Instant; @@ -197,7 +197,7 @@ fn test_add_entry_from_detached() { fn test_add_roots() { let tx1 = build_tx(vec![(&Byte32::zero(), 1), (&Byte32::zero(), 2)], 1); let tx2 = build_tx( - vec![(&h256!("0x2").into(), 1), (&h256!("0x3").into(), 2)], + vec![(&h256!("0x2").pack(), 1), (&h256!("0x3").pack(), 2)], 3, ); @@ -517,36 +517,36 @@ fn test_get_ancestors() { #[test] fn test_dep_group() { - let tx1 = build_tx(vec![(&h256!("0x1").into(), 0)], 1); + let tx1 = build_tx(vec![(&h256!("0x1").pack(), 0)], 1); let tx1_out_point = OutPoint::new(tx1.hash(), 0); // Dep group cell - let tx2_data = Into::::into(vec![tx1_out_point.clone()]).as_bytes(); + let tx2_data = vec![tx1_out_point.clone()].pack().as_bytes(); let tx2 = TransactionBuilder::default() - .input(CellInput::new(OutPoint::new(h256!("0x2").into(), 0), 0)) + .input(CellInput::new(OutPoint::new(h256!("0x2").pack(), 0), 0)) .output( CellOutput::new_builder() - .capacity(Capacity::bytes(1000).unwrap()) + .capacity(Capacity::bytes(1000).unwrap().pack()) .build(), ) - .output_data(&tx2_data) + .output_data(tx2_data.pack()) .build(); let tx2_out_point = OutPoint::new(tx2.hash(), 0); // Transaction use dep group let dep = CellDep::new_builder() .out_point(tx2_out_point.clone()) - .dep_type(DepType::DepGroup) + .dep_type(DepType::DepGroup.into()) .build(); let tx3 = TransactionBuilder::default() .cell_dep(dep) - .input(CellInput::new(OutPoint::new(h256!("0x3").into(), 0), 0)) + .input(CellInput::new(OutPoint::new(h256!("0x3").pack(), 0), 0)) .output( CellOutput::new_builder() - .capacity(Capacity::bytes(3).unwrap()) + .capacity(Capacity::bytes(3).unwrap().pack()) .build(), ) - .output_data(Bytes::new()) + .output_data(Bytes::new().pack()) .build(); let tx3_out_point = OutPoint::new(tx3.hash(), 0); @@ -590,9 +590,9 @@ fn test_dep_group() { fn test_resolve_conflict_header_dep() { let mut pool = PoolMap::new(DEFAULT_MAX_ANCESTORS_COUNT); - let header: Byte32 = h256!("0x1").into(); + let header: Byte32 = h256!("0x1").pack(); let tx = build_tx_with_header_dep( - vec![(&Byte32::zero(), 1), (&h256!("0x1").into(), 1)], + vec![(&Byte32::zero(), 1), (&h256!("0x1").pack(), 1)], vec![header.clone()], 1, ); @@ -672,12 +672,12 @@ fn test_max_ancestors_with_dep() { let mut pool = PoolMap::new(1); let tx1 = build_tx_with_dep( vec![(&Byte32::zero(), 0)], - vec![(&h256!("0x1").into(), 0)], + vec![(&h256!("0x1").pack(), 0)], 1, ); let tx1_id = tx1.proposal_short_id(); let tx1_hash = tx1.hash(); - let tx2 = build_tx_with_dep(vec![(&tx1_hash, 0)], vec![(&h256!("0x2").into(), 0)], 1); + let tx2 = build_tx_with_dep(vec![(&tx1_hash, 0)], vec![(&h256!("0x2").pack(), 0)], 1); let entry1 = TxEntry::dummy_resolve(tx1, MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); let entry2 = TxEntry::dummy_resolve(tx2, MOCK_CYCLES, MOCK_FEE, MOCK_SIZE); @@ -687,7 +687,7 @@ fn test_max_ancestors_with_dep() { assert!(pool .edges .deps - .contains_key(&OutPoint::new(h256!("0x1").into(), 0))); + .contains_key(&OutPoint::new(h256!("0x1").pack(), 0))); assert!(pool.calc_descendants(&tx1_id).is_empty()); assert_eq!(pool.edges.inputs_len(), 1); @@ -716,12 +716,12 @@ fn test_container_bench_add_limits() { .previous_output( OutPoint::new_builder() .tx_hash(prev_tx.transaction().hash()) - .index(0u32) + .index(0u32.pack()) .build(), ) .build(), ) - .witness(Bytes::new()) + .witness(Bytes::new().pack()) .build(), rng.gen_range(0..1000), Capacity::shannons(200), @@ -748,26 +748,26 @@ fn test_pool_map_bench() { let mut time_spend = vec![]; for i in 0..20000 { let lock_script1 = ScriptBuilder::default() - .code_hash(H256(rand::random())) - .hash_type(ScriptHashType::Data) - .args(Bytes::from(b"lock_script1".to_vec())) + .code_hash(H256(rand::random()).pack()) + .hash_type(ScriptHashType::Data.into()) + .args(Bytes::from(b"lock_script1".to_vec()).pack()) .build(); let type_script1 = ScriptBuilder::default() - .code_hash(H256(rand::random())) - .hash_type(ScriptHashType::Data) - .args(Bytes::from(b"type_script1".to_vec())) + .code_hash(H256(rand::random()).pack()) + .hash_type(ScriptHashType::Data.into()) + .args(Bytes::from(b"type_script1".to_vec()).pack()) .build(); let tx = TransactionBuilder::default() .output( CellOutputBuilder::default() - .capacity(capacity_bytes!(1000)) + .capacity(capacity_bytes!(1000).pack()) .lock(lock_script1) - .type_(Some(type_script1)) + .type_(Some(type_script1).pack()) .build(), ) - .output_data(packed::Bytes::default()) + .output_data(Default::default()) .build(); let entry = TxEntry::dummy_resolve( diff --git a/tx-pool/src/component/tests/score_key.rs b/tx-pool/src/component/tests/score_key.rs index 0155fa710c..c12cc7426c 100644 --- a/tx-pool/src/component/tests/score_key.rs +++ b/tx-pool/src/component/tests/score_key.rs @@ -111,12 +111,12 @@ fn test_remove_entry() { .previous_output( OutPoint::new_builder() .tx_hash(tx1.transaction().hash()) - .index(0u32) + .index(0u32.pack()) .build(), ) .build(), ) - .witness(Bytes::new()) + .witness(Bytes::new().pack()) .build(), 200, Capacity::shannons(200), @@ -129,12 +129,12 @@ fn test_remove_entry() { .previous_output( OutPoint::new_builder() .tx_hash(tx2.transaction().hash()) - .index(0u32) + .index(0u32.pack()) .build(), ) .build(), ) - .witness(Bytes::new()) + .witness(Bytes::new().pack()) .build(), 200, Capacity::shannons(200), @@ -184,12 +184,12 @@ fn test_remove_entry_and_descendants() { .previous_output( OutPoint::new_builder() .tx_hash(tx1.transaction().hash()) - .index(0u32) + .index(0u32.pack()) .build(), ) .build(), ) - .witness(Bytes::new()) + .witness(Bytes::new().pack()) .build(), 200, Capacity::shannons(200), @@ -202,12 +202,12 @@ fn test_remove_entry_and_descendants() { .previous_output( OutPoint::new_builder() .tx_hash(tx2.transaction().hash()) - .index(0u32) + .index(0u32.pack()) .build(), ) .build(), ) - .witness(Bytes::new()) + .witness(Bytes::new().pack()) .build(), 200, Capacity::shannons(200), diff --git a/tx-pool/src/component/tests/util.rs b/tx-pool/src/component/tests/util.rs index d55d37262e..32d4563d61 100644 --- a/tx-pool/src/component/tests/util.rs +++ b/tx-pool/src/component/tests/util.rs @@ -19,10 +19,10 @@ pub(crate) fn build_tx(inputs: Vec<(&Byte32, u32)>, outputs_len: usize) -> Trans ) .outputs((0..outputs_len).map(|i| { CellOutput::new_builder() - .capacity(Capacity::bytes(i + 1).unwrap()) + .capacity(Capacity::bytes(i + 1).unwrap().pack()) .build() })) - .outputs_data((0..outputs_len).map(|_| Bytes::new().into())) + .outputs_data((0..outputs_len).map(|_| Bytes::new().pack())) .build() } @@ -44,10 +44,10 @@ pub(crate) fn build_tx_with_dep( })) .outputs((0..outputs_len).map(|i| { CellOutput::new_builder() - .capacity(Capacity::bytes(i + 1).unwrap()) + .capacity(Capacity::bytes(i + 1).unwrap().pack()) .build() })) - .outputs_data((0..outputs_len).map(|_| Bytes::new().into())) + .outputs_data((0..outputs_len).map(|_| Bytes::new().pack())) .build() } @@ -65,9 +65,9 @@ pub(crate) fn build_tx_with_header_dep( .set_header_deps(header_deps) .outputs((0..outputs_len).map(|i| { CellOutput::new_builder() - .capacity(Capacity::bytes(i + 1).unwrap()) + .capacity(Capacity::bytes(i + 1).unwrap().pack()) .build() })) - .outputs_data((0..outputs_len).map(|_| Bytes::new().into())) + .outputs_data((0..outputs_len).map(|_| Bytes::new().pack())) .build() } diff --git a/util/dao/src/lib.rs b/util/dao/src/lib.rs index eb56e7df3e..ebb550871c 100644 --- a/util/dao/src/lib.rs +++ b/util/dao/src/lib.rs @@ -197,7 +197,7 @@ impl<'a, DL: CellDataProvider + EpochProvider + HeaderProvider> DaoCalculator<'a let tx_input_capacities = rtx.resolved_inputs.iter().try_fold( Capacity::zero(), |tx_capacities, cell_meta| { - let output_capacity: Capacity = cell_meta.cell_output.capacity().into(); + let output_capacity: Capacity = cell_meta.cell_output.capacity().unpack(); tx_capacities.safe_add(output_capacity) }, )?; @@ -248,11 +248,14 @@ impl<'a, DL: CellDataProvider + EpochProvider + HeaderProvider> DaoCalculator<'a .ok_or(DaoError::InvalidOutPoint) .and_then(|witness_data| { // dao contract stores header deps index as u64 in the input_type field of WitnessArgs - let witness = - WitnessArgs::from_slice(&Into::::into(witness_data)) - .map_err(|_| DaoError::InvalidDaoFormat)?; - let header_deps_index_data: Option = - witness.input_type().to_opt().map(|witness| witness.into()); + let witness = WitnessArgs::from_slice(&Unpack::::unpack( + &witness_data, + )) + .map_err(|_| DaoError::InvalidDaoFormat)?; + let header_deps_index_data: Option = witness + .input_type() + .to_opt() + .map(|witness| witness.unpack()); if header_deps_index_data.is_none() || header_deps_index_data.clone().map(|data| data.len()) != Some(8) @@ -275,7 +278,7 @@ impl<'a, DL: CellDataProvider + EpochProvider + HeaderProvider> DaoCalculator<'a withdrawing_header_hash, ) } else { - Ok(output.capacity().into()) + Ok(output.capacity().unpack()) } }; capacity.and_then(|c| c.safe_add(capacities).map_err(Into::into)) @@ -307,7 +310,7 @@ impl<'a, DL: CellDataProvider + EpochProvider + HeaderProvider> DaoCalculator<'a let (withdrawing_ar, _, _, _) = extract_dao_data(withdrawing_header.dao()); let occupied_capacity = output.occupied_capacity(output_data_capacity)?; - let output_capacity: Capacity = output.capacity().into(); + let output_capacity: Capacity = output.capacity().unpack(); let counted_capacity = output_capacity.safe_sub(occupied_capacity)?; let withdraw_counted_capacity = u128::from(counted_capacity.as_u64()) * u128::from(withdrawing_ar) @@ -330,7 +333,7 @@ pub fn modified_occupied_capacity( && tx_info.is_cellbase() && cell_meta.cell_output.lock().args().raw_data() == consensus.satoshi_pubkey_hash.0[..] { - return Into::::into(&cell_meta.cell_output.capacity()) + return Unpack::::unpack(&cell_meta.cell_output.capacity()) .safe_mul_ratio(consensus.satoshi_cell_occupied_ratio); } } diff --git a/util/dao/src/tests.rs b/util/dao/src/tests.rs index 7ac4ecb24f..bbb4c2cf36 100644 --- a/util/dao/src/tests.rs +++ b/util/dao/src/tests.rs @@ -40,12 +40,12 @@ fn prepare_store( .base_block_reward(Capacity::shannons(50_000_000_000)) .remainder_reward(Capacity::shannons(1_000_128)) .previous_epoch_hash_rate(U256::one()) - .last_block_hash_in_previous_epoch(h256!("0x1").into()) + .last_block_hash_in_previous_epoch(h256!("0x1").pack()) .start_number(epoch_start.unwrap_or_else(|| parent.number() - 1000)) .length(2091) .compact_target(DIFF_TWO) .build(); - let epoch_hash = h256!("0x123455").into(); + let epoch_hash = h256!("0x123455").pack(); txn.insert_block_epoch_index(&parent.hash(), &epoch_hash) .unwrap(); @@ -63,8 +63,8 @@ fn check_dao_data_calculation() { let parent_number = 12345; let epoch = EpochNumberWithFraction::new(12, 345, 1000); let parent_header = HeaderBuilder::default() - .number(parent_number) - .epoch(epoch) + .number(parent_number.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Capacity::shannons(500_000_000_123_000), @@ -95,7 +95,7 @@ fn check_initial_dao_data_calculation() { let parent_number = 0; let parent_header = HeaderBuilder::default() - .number(parent_number) + .number(parent_number.pack()) .dao(pack_dao_data( 10_000_000_000_000_000, Capacity::shannons(500_000_000_000_000), @@ -127,8 +127,8 @@ fn check_first_epoch_block_dao_data_calculation() { let parent_number = 12340; let epoch = EpochNumberWithFraction::new(12, 340, 1000); let parent_header = HeaderBuilder::default() - .number(parent_number) - .epoch(epoch) + .number(parent_number.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Capacity::shannons(500_000_000_123_000), @@ -160,8 +160,8 @@ fn check_dao_data_calculation_overflows() { let parent_number = 12345; let epoch = EpochNumberWithFraction::new(12, 345, 1000); let parent_header = HeaderBuilder::default() - .number(parent_number) - .epoch(epoch) + .number(parent_number.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Capacity::shannons(18_446_744_073_709_000_000), @@ -183,8 +183,8 @@ fn check_dao_data_calculation_with_transactions() { let parent_number = 12345; let epoch = EpochNumberWithFraction::new(12, 345, 1000); let parent_header = HeaderBuilder::default() - .number(parent_number) - .epoch(epoch) + .number(parent_number.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Capacity::shannons(500_000_000_123_000), @@ -196,16 +196,16 @@ fn check_dao_data_calculation_with_transactions() { let (_tmp_dir, store, parent_header) = prepare_store(&parent_header, None); let input_cell_data = Bytes::from("abcde"); let input_cell = CellOutput::new_builder() - .capacity(capacity_bytes!(10000)) + .capacity(capacity_bytes!(10000).pack()) .build(); let output_cell_data = Bytes::from("abcde12345"); let output_cell = CellOutput::new_builder() - .capacity(capacity_bytes!(20000)) + .capacity(capacity_bytes!(20000).pack()) .build(); let tx = TransactionBuilder::default() .output(output_cell) - .output_data(output_cell_data) + .output_data(output_cell_data.pack()) .build(); let rtx = ResolvedTransaction { transaction: tx, @@ -235,16 +235,16 @@ fn check_dao_data_calculation_with_transactions() { fn check_withdraw_calculation() { let data = Bytes::from(vec![1; 10]); let output = CellOutput::new_builder() - .capacity(capacity_bytes!(1000000)) + .capacity(capacity_bytes!(1000000).pack()) .build(); let tx = TransactionBuilder::default() .output(output.clone()) - .output_data(&data) + .output_data(data.pack()) .build(); let epoch = EpochNumberWithFraction::new(1, 100, 1000); let deposit_header = HeaderBuilder::default() - .number(100) - .epoch(epoch) + .number(100.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Default::default(), @@ -259,8 +259,8 @@ fn check_withdraw_calculation() { let epoch = EpochNumberWithFraction::new(1, 200, 1000); let withdrawing_header = HeaderBuilder::default() - .number(200) - .epoch(epoch) + .number(200.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_001_123_456, Default::default(), @@ -295,13 +295,13 @@ fn check_withdraw_calculation() { #[test] fn check_withdraw_calculation_overflows() { let output = CellOutput::new_builder() - .capacity(Capacity::shannons(18_446_744_073_709_550_000)) + .capacity(Capacity::shannons(18_446_744_073_709_550_000).pack()) .build(); let tx = TransactionBuilder::default().output(output.clone()).build(); let epoch = EpochNumberWithFraction::new(1, 100, 1000); let deposit_header = HeaderBuilder::default() - .number(100) - .epoch(epoch) + .number(100.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_000_123_456, Default::default(), @@ -316,8 +316,8 @@ fn check_withdraw_calculation_overflows() { let epoch = EpochNumberWithFraction::new(1, 200, 1000); let withdrawing_header = HeaderBuilder::default() - .number(200) - .epoch(epoch) + .number(200.pack()) + .epoch(epoch.pack()) .dao(pack_dao_data( 10_000_000_001_123_456, Default::default(), diff --git a/util/dao/utils/src/lib.rs b/util/dao/utils/src/lib.rs index ef2da02c14..3e67098a43 100644 --- a/util/dao/utils/src/lib.rs +++ b/util/dao/utils/src/lib.rs @@ -52,7 +52,7 @@ pub fn genesis_dao_data_with_satoshi_gift( .enumerate() .filter(|(index, _)| !dead_cells.contains(&OutPoint::new(tx.hash(), *index as u32))) .try_fold(Capacity::zero(), |capacity, (_, output)| { - let cap: Capacity = output.capacity().into(); + let cap: Capacity = output.capacity().unpack(); capacity.safe_add(cap) })?; let u = tx @@ -64,7 +64,7 @@ pub fn genesis_dao_data_with_satoshi_gift( let occupied_capacity = if tx_index == 0 && output.lock().args().raw_data() == satoshi_pubkey_hash.0[..] { - Into::::into(&output.capacity()) + Unpack::::unpack(&output.capacity()) .safe_mul_ratio(satoshi_cell_occupied_ratio) } else { Capacity::bytes(data.len()).and_then(|c| output.occupied_capacity(c)) @@ -128,6 +128,7 @@ mod tests { pub use ckb_types::core::Capacity; pub use ckb_types::h256; pub use ckb_types::packed::Byte32; + pub use ckb_types::prelude::Pack; #[test] #[allow(clippy::unreadable_literal)] @@ -159,7 +160,7 @@ mod tests { ), ]; for (dao_h256, ar, c, s, u) in cases { - let dao_byte32: Byte32 = dao_h256.into(); + let dao_byte32: Byte32 = dao_h256.pack(); assert_eq!((ar, c, s, u), extract_dao_data(dao_byte32.clone())); assert_eq!(dao_byte32, pack_dao_data(ar, c, s, u,)); } diff --git a/util/fixed-hash/core/src/std_str.rs b/util/fixed-hash/core/src/std_str.rs index 664298d50c..01ee940cc5 100644 --- a/util/fixed-hash/core/src/std_str.rs +++ b/util/fixed-hash/core/src/std_str.rs @@ -1,6 +1,6 @@ use crate::{error::FromStrError, H160, H256, H512, H520}; -pub(crate) const DICT_HEX_ERROR: u8 = u8::MAX; +pub(crate) const DICT_HEX_ERROR: u8 = u8::max_value(); pub(crate) static DICT_HEX_LO: [u8; 256] = { const ____: u8 = DICT_HEX_ERROR; [ diff --git a/util/gen-types/src/conversion/blockchain/mod.rs b/util/gen-types/src/conversion/blockchain/mod.rs index e400ed16d7..b80804fc09 100644 --- a/util/gen-types/src/conversion/blockchain/mod.rs +++ b/util/gen-types/src/conversion/blockchain/mod.rs @@ -9,12 +9,6 @@ impl Pack for [u8; 32] { } } -impl From<&[u8; 32]> for packed::Byte32 { - fn from(value: &[u8; 32]) -> Self { - packed::Byte32::from_slice(&value[..]).expect("impossible: fail to pack [u8; 32]") - } -} - impl<'r> Unpack<[u8; 32]> for packed::Byte32Reader<'r> { fn unpack(&self) -> [u8; 32] { let mut b = [0u8; 32]; @@ -24,14 +18,6 @@ impl<'r> Unpack<[u8; 32]> for packed::Byte32Reader<'r> { } impl_conversion_for_entity_unpack!([u8; 32], Byte32); -impl<'r> From> for [u8; 32] { - fn from(value: packed::Byte32Reader<'r>) -> [u8; 32] { - let mut b = [0u8; 32]; - b.copy_from_slice(value.raw_data()); - b - } -} - impl Pack for [u8; 10] { fn pack(&self) -> packed::ProposalShortId { packed::ProposalShortId::from_slice(&self[..]) @@ -48,14 +34,6 @@ impl<'r> Unpack<[u8; 10]> for packed::ProposalShortIdReader<'r> { } impl_conversion_for_entity_unpack!([u8; 10], ProposalShortId); -impl<'r> From> for [u8; 10] { - fn from(value: packed::ProposalShortIdReader<'r>) -> [u8; 10] { - let mut b = [0u8; 10]; - b.copy_from_slice(value.raw_data()); - b - } -} - impl Pack for Bytes { fn pack(&self) -> packed::Bytes { let len = (self.len() as u32).to_le_bytes(); @@ -66,46 +44,18 @@ impl Pack for Bytes { } } -impl From<&Bytes> for packed::Bytes { - fn from(value: &Bytes) -> Self { - let len = (value.len() as u32).to_le_bytes(); - let mut v = Vec::with_capacity(4 + value.len()); - v.extend_from_slice(&len[..]); - v.extend_from_slice(&value[..]); - packed::Bytes::new_unchecked(v.into()) - } -} - -impl From for packed::Bytes { - fn from(value: Bytes) -> Self { - (&value).into() - } -} - impl<'r> Unpack for packed::BytesReader<'r> { fn unpack(&self) -> Bytes { Bytes::from(self.raw_data().to_owned()) } } -impl<'r> From> for Bytes { - fn from(value: packed::BytesReader<'r>) -> Bytes { - Bytes::from(value.raw_data().to_owned()) - } -} - impl Unpack for packed::Bytes { fn unpack(&self) -> Bytes { self.raw_data() } } -impl From for Bytes { - fn from(value: packed::Bytes) -> Bytes { - value.raw_data() - } -} - impl_conversion_for_vector!(Bytes, BytesVec, BytesVecReader); impl_conversion_for_packed_optional_pack!(Byte32, Byte32Opt); impl_conversion_for_packed_optional_pack!(CellOutput, CellOutputOpt); @@ -120,8 +70,3 @@ impl_conversion_for_packed_iterator_pack!(CellInput, CellInputVec); impl_conversion_for_packed_iterator_pack!(UncleBlock, UncleBlockVec); impl_conversion_for_packed_iterator_pack!(Header, HeaderVec); impl_conversion_for_packed_iterator_pack!(Byte32, Byte32Vec); - -impl_conversion_for_vector_from_into!(Bytes, BytesVec, BytesVecReader); -impl_conversion_for_packed_optional_from!(Byte32, Byte32Opt); -impl_conversion_for_packed_optional_from!(CellOutput, CellOutputOpt); -impl_conversion_for_packed_optional_from!(Script, ScriptOpt); diff --git a/util/gen-types/src/conversion/blockchain/std_env.rs b/util/gen-types/src/conversion/blockchain/std_env.rs index 696fe77123..5fd0f40751 100644 --- a/util/gen-types/src/conversion/blockchain/std_env.rs +++ b/util/gen-types/src/conversion/blockchain/std_env.rs @@ -10,18 +10,6 @@ impl Pack for Capacity { } } -impl From for packed::Uint64 { - fn from(value: Capacity) -> Self { - (&value).into() - } -} - -impl From<&Capacity> for packed::Uint64 { - fn from(value: &Capacity) -> Self { - value.as_u64().into() - } -} - impl<'r> Unpack for packed::Uint64Reader<'r> { fn unpack(&self) -> Capacity { Capacity::shannons(self.unpack()) @@ -29,32 +17,12 @@ impl<'r> Unpack for packed::Uint64Reader<'r> { } impl_conversion_for_entity_unpack!(Capacity, Uint64); -impl<'r> From> for Capacity { - fn from(value: packed::Uint64Reader<'r>) -> Capacity { - Capacity::shannons(value.into()) - } -} -impl_conversion_for_entity_from!(Capacity, Uint64); - impl Pack for U256 { fn pack(&self) -> packed::Uint256 { packed::Uint256::from_slice(&self.to_le_bytes()[..]).expect("impossible: fail to pack U256") } } -impl From for packed::Uint256 { - fn from(value: U256) -> Self { - (&value).into() - } -} - -impl From<&U256> for packed::Uint256 { - fn from(value: &U256) -> Self { - packed::Uint256::from_slice(&value.to_le_bytes()[..]) - .expect("impossible: fail to pack U256") - } -} - impl<'r> Unpack for packed::Uint256Reader<'r> { fn unpack(&self) -> U256 { U256::from_little_endian(self.as_slice()).expect("internal error: fail to unpack U256") @@ -62,31 +30,12 @@ impl<'r> Unpack for packed::Uint256Reader<'r> { } impl_conversion_for_entity_unpack!(U256, Uint256); -impl<'r> From> for U256 { - fn from(value: packed::Uint256Reader<'r>) -> U256 { - U256::from_little_endian(value.as_slice()).expect("internal error: fail to unpack U256") - } -} -impl_conversion_for_entity_from!(U256, Uint256); - impl Pack for H256 { fn pack(&self) -> packed::Byte32 { packed::Byte32::from_slice(self.as_bytes()).expect("impossible: fail to pack H256") } } -impl From for packed::Byte32 { - fn from(value: H256) -> Self { - (&value).into() - } -} - -impl From<&H256> for packed::Byte32 { - fn from(value: &H256) -> Self { - packed::Byte32::from_slice(value.as_bytes()).expect("impossible: fail to pack H256") - } -} - impl<'r> Unpack for packed::Byte32Reader<'r> { fn unpack(&self) -> H256 { H256::from_slice(self.as_slice()).expect("internal error: fail to unpack H256") @@ -94,15 +43,5 @@ impl<'r> Unpack for packed::Byte32Reader<'r> { } impl_conversion_for_entity_unpack!(H256, Byte32); -impl<'r> From> for H256 { - fn from(value: packed::Byte32Reader<'r>) -> H256 { - H256::from_slice(value.as_slice()).expect("internal error: fail to unpack H256") - } -} -impl_conversion_for_entity_from!(H256, Byte32); - impl_conversion_for_option!(H256, Byte32Opt, Byte32OptReader); impl_conversion_for_vector!(Capacity, Uint64Vec, Uint64VecReader); - -impl_conversion_for_option_from_into!(H256, Byte32Opt, Byte32OptReader, Byte32); -impl_conversion_for_vector_from_into!(Capacity, Uint64Vec, Uint64VecReader); diff --git a/util/gen-types/src/conversion/primitive.rs b/util/gen-types/src/conversion/primitive.rs index b0a326abe8..38d82d9228 100644 --- a/util/gen-types/src/conversion/primitive.rs +++ b/util/gen-types/src/conversion/primitive.rs @@ -1,6 +1,5 @@ #[cfg(not(feature = "std"))] use alloc::{borrow::ToOwned, str, string::String}; -use core::usize; #[cfg(feature = "std")] use std::str; @@ -13,29 +12,6 @@ impl Pack for bool { } } -impl From for packed::Bool { - fn from(value: bool) -> Self { - (&value).into() - } -} - -impl From<&bool> for packed::Bool { - fn from(value: &bool) -> Self { - let b = u8::from(*value); - packed::Bool::new_unchecked(Bytes::from(vec![b])) - } -} - -impl<'r> From> for bool { - fn from(value: packed::BoolReader<'r>) -> bool { - match value.as_slice()[0] { - 0 => false, - 1 => true, - _ => unreachable!(), - } - } -} -impl_conversion_for_entity_from!(bool, Bool); impl<'r> Unpack for packed::BoolReader<'r> { fn unpack(&self) -> bool { match self.as_slice()[0] { @@ -53,80 +29,24 @@ impl Pack for u32 { } } -impl From for packed::Uint32 { - fn from(value: u32) -> Self { - (&value).into() - } -} - -impl From<&u32> for packed::Uint32 { - fn from(value: &u32) -> Self { - packed::Uint32::new_unchecked(Bytes::from(value.to_le_bytes().to_vec())) - } -} - impl Pack for u64 { fn pack(&self) -> packed::Uint64 { packed::Uint64::new_unchecked(Bytes::from(self.to_le_bytes().to_vec())) } } -impl From for packed::Uint64 { - fn from(value: u64) -> Self { - (&value).into() - } -} - -impl From<&u64> for packed::Uint64 { - fn from(value: &u64) -> Self { - packed::Uint64::new_unchecked(Bytes::from(value.to_le_bytes().to_vec())) - } -} - impl Pack for u128 { fn pack(&self) -> packed::Uint128 { packed::Uint128::new_unchecked(Bytes::from(self.to_le_bytes().to_vec())) } } -impl From for packed::Uint128 { - fn from(value: u128) -> Self { - (&value).into() - } -} - -impl From<&u128> for packed::Uint128 { - fn from(value: &u128) -> Self { - packed::Uint128::new_unchecked(Bytes::from(value.to_le_bytes().to_vec())) - } -} - impl Pack for usize { fn pack(&self) -> packed::Uint32 { (*self as u32).pack() } } -impl From for packed::Uint32 { - fn from(value: usize) -> Self { - (value as u32).into() - } -} - -impl From<&usize> for packed::Uint32 { - fn from(value: &usize) -> Self { - (*value as u32).into() - } -} - -impl<'r> From> for u32 { - fn from(value: packed::Uint32Reader<'r>) -> u32 { - let mut b = [0u8; 4]; - b.copy_from_slice(value.as_slice()); - u32::from_le_bytes(b) - } -} -impl_conversion_for_entity_from!(u32, Uint32); impl<'r> Unpack for packed::Uint32Reader<'r> { fn unpack(&self) -> u32 { let mut b = [0u8; 4]; @@ -136,14 +56,6 @@ impl<'r> Unpack for packed::Uint32Reader<'r> { } impl_conversion_for_entity_unpack!(u32, Uint32); -impl<'r> From> for u64 { - fn from(value: packed::Uint64Reader<'r>) -> u64 { - let mut b = [0u8; 8]; - b.copy_from_slice(value.as_slice()); - u64::from_le_bytes(b) - } -} -impl_conversion_for_entity_from!(u64, Uint64); impl<'r> Unpack for packed::Uint64Reader<'r> { fn unpack(&self) -> u64 { let mut b = [0u8; 8]; @@ -153,14 +65,6 @@ impl<'r> Unpack for packed::Uint64Reader<'r> { } impl_conversion_for_entity_unpack!(u64, Uint64); -impl<'r> From> for u128 { - fn from(value: packed::Uint128Reader<'r>) -> u128 { - let mut b = [0u8; 16]; - b.copy_from_slice(value.as_slice()); - u128::from_le_bytes(b) - } -} -impl_conversion_for_entity_from!(u128, Uint128); impl<'r> Unpack for packed::Uint128Reader<'r> { fn unpack(&self) -> u128 { let mut b = [0u8; 16]; @@ -170,13 +74,6 @@ impl<'r> Unpack for packed::Uint128Reader<'r> { } impl_conversion_for_entity_unpack!(u128, Uint128); -impl<'r> From> for usize { - fn from(value: packed::Uint32Reader<'r>) -> usize { - let x: u32 = value.into(); - x as usize - } -} -impl_conversion_for_entity_from!(usize, Uint32); impl<'r> Unpack for packed::Uint32Reader<'r> { fn unpack(&self) -> usize { let x: u32 = self.unpack(); @@ -191,62 +88,18 @@ impl Pack for u32 { } } -impl From for packed::BeUint32 { - fn from(value: u32) -> Self { - (&value).into() - } -} - -impl From<&u32> for packed::BeUint32 { - fn from(value: &u32) -> Self { - packed::BeUint32::new_unchecked(Bytes::from(value.to_be_bytes().to_vec())) - } -} - impl Pack for u64 { fn pack(&self) -> packed::BeUint64 { packed::BeUint64::new_unchecked(Bytes::from(self.to_be_bytes().to_vec())) } } -impl From for packed::BeUint64 { - fn from(value: u64) -> Self { - (&value).into() - } -} - -impl From<&u64> for packed::BeUint64 { - fn from(value: &u64) -> Self { - packed::BeUint64::new_unchecked(Bytes::from(value.to_be_bytes().to_vec())) - } -} - impl Pack for usize { fn pack(&self) -> packed::BeUint32 { (*self as u32).pack() } } -impl From for packed::BeUint32 { - fn from(value: usize) -> Self { - (value as u32).into() - } -} - -impl From<&usize> for packed::BeUint32 { - fn from(value: &usize) -> Self { - (*value as u32).into() - } -} - -impl<'r> From> for u32 { - fn from(value: packed::BeUint32Reader<'r>) -> u32 { - let mut b = [0u8; 4]; - b.copy_from_slice(value.as_slice()); - u32::from_be_bytes(b) - } -} -impl_conversion_for_entity_from!(u32, BeUint32); impl<'r> Unpack for packed::BeUint32Reader<'r> { fn unpack(&self) -> u32 { let mut b = [0u8; 4]; @@ -256,14 +109,6 @@ impl<'r> Unpack for packed::BeUint32Reader<'r> { } impl_conversion_for_entity_unpack!(u32, BeUint32); -impl<'r> From> for u64 { - fn from(value: packed::BeUint64Reader<'r>) -> u64 { - let mut b = [0u8; 8]; - b.copy_from_slice(value.as_slice()); - u64::from_be_bytes(b) - } -} -impl_conversion_for_entity_from!(u64, BeUint64); impl<'r> Unpack for packed::BeUint64Reader<'r> { fn unpack(&self) -> u64 { let mut b = [0u8; 8]; @@ -273,13 +118,6 @@ impl<'r> Unpack for packed::BeUint64Reader<'r> { } impl_conversion_for_entity_unpack!(u64, BeUint64); -impl<'r> From> for usize { - fn from(value: packed::BeUint32Reader<'r>) -> usize { - let x: u32 = value.into(); - x as usize - } -} -impl_conversion_for_entity_from!(usize, BeUint32); impl<'r> Unpack for packed::BeUint32Reader<'r> { fn unpack(&self) -> usize { let x: u32 = self.unpack(); @@ -298,34 +136,6 @@ impl Pack for [u8] { } } -impl From<&[u8]> for packed::Bytes { - fn from(value: &[u8]) -> Self { - let len = value.len(); - let mut vec: Vec = Vec::with_capacity(4 + len); - vec.extend_from_slice(&(len as u32).to_le_bytes()[..]); - vec.extend_from_slice(value); - packed::Bytes::new_unchecked(Bytes::from(vec)) - } -} - -impl From<[u8; N]> for packed::Bytes { - fn from(value: [u8; N]) -> Self { - (&value[..]).into() - } -} - -impl From<&[u8; N]> for packed::Bytes { - fn from(value: &[u8; N]) -> Self { - (&value[..]).into() - } -} - -impl<'r> From> for Vec { - fn from(value: packed::BytesReader<'r>) -> Vec { - value.raw_data().to_owned() - } -} -impl_conversion_for_entity_from!(Vec, Bytes); impl<'r> Unpack> for packed::BytesReader<'r> { fn unpack(&self) -> Vec { self.raw_data().to_owned() @@ -339,12 +149,6 @@ impl Pack for str { } } -impl From<&str> for packed::Bytes { - fn from(value: &str) -> Self { - value.as_bytes().into() - } -} - impl<'r> packed::BytesReader<'r> { /// Converts self to a string slice. pub fn as_utf8(&self) -> Result<&str, str::Utf8Error> { @@ -374,24 +178,12 @@ impl Pack for String { } } -impl From for packed::Bytes { - fn from(value: String) -> Self { - value.as_str().into() - } -} - impl<'r> Unpack>> for packed::Uint64VecOptReader<'r> { fn unpack(&self) -> Option> { self.to_opt().map(|x| x.unpack()) } } -impl<'r> From> for Option> { - fn from(value: packed::Uint64VecOptReader<'r>) -> Option> { - value.to_opt().map(|x| x.into()) - } -} - impl_conversion_for_entity_unpack!(Option>, Uint64VecOpt); impl Pack for Option> { @@ -406,24 +198,6 @@ impl Pack for Option> { } } -impl From>> for packed::Uint64VecOpt { - fn from(value: Option>) -> Self { - (&value).into() - } -} - -impl From<&Option>> for packed::Uint64VecOpt { - fn from(value: &Option>) -> Self { - if let Some(inner) = value { - packed::Uint64VecOptBuilder::default() - .set(Some(inner.as_slice().into())) - .build() - } else { - packed::Uint64VecOpt::default() - } - } -} - impl_conversion_for_option!(bool, BoolOpt, BoolOptReader); impl_conversion_for_vector!(u32, Uint32Vec, Uint32VecReader); impl_conversion_for_vector!(usize, Uint32Vec, Uint32VecReader); @@ -432,13 +206,3 @@ impl_conversion_for_option_pack!(&str, BytesOpt); impl_conversion_for_option_pack!(String, BytesOpt); impl_conversion_for_option_pack!(Bytes, BytesOpt); impl_conversion_for_packed_optional_pack!(Bytes, BytesOpt); - -impl_conversion_for_option_from_into!(bool, BoolOpt, BoolOptReader, Bool); -impl_conversion_for_vector_from_into!(u32, Uint32Vec, Uint32VecReader); -impl_conversion_for_vector_from_into!(usize, Uint32Vec, Uint32VecReader); -impl_conversion_for_vector_from_into!(u64, Uint64Vec, Uint64VecReader); - -impl_conversion_for_option_from!(&str, BytesOpt, Bytes); -impl_conversion_for_option_from!(String, BytesOpt, Bytes); -impl_conversion_for_option_from!(Bytes, BytesOpt, Bytes); -impl_conversion_for_packed_optional_from!(Bytes, BytesOpt); diff --git a/util/gen-types/src/conversion/utilities.rs b/util/gen-types/src/conversion/utilities.rs index 2109c79bff..cd5faa9a78 100644 --- a/util/gen-types/src/conversion/utilities.rs +++ b/util/gen-types/src/conversion/utilities.rs @@ -8,22 +8,6 @@ macro_rules! impl_conversion_for_entity_unpack { }; } -macro_rules! impl_conversion_for_entity_from { - ($original:ty, $entity:ident) => { - impl From for $original { - fn from(v: packed::$entity) -> $original { - (&v).into() - } - } - - impl From<&packed::$entity> for $original { - fn from(v: &packed::$entity) -> $original { - v.as_reader().into() - } - } - }; -} - macro_rules! impl_conversion_for_option_pack { ($original:ty, $entity:ident) => { impl Pack for Option<$original> { @@ -38,22 +22,6 @@ macro_rules! impl_conversion_for_option_pack { }; } -macro_rules! impl_conversion_for_option_from { - ($original:ty, $entity:ident, $entity_inner:ident) => { - impl From> for packed::$entity { - fn from(value: Option<$original>) -> packed::$entity { - if let Some(inner) = value { - packed::$entity::new_unchecked( - Into::::into(inner).as_bytes(), - ) - } else { - packed::$entity::default() - } - } - } - }; -} - macro_rules! impl_conversion_for_option_unpack { ($original:ty, $entity:ident, $reader:ident) => { impl<'r> Unpack> for packed::$reader<'r> { @@ -65,17 +33,6 @@ macro_rules! impl_conversion_for_option_unpack { }; } -macro_rules! impl_conversion_for_option_reader_from { - ($original:ty, $entity:ident, $reader:ident) => { - impl<'r> From> for Option<$original> { - fn from(value: packed::$reader<'r>) -> Option<$original> { - value.to_opt().map(|x| x.into()) - } - } - impl_conversion_for_entity_from!(Option<$original>, $entity); - }; -} - macro_rules! impl_conversion_for_option { ($original:ty, $entity:ident, $reader:ident) => { impl_conversion_for_option_pack!($original, $entity); @@ -83,13 +40,6 @@ macro_rules! impl_conversion_for_option { }; } -macro_rules! impl_conversion_for_option_from_into { - ($original:ty, $entity:ident, $reader:ident, $entity_inner:ident) => { - impl_conversion_for_option_from!($original, $entity, $entity_inner); - impl_conversion_for_option_reader_from!($original, $entity, $reader); - }; -} - macro_rules! impl_conversion_for_vector_pack { ($original:ty, $entity:ident) => { impl Pack for [$original] { @@ -102,30 +52,6 @@ macro_rules! impl_conversion_for_vector_pack { }; } -macro_rules! impl_conversion_for_vector_from { - ($original:ty, $entity:ident) => { - impl From<&[$original]> for packed::$entity { - fn from(value: &[$original]) -> packed::$entity { - packed::$entity::new_builder() - .set(value.iter().map(|v| v.into()).collect()) - .build() - } - } - - impl From<[$original; N]> for packed::$entity { - fn from(value: [$original; N]) -> packed::$entity { - (&value[..]).into() - } - } - - impl From<&[$original; N]> for packed::$entity { - fn from(value: &[$original; N]) -> packed::$entity { - (&value[..]).into() - } - } - }; -} - macro_rules! impl_conversion_for_vector_unpack { ($original:ty, $entity:ident, $reader:ident) => { impl<'r> Unpack> for packed::$reader<'r> { @@ -137,17 +63,6 @@ macro_rules! impl_conversion_for_vector_unpack { }; } -macro_rules! impl_conversion_for_vector_reader_from { - ($original:ty, $entity:ident, $reader:ident) => { - impl<'r> From> for Vec<$original> { - fn from(value: packed::$reader<'r>) -> Vec<$original> { - value.iter().map(|x| x.into()).collect() - } - } - impl_conversion_for_entity_from!(Vec<$original>, $entity); - }; -} - macro_rules! impl_conversion_for_vector { ($original:ty, $entity:ident, $reader:ident) => { impl_conversion_for_vector_pack!($original, $entity); @@ -155,13 +70,6 @@ macro_rules! impl_conversion_for_vector { }; } -macro_rules! impl_conversion_for_vector_from_into { - ($original:ty, $entity:ident, $reader:ident) => { - impl_conversion_for_vector_from!($original, $entity); - impl_conversion_for_vector_reader_from!($original, $entity, $reader); - }; -} - macro_rules! impl_conversion_for_packed_optional_pack { ($original:ident, $entity:ident) => { impl Pack for Option { @@ -176,20 +84,6 @@ macro_rules! impl_conversion_for_packed_optional_pack { }; } -macro_rules! impl_conversion_for_packed_optional_from { - ($original:ident, $entity:ident) => { - impl From> for packed::$entity { - fn from(value: Option) -> packed::$entity { - if let Some(ref inner) = value { - packed::$entity::new_unchecked(inner.as_bytes()) - } else { - packed::$entity::default() - } - } - } - }; -} - macro_rules! impl_conversion_for_packed_iterator_pack { ($item:ident, $vec:ident) => { impl PackVec for T diff --git a/util/gen-types/src/extension/calc_hash.rs b/util/gen-types/src/extension/calc_hash.rs index ff0b5a2e1c..b552ca7e20 100644 --- a/util/gen-types/src/extension/calc_hash.rs +++ b/util/gen-types/src/extension/calc_hash.rs @@ -17,7 +17,7 @@ where R: Reader<'r>, { fn calc_hash(&self) -> packed::Byte32 { - blake2b_256(self.as_slice()).into() + blake2b_256(self.as_slice()).pack() } } @@ -65,7 +65,7 @@ impl packed::CellOutput { if data.is_empty() { packed::Byte32::zero() } else { - blake2b_256(data).into() + blake2b_256(data).pack() } } } @@ -75,7 +75,7 @@ impl<'r> packed::BytesReader<'r> { /// /// Returns the empty hash if no data, otherwise, calculates the hash of the data and returns it. pub fn calc_raw_data_hash(&self) -> packed::Byte32 { - blake2b_256(self.raw_data()).into() + blake2b_256(self.raw_data()).pack() } } impl_calc_special_hash_for_entity!(Bytes, calc_raw_data_hash); @@ -116,7 +116,7 @@ impl<'r> packed::ProposalShortIdVecReader<'r> { blake2b.update(id.as_slice()); } blake2b.finalize(&mut ret); - ret.into() + ret.pack() } } } @@ -215,7 +215,7 @@ impl<'r> packed::UncleBlockVecReader<'r> { blake2b.update(uncle.calc_header_hash().as_slice()); } blake2b.finalize(&mut ret); - ret.into() + ret.pack() } } } diff --git a/util/gen-types/src/extension/capacity.rs b/util/gen-types/src/extension/capacity.rs index 3970406295..ac4478378f 100644 --- a/util/gen-types/src/extension/capacity.rs +++ b/util/gen-types/src/extension/capacity.rs @@ -46,7 +46,7 @@ impl packed::CellOutput { /// [`occupied capacity`]: #method.occupied_capacity pub fn is_lack_of_capacity(&self, data_capacity: Capacity) -> CapacityResult { self.occupied_capacity(data_capacity) - .map(|cap| cap > self.capacity().into()) + .map(|cap| cap > self.capacity().unpack()) } } @@ -71,7 +71,7 @@ impl packed::CellOutputBuilder { .transpose() .and_then(|y| y.unwrap_or_else(Capacity::zero).safe_add(x)) }) - .map(|x| self.capacity(x).build()) + .map(|x| self.capacity(x.pack()).build()) } } @@ -83,7 +83,7 @@ impl packed::CellOutputVec { self.as_reader() .iter() .map(|output| { - let cap: Capacity = output.capacity().into(); + let cap: Capacity = output.capacity().unpack(); cap }) .try_fold(Capacity::zero(), Capacity::safe_add) diff --git a/util/gen-types/src/extension/rust_core_traits.rs b/util/gen-types/src/extension/rust_core_traits.rs index 631224abdb..792895cf93 100644 --- a/util/gen-types/src/extension/rust_core_traits.rs +++ b/util/gen-types/src/extension/rust_core_traits.rs @@ -52,8 +52,8 @@ macro_rules! impl_cmp_partial_ord { impl ::core::cmp::Ord for packed::Uint32 { #[inline] fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { - let self_val: u32 = self.as_reader().into(); - let other_val: u32 = other.as_reader().into(); + let self_val: u32 = self.unpack(); + let other_val: u32 = other.unpack(); self_val.cmp(&other_val) } } @@ -62,8 +62,8 @@ impl_cmp_partial_ord!(Uint32); impl ::core::cmp::Ord for packed::Uint64 { #[inline] fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { - let self_val: u64 = self.as_reader().into(); - let other_val: u64 = other.as_reader().into(); + let self_val: u64 = self.unpack(); + let other_val: u64 = other.unpack(); self_val.cmp(&other_val) } } @@ -72,8 +72,8 @@ impl_cmp_partial_ord!(Uint64); impl ::core::cmp::Ord for packed::Uint128 { #[inline] fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { - let self_val: u128 = self.as_reader().into(); - let other_val: u128 = other.as_reader().into(); + let self_val: u128 = self.unpack(); + let other_val: u128 = other.unpack(); self_val.cmp(&other_val) } } @@ -81,14 +81,14 @@ impl_cmp_partial_ord!(Uint128); #[cfg(feature = "std")] mod std_feature_mod { - use crate::packed; + use crate::{packed, prelude::*}; use numext_fixed_uint::U256; impl ::core::cmp::Ord for packed::Uint256 { #[inline] fn cmp(&self, other: &Self) -> ::core::cmp::Ordering { - let self_val: U256 = self.as_reader().into(); - let other_val: U256 = other.as_reader().into(); + let self_val: U256 = self.unpack(); + let other_val: U256 = other.unpack(); self_val.cmp(&other_val) } } diff --git a/util/gen-types/src/extension/shortcut.rs b/util/gen-types/src/extension/shortcut.rs index b10f9e68cd..499145ee90 100644 --- a/util/gen-types/src/extension/shortcut.rs +++ b/util/gen-types/src/extension/shortcut.rs @@ -10,7 +10,7 @@ impl packed::Byte32 { /// Creates a new `Byte32` whose bits are all ones. pub fn max_value() -> Self { - [u8::max_value(); 32].into() + [u8::max_value(); 32].pack() } /// Checks whether all bits in self are zeros. @@ -20,7 +20,7 @@ impl packed::Byte32 { /// Creates a new `Bytes32`. pub fn new(v: [u8; 32]) -> Self { - v.into() + v.pack() } } @@ -29,7 +29,7 @@ impl packed::ProposalShortId { pub fn from_tx_hash(h: &packed::Byte32) -> Self { let mut inner = [0u8; 10]; inner.copy_from_slice(&h.as_slice()[..10]); - inner.into() + inner.pack() } /// Creates a new `ProposalShortId` whose bits are all zeros. @@ -39,7 +39,7 @@ impl packed::ProposalShortId { /// Creates a new `ProposalShortId`. pub fn new(v: [u8; 10]) -> Self { - v.into() + v.pack() } } @@ -48,20 +48,20 @@ impl packed::OutPoint { pub fn new(tx_hash: packed::Byte32, index: u32) -> Self { packed::OutPoint::new_builder() .tx_hash(tx_hash) - .index(index) + .index(index.pack()) .build() } /// Creates a new null `OutPoint`. pub fn null() -> Self { packed::OutPoint::new_builder() - .index(u32::max_value()) + .index(u32::max_value().pack()) .build() } /// Checks whether self is a null `OutPoint`. pub fn is_null(&self) -> bool { - self.tx_hash().is_zero() && Into::::into(self.index().as_reader()) == u32::max_value() + self.tx_hash().is_zero() && Unpack::::unpack(&self.index()) == u32::max_value() } /// Generates a binary data to be used as a key for indexing cells in storage. @@ -82,7 +82,7 @@ impl packed::OutPoint { /// order, so as to traverse cells in the forward order too. pub fn to_cell_key(&self) -> Vec { let mut key = Vec::with_capacity(36); - let index: u32 = self.index().as_reader().into(); + let index: u32 = self.index().unpack(); key.extend_from_slice(self.tx_hash().as_slice()); key.extend_from_slice(&index.to_be_bytes()); key @@ -93,7 +93,7 @@ impl packed::CellInput { /// Creates a new `CellInput`. pub fn new(previous_output: packed::OutPoint, block_number: BlockNumber) -> Self { packed::CellInput::new_builder() - .since(block_number) + .since(block_number.pack()) .previous_output(previous_output) .build() } @@ -110,7 +110,7 @@ impl packed::Script { .lock(self) .build() .as_bytes() - .into() + .pack() } /// Converts from bytes of [`CellbaseWitness`](struct.CellbaseWitness.html). diff --git a/util/gen-types/src/extension/tests/calc_hash.rs b/util/gen-types/src/extension/tests/calc_hash.rs index e828d9b512..b0715dd1ec 100644 --- a/util/gen-types/src/extension/tests/calc_hash.rs +++ b/util/gen-types/src/extension/tests/calc_hash.rs @@ -1,108 +1,100 @@ -use crate::{ - packed::{self, ProposalShortIdVec, UncleBlockVec}, - prelude::*, - vec, -}; +use crate::{packed, prelude::*, vec}; use ckb_fixed_hash::h256; use ckb_hash::blake2b_256; #[test] fn proposals_hash() { - let proposal1 = [1; 10].into(); - let proposal2 = [2; 10].into(); - let proposals: ProposalShortIdVec = vec![proposal1, proposal2].into(); + let proposal1 = [1; 10].pack(); + let proposal2 = [2; 10].pack(); + let proposals = vec![proposal1, proposal2].pack(); let expect = h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562"); - assert_eq!(proposals.calc_proposals_hash(), expect.into()); + assert_eq!(proposals.calc_proposals_hash(), expect.pack()); } #[test] fn empty_proposals_hash() { let proposals = packed::ProposalShortIdVec::new_builder().build(); let expect = h256!("0x0"); - assert_eq!(proposals.calc_proposals_hash(), expect.into()); + assert_eq!(proposals.calc_proposals_hash(), expect.pack()); } #[test] fn uncles_hash() { let uncle1_raw_header = packed::RawHeader::new_builder() - .version(0u32) - .compact_target(0x1e08_3126u32) - .timestamp(0x5cd2_b117u64) - .number(0x400u64) - .epoch(0x0007_0800_1800_0001u64) - .parent_hash(h256!( - "0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831" - )) - .transactions_root(h256!( - "0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f" - )) - .proposals_hash(h256!( - "0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562" - )) - .extra_hash(h256!( - "0x0000000000000000000000000000000000000000000000000000000000000000" - )) - .dao(h256!( - "0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000" - )) + .version(0u32.pack()) + .compact_target(0x1e08_3126u32.pack()) + .timestamp(0x5cd2_b117u64.pack()) + .number(0x400u64.pack()) + .epoch(0x0007_0800_1800_0001u64.pack()) + .parent_hash( + h256!("0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831").pack(), + ) + .transactions_root( + h256!("0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f").pack(), + ) + .proposals_hash( + h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").pack(), + ) + .extra_hash( + h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(), + ) + .dao(h256!("0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000").pack()) .build(); let uncle1_header = packed::Header::new_builder() .raw(uncle1_raw_header) - .nonce(0x5ff1_389a_f870_6543_11a2_bee6_1237u128) + .nonce(0x5ff1_389a_f870_6543_11a2_bee6_1237u128.pack()) .build(); - let uncle1_proposals: ProposalShortIdVec = vec![[1; 10].into(), [2; 10].into()].into(); + let uncle1_proposals = vec![[1; 10].pack(), [2; 10].pack()].pack(); let uncle1 = packed::UncleBlock::new_builder() .header(uncle1_header) .proposals(uncle1_proposals) .build(); let uncle2_raw_header = packed::RawHeader::new_builder() - .version(0u32) - .compact_target(0x2001_0000u32) - .timestamp(0x5cd2_1a16u64) - .number(0x400u64) - .epoch(0x0007_0800_1800_0001u64) - .parent_hash(h256!( - "0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831" - )) - .transactions_root(h256!( - "0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f" - )) - .proposals_hash(h256!( - "0x0000000000000000000000000000000000000000000000000000000000000000" - )) - .extra_hash(h256!( - "0x0000000000000000000000000000000000000000000000000000000000000000" - )) - .dao(h256!( - "0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000" - )) + .version(0u32.pack()) + .compact_target(0x2001_0000u32.pack()) + .timestamp(0x5cd2_1a16u64.pack()) + .number(0x400u64.pack()) + .epoch(0x0007_0800_1800_0001u64.pack()) + .parent_hash( + h256!("0x8381df265c9442d5c27559b167892c5a6a8322871112d3cc8ef45222c6624831").pack(), + ) + .transactions_root( + h256!("0x12214693b8bd5c3d8f96e270dc8fe32b1702bd97630a9eab53a69793e6bc893f").pack(), + ) + .proposals_hash( + h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(), + ) + .extra_hash( + h256!("0x0000000000000000000000000000000000000000000000000000000000000000").pack(), + ) + .dao(h256!("0xb54bdd7f6be90000bb52f392d41cd70024f7ef29b437000000febffacf030000").pack()) .build(); let uncle2_header = packed::Header::new_builder() .raw(uncle2_raw_header) - .nonce(0x2f39_2d41_cd70_024fu128) + .nonce(0x2f39_2d41_cd70_024fu128.pack()) .build(); let uncle2 = packed::UncleBlock::new_builder() .header(uncle2_header) .build(); - let uncles: UncleBlockVec = vec![uncle1, uncle2].into(); + let uncles = vec![uncle1, uncle2].pack(); let expect = h256!("0x0135d01f169a870bd9c92b2b37aecfa0fbfb7c1862cc176e03bb525fab0649d9"); - assert_eq!(uncles.calc_uncles_hash(), expect.into()); + assert_eq!(uncles.calc_uncles_hash(), expect.pack()); } #[test] fn empty_uncles_hash() { let uncles = packed::UncleBlockVec::new_builder().build(); let expect = h256!("0x0"); - assert_eq!(uncles.calc_uncles_hash(), expect.into()); + assert_eq!(uncles.calc_uncles_hash(), expect.pack()); } #[test] fn empty_script_hash() { let script = packed::Script::new_builder().build(); let expect = h256!("0x77c93b0632b5b6c3ef922c5b7cea208fb0a7c427a13d50e13d3fefad17e0c590"); - assert_eq!(script.calc_script_hash(), expect.into()); + assert_eq!(script.calc_script_hash(), expect.pack()); } #[test] @@ -111,15 +103,15 @@ fn always_success_script_hash() { let always_success_hash = blake2b_256(&always_success[..]); let script = packed::Script::new_builder() - .code_hash(always_success_hash) + .code_hash(always_success_hash.pack()) .build(); let expect = h256!("0x4ceaa32f692948413e213ce6f3a83337145bde6e11fd8cb94377ce2637dcc412"); - assert_eq!(script.calc_script_hash(), expect.into()); + assert_eq!(script.calc_script_hash(), expect.pack()); } #[test] fn one_arg_script_hash() { - let script = packed::Script::new_builder().args([1]).build(); + let script = packed::Script::new_builder().args([1].pack()).build(); let expect = h256!("0x67951b34bce20cb71b7e235c1f8cda259628d99d94825bffe549c23b4dd2930f"); - assert_eq!(script.calc_script_hash(), expect.into()); + assert_eq!(script.calc_script_hash(), expect.pack()); } diff --git a/util/gen-types/src/extension/tests/capacity.rs b/util/gen-types/src/extension/tests/capacity.rs index 223bbbb06b..3502bf6a0b 100644 --- a/util/gen-types/src/extension/tests/capacity.rs +++ b/util/gen-types/src/extension/tests/capacity.rs @@ -10,7 +10,7 @@ fn script_occupied_capacity() { (vec![0, 0], 2 + 32 + 1), ]; for (args, ckb) in testcases.into_iter() { - let script = packed::Script::new_builder().args(args).build(); + let script = packed::Script::new_builder().args(args.pack()).build(); let expect = Capacity::bytes(ckb).unwrap(); assert_eq!(script.occupied_capacity().unwrap(), expect); } @@ -28,7 +28,7 @@ fn min_cell_output_capacity() { #[test] fn min_secp256k1_cell_output_capacity() { - let lock = packed::Script::new_builder().args([0u8; 20]).build(); + let lock = packed::Script::new_builder().args([0u8; 20].pack()).build(); let output = packed::CellOutput::new_builder().lock(lock).build(); assert_eq!( output.occupied_capacity(Capacity::zero()).unwrap(), diff --git a/util/gen-types/src/extension/tests/check_data.rs b/util/gen-types/src/extension/tests/check_data.rs index f4c567c370..c66c247392 100644 --- a/util/gen-types/src/extension/tests/check_data.rs +++ b/util/gen-types/src/extension/tests/check_data.rs @@ -1,25 +1,17 @@ -use crate::{ - borrow::ToOwned, - packed::{self, Bytes, CellOutput}, - prelude::*, -}; +use crate::{borrow::ToOwned, packed, prelude::*}; fn create_transaction( outputs: &[&packed::CellOutput], outputs_data: &[&[u8]], cell_deps: &[&packed::CellDep], ) -> packed::Transaction { - let outputs_iter: Vec = outputs.iter().map(|d| d.to_owned().to_owned()).collect(); - let outputs_data_iter: Vec = outputs_data - .iter() - .map(|d| Into::::into(d.to_owned())) - .collect(); - let cell_deps_iter: Vec = - cell_deps.iter().map(|d| d.to_owned().to_owned()).collect(); + let outputs_iter = outputs.iter().map(|d| d.to_owned().to_owned()); + let outputs_data_iter = outputs_data.iter().map(|d| d.to_owned().to_owned().pack()); + let cell_deps_iter = cell_deps.iter().map(|d| d.to_owned().to_owned()); let raw = packed::RawTransaction::new_builder() - .outputs(outputs_iter) - .outputs_data(outputs_data_iter) - .cell_deps(cell_deps_iter) + .outputs(outputs_iter.pack()) + .outputs_data(outputs_data_iter.pack()) + .cell_deps(cell_deps_iter.pack()) .build(); packed::Transaction::new_builder().raw(raw).build() } @@ -39,10 +31,10 @@ fn check_data() { for ht in 0..4 { if ht != 3 { for dt in 0..2 { - let ht_right = ht; - let dt_right = dt; - let ht_error = 3; - let dt_error = 2; + let ht_right = ht.into(); + let dt_right = dt.into(); + let ht_error = 3.into(); + let dt_error = 2.into(); let script_right = packed::Script::new_builder().hash_type(ht_right).build(); let script_error = packed::Script::new_builder().hash_type(ht_error).build(); diff --git a/util/gen-types/src/extension/tests/rust_core_traits.rs b/util/gen-types/src/extension/tests/rust_core_traits.rs index ee2bd21d9e..b3e3ce1adb 100644 --- a/util/gen-types/src/extension/tests/rust_core_traits.rs +++ b/util/gen-types/src/extension/tests/rust_core_traits.rs @@ -4,50 +4,49 @@ use numext_fixed_uint::U256; #[test] fn test_uint32_cmp() { - let a: Uint32 = 10u32.into(); - let b = 20u32.into(); - let c = 10u32.into(); + let a: Uint32 = 10u32.pack(); + let b = 20u32.pack(); + let c = 10u32.pack(); assert!(a < b); assert!(a == c); } #[test] fn test_uint64_cmp() { - let a: Uint64 = 10u64.into(); - let b = 20u64.into(); - let c = 10u64.into(); + let a: Uint64 = 10u64.pack(); + let b = 20u64.pack(); + let c = 10u64.pack(); assert!(a < b); assert!(a == c); - let a: Uint64 = 1000u64.into(); - let b: Uint64 = 2000u64.into(); + let a: Uint64 = 1000u64.pack(); + let b: Uint64 = 2000u64.pack(); assert!(a < b); } #[test] fn test_uint128_cmp() { - let a: Uint128 = 10u128.into(); - let b = 20u128.into(); - let c = 10u128.into(); + let a: Uint128 = 10u128.pack(); + let b = 20u128.pack(); + let c = 10u128.pack(); assert!(a < b); assert!(a == c); } #[test] fn test_uint256_cmp() { - let a: Uint256 = U256::from(10u32).into(); - let b = U256::from(20u32).into(); - let c = U256::from(10u32).into(); + let a = U256::from(10u32).pack(); + let b = U256::from(20u32).pack(); + let c = U256::from(10u32).pack(); assert!(a < b); assert!(a == c); } #[test] fn test_byte32_cmp() { - let a: Byte32 = - h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").into(); - let b = h256!("0xd2670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").into(); - let c = h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").into(); + let a = h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").pack(); + let b = h256!("0xd2670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").pack(); + let c = h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562").pack(); assert!(a < b); assert!(a == c); @@ -55,27 +54,24 @@ fn test_byte32_cmp() { #[test] fn test_bytesopt_cmp() { - let a: BytesOpt = Some( - Into::::into(h256!( - "0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562" - )) - .as_bytes(), + let a = Some( + h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562") + .pack() + .as_bytes(), ) - .into(); + .pack(); let b = Some( - Into::::into(h256!( - "0xd2670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562" - )) - .as_bytes(), + h256!("0xd2670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562") + .pack() + .as_bytes(), ) - .into(); + .pack(); let c = Some( - Into::::into(h256!( - "0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562" - )) - .as_bytes(), + h256!("0xd1670e45af1deb9cc00951d71c09ce80932e7ddf9fb151d744436bd04ac4a562") + .pack() + .as_bytes(), ) - .into(); + .pack(); let d = BytesOpt::new_builder().build(); assert!(d.is_none()); @@ -86,37 +82,37 @@ fn test_bytesopt_cmp() { #[test] fn test_script_cmp() { - let a = Script::new_builder().args([1]).build(); - let b = Script::new_builder().args([2]).build(); + let a = Script::new_builder().args([1].pack()).build(); + let b = Script::new_builder().args([2].pack()).build(); assert!(a < b); } #[test] fn test_celldep_cmp() { - let a = CellDep::new_builder().dep_type(1).build(); - let b = CellDep::new_builder().dep_type(2).build(); + let a = CellDep::new_builder().dep_type(1.into()).build(); + let b = CellDep::new_builder().dep_type(2.into()).build(); assert!(a < b); } #[test] fn test_outpoint_cmp() { - let a = OutPoint::new_builder().index(1u32).build(); - let b = OutPoint::new_builder().index(2u32).build(); + let a = OutPoint::new_builder().index(1u32.pack()).build(); + let b = OutPoint::new_builder().index(2u32.pack()).build(); assert!(a < b); } #[test] fn test_cellinput_cmp() { - let a = CellInput::new_builder().since(1000u64).build(); - let b = CellInput::new_builder().since(2000u64).build(); + let a = CellInput::new_builder().since(1000u64.pack()).build(); + let b = CellInput::new_builder().since(2000u64.pack()).build(); assert!(a > b); } #[test] fn test_celloutput_cmp() { - let script_lock = Script::new_builder().hash_type(1).build(); - let script_type = Script::new_builder().hash_type(2).build(); + let script_lock = Script::new_builder().hash_type(1.into()).build(); + let script_type = Script::new_builder().hash_type(2.into()).build(); let script_type_opt = ScriptOpt::new_builder().set(Some(script_type)).build(); let output_a = CellOutput::new_builder().lock(script_lock.clone()).build(); let output_b = CellOutput::new_builder() diff --git a/util/gen-types/src/extension/tests/serialized_size.rs b/util/gen-types/src/extension/tests/serialized_size.rs index cc1d1bba48..40bba83b2f 100644 --- a/util/gen-types/src/extension/tests/serialized_size.rs +++ b/util/gen-types/src/extension/tests/serialized_size.rs @@ -1,17 +1,13 @@ -use crate::{ - packed::{self, ProposalShortId, ProposalShortIdVec}, - prelude::*, - vec::Vec, -}; +use crate::{packed, prelude::*, vec, vec::Vec}; #[test] fn block_size_should_not_include_uncles_proposals() { - let proposal1: ProposalShortId = [1; 10].into(); - let proposal2: ProposalShortId = [2; 10].into(); - let proposal3 = [3; 10].into(); - let proposals1: ProposalShortIdVec = vec![proposal1.clone()].into(); - let proposals2: ProposalShortIdVec = vec![proposal1.clone(), proposal2.clone()].into(); - let proposals3: ProposalShortIdVec = vec![proposal1, proposal2, proposal3].into(); + let proposal1 = [1; 10].pack(); + let proposal2 = [2; 10].pack(); + let proposal3 = [3; 10].pack(); + let proposals1 = vec![proposal1.clone()].pack(); + let proposals2 = vec![proposal1.clone(), proposal2.clone()].pack(); + let proposals3 = vec![proposal1, proposal2, proposal3].pack(); let uncle0 = packed::UncleBlock::new_builder().build(); let uncle1 = packed::UncleBlock::new_builder() .proposals(proposals1) @@ -35,9 +31,11 @@ fn block_size_should_not_include_uncles_proposals() { let mut uncles = uncles.clone(); loop { let block_with_empty_uncles = packed::Block::new_builder() - .uncles(empty_uncles.clone()) + .uncles(empty_uncles.clone().pack()) + .build(); + let block_with_uncles = packed::Block::new_builder() + .uncles(uncles.clone().pack()) .build(); - let block_with_uncles = packed::Block::new_builder().uncles(uncles.clone()).build(); let actual = block_with_uncles.serialized_size_without_uncle_proposals(); let actual_empty = block_with_empty_uncles.serialized_size_without_uncle_proposals(); let expected = block_with_empty_uncles.as_slice().len(); @@ -56,21 +54,21 @@ fn block_size_should_not_include_uncles_proposals() { let mut empty_uncles = empty_uncles; let mut uncles = uncles; let extensions: Vec = vec![ - [0u8].into(), - [0u8; 24].into(), - [0u8; 48].into(), - [0u8; 72].into(), - [0u8; 96].into(), + [0u8].pack(), + [0u8; 24].pack(), + [0u8; 48].pack(), + [0u8; 72].pack(), + [0u8; 96].pack(), ]; for extension in extensions { loop { let block_with_empty_uncles_v1 = packed::BlockV1::new_builder() - .uncles(empty_uncles.clone()) + .uncles(empty_uncles.clone().pack()) .extension(extension.clone()) .build(); let block_with_empty_uncles = block_with_empty_uncles_v1.as_v0(); let block_with_uncles = packed::BlockV1::new_builder() - .uncles(uncles.clone()) + .uncles(uncles.clone().pack()) .extension(extension.clone()) .build() .as_v0(); diff --git a/util/gen-types/src/generated/blockchain.rs b/util/gen-types/src/generated/blockchain.rs index 97c34a09c6..3eb5b9b6b9 100644 --- a/util/gen-types/src/generated/blockchain.rs +++ b/util/gen-types/src/generated/blockchain.rs @@ -1,4 +1,4 @@ -// Generated by Molecule 0.8.0 +// Generated by Molecule 0.7.5 use molecule::prelude::*; #[derive(Clone)] @@ -143,7 +143,6 @@ impl<'r> molecule::prelude::Reader<'r> for Uint32Reader<'r> { Ok(()) } } -#[derive(Clone)] pub struct Uint32Builder(pub(crate) [Byte; 4]); impl ::core::fmt::Debug for Uint32Builder { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { @@ -164,39 +163,24 @@ impl Uint32Builder { pub const TOTAL_SIZE: usize = 4; pub const ITEM_SIZE: usize = 1; pub const ITEM_COUNT: usize = 4; - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into<[Byte; 4]>, - { - self.0 = v.into(); + pub fn set(mut self, v: [Byte; 4]) -> Self { + self.0 = v; self } - pub fn nth0(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[0] = v.into(); + pub fn nth0(mut self, v: Byte) -> Self { + self.0[0] = v; self } - pub fn nth1(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[1] = v.into(); + pub fn nth1(mut self, v: Byte) -> Self { + self.0[1] = v; self } - pub fn nth2(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[2] = v.into(); + pub fn nth2(mut self, v: Byte) -> Self { + self.0[2] = v; self } - pub fn nth3(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[3] = v.into(); + pub fn nth3(mut self, v: Byte) -> Self { + self.0[3] = v; self } } @@ -220,54 +204,6 @@ impl molecule::prelude::Builder for Uint32Builder { Uint32::new_unchecked(inner.into()) } } -impl From<[Byte; 4usize]> for Uint32 { - fn from(value: [Byte; 4usize]) -> Self { - Self::new_builder().set(value).build() - } -} -impl ::core::convert::TryFrom<&[Byte]> for Uint32 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[Byte]) -> Result { - Ok(Self::new_builder() - .set(<&[Byte; 4usize]>::try_from(value)?.clone()) - .build()) - } -} -impl From for [Byte; 4usize] { - #[track_caller] - fn from(value: Uint32) -> Self { - [value.nth0(), value.nth1(), value.nth2(), value.nth3()] - } -} -impl From<[u8; 4usize]> for Uint32 { - fn from(value: [u8; 4usize]) -> Self { - Uint32Reader::new_unchecked(&value).to_entity() - } -} -impl ::core::convert::TryFrom<&[u8]> for Uint32 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[u8]) -> Result { - Ok(<[u8; 4usize]>::try_from(value)?.into()) - } -} -impl From for [u8; 4usize] { - #[track_caller] - fn from(value: Uint32) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From> for &'a [u8; 4usize] { - #[track_caller] - fn from(value: Uint32Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From<&'a Uint32Reader<'a>> for &'a [u8; 4usize] { - #[track_caller] - fn from(value: &'a Uint32Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} #[derive(Clone)] pub struct Uint64(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Uint64 { @@ -443,7 +379,6 @@ impl<'r> molecule::prelude::Reader<'r> for Uint64Reader<'r> { Ok(()) } } -#[derive(Clone)] pub struct Uint64Builder(pub(crate) [Byte; 8]); impl ::core::fmt::Debug for Uint64Builder { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { @@ -468,67 +403,40 @@ impl Uint64Builder { pub const TOTAL_SIZE: usize = 8; pub const ITEM_SIZE: usize = 1; pub const ITEM_COUNT: usize = 8; - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into<[Byte; 8]>, - { - self.0 = v.into(); + pub fn set(mut self, v: [Byte; 8]) -> Self { + self.0 = v; self } - pub fn nth0(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[0] = v.into(); + pub fn nth0(mut self, v: Byte) -> Self { + self.0[0] = v; self } - pub fn nth1(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[1] = v.into(); + pub fn nth1(mut self, v: Byte) -> Self { + self.0[1] = v; self } - pub fn nth2(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[2] = v.into(); + pub fn nth2(mut self, v: Byte) -> Self { + self.0[2] = v; self } - pub fn nth3(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[3] = v.into(); + pub fn nth3(mut self, v: Byte) -> Self { + self.0[3] = v; self } - pub fn nth4(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[4] = v.into(); + pub fn nth4(mut self, v: Byte) -> Self { + self.0[4] = v; self } - pub fn nth5(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[5] = v.into(); + pub fn nth5(mut self, v: Byte) -> Self { + self.0[5] = v; self } - pub fn nth6(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[6] = v.into(); + pub fn nth6(mut self, v: Byte) -> Self { + self.0[6] = v; self } - pub fn nth7(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[7] = v.into(); + pub fn nth7(mut self, v: Byte) -> Self { + self.0[7] = v; self } } @@ -556,63 +464,6 @@ impl molecule::prelude::Builder for Uint64Builder { Uint64::new_unchecked(inner.into()) } } -impl From<[Byte; 8usize]> for Uint64 { - fn from(value: [Byte; 8usize]) -> Self { - Self::new_builder().set(value).build() - } -} -impl ::core::convert::TryFrom<&[Byte]> for Uint64 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[Byte]) -> Result { - Ok(Self::new_builder() - .set(<&[Byte; 8usize]>::try_from(value)?.clone()) - .build()) - } -} -impl From for [Byte; 8usize] { - #[track_caller] - fn from(value: Uint64) -> Self { - [ - value.nth0(), - value.nth1(), - value.nth2(), - value.nth3(), - value.nth4(), - value.nth5(), - value.nth6(), - value.nth7(), - ] - } -} -impl From<[u8; 8usize]> for Uint64 { - fn from(value: [u8; 8usize]) -> Self { - Uint64Reader::new_unchecked(&value).to_entity() - } -} -impl ::core::convert::TryFrom<&[u8]> for Uint64 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[u8]) -> Result { - Ok(<[u8; 8usize]>::try_from(value)?.into()) - } -} -impl From for [u8; 8usize] { - #[track_caller] - fn from(value: Uint64) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From> for &'a [u8; 8usize] { - #[track_caller] - fn from(value: Uint64Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From<&'a Uint64Reader<'a>> for &'a [u8; 8usize] { - #[track_caller] - fn from(value: &'a Uint64Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} #[derive(Clone)] pub struct Uint128(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Uint128 { @@ -844,7 +695,6 @@ impl<'r> molecule::prelude::Reader<'r> for Uint128Reader<'r> { Ok(()) } } -#[derive(Clone)] pub struct Uint128Builder(pub(crate) [Byte; 16]); impl ::core::fmt::Debug for Uint128Builder { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { @@ -877,123 +727,72 @@ impl Uint128Builder { pub const TOTAL_SIZE: usize = 16; pub const ITEM_SIZE: usize = 1; pub const ITEM_COUNT: usize = 16; - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into<[Byte; 16]>, - { - self.0 = v.into(); + pub fn set(mut self, v: [Byte; 16]) -> Self { + self.0 = v; self } - pub fn nth0(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[0] = v.into(); + pub fn nth0(mut self, v: Byte) -> Self { + self.0[0] = v; self } - pub fn nth1(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[1] = v.into(); + pub fn nth1(mut self, v: Byte) -> Self { + self.0[1] = v; self } - pub fn nth2(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[2] = v.into(); + pub fn nth2(mut self, v: Byte) -> Self { + self.0[2] = v; self } - pub fn nth3(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[3] = v.into(); + pub fn nth3(mut self, v: Byte) -> Self { + self.0[3] = v; self } - pub fn nth4(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[4] = v.into(); + pub fn nth4(mut self, v: Byte) -> Self { + self.0[4] = v; self } - pub fn nth5(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[5] = v.into(); + pub fn nth5(mut self, v: Byte) -> Self { + self.0[5] = v; self } - pub fn nth6(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[6] = v.into(); + pub fn nth6(mut self, v: Byte) -> Self { + self.0[6] = v; self } - pub fn nth7(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[7] = v.into(); + pub fn nth7(mut self, v: Byte) -> Self { + self.0[7] = v; self } - pub fn nth8(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[8] = v.into(); + pub fn nth8(mut self, v: Byte) -> Self { + self.0[8] = v; self } - pub fn nth9(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[9] = v.into(); + pub fn nth9(mut self, v: Byte) -> Self { + self.0[9] = v; self } - pub fn nth10(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[10] = v.into(); + pub fn nth10(mut self, v: Byte) -> Self { + self.0[10] = v; self } - pub fn nth11(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[11] = v.into(); + pub fn nth11(mut self, v: Byte) -> Self { + self.0[11] = v; self } - pub fn nth12(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[12] = v.into(); + pub fn nth12(mut self, v: Byte) -> Self { + self.0[12] = v; self } - pub fn nth13(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[13] = v.into(); + pub fn nth13(mut self, v: Byte) -> Self { + self.0[13] = v; self } - pub fn nth14(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[14] = v.into(); + pub fn nth14(mut self, v: Byte) -> Self { + self.0[14] = v; self } - pub fn nth15(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[15] = v.into(); + pub fn nth15(mut self, v: Byte) -> Self { + self.0[15] = v; self } } @@ -1029,71 +828,6 @@ impl molecule::prelude::Builder for Uint128Builder { Uint128::new_unchecked(inner.into()) } } -impl From<[Byte; 16usize]> for Uint128 { - fn from(value: [Byte; 16usize]) -> Self { - Self::new_builder().set(value).build() - } -} -impl ::core::convert::TryFrom<&[Byte]> for Uint128 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[Byte]) -> Result { - Ok(Self::new_builder() - .set(<&[Byte; 16usize]>::try_from(value)?.clone()) - .build()) - } -} -impl From for [Byte; 16usize] { - #[track_caller] - fn from(value: Uint128) -> Self { - [ - value.nth0(), - value.nth1(), - value.nth2(), - value.nth3(), - value.nth4(), - value.nth5(), - value.nth6(), - value.nth7(), - value.nth8(), - value.nth9(), - value.nth10(), - value.nth11(), - value.nth12(), - value.nth13(), - value.nth14(), - value.nth15(), - ] - } -} -impl From<[u8; 16usize]> for Uint128 { - fn from(value: [u8; 16usize]) -> Self { - Uint128Reader::new_unchecked(&value).to_entity() - } -} -impl ::core::convert::TryFrom<&[u8]> for Uint128 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[u8]) -> Result { - Ok(<[u8; 16usize]>::try_from(value)?.into()) - } -} -impl From for [u8; 16usize] { - #[track_caller] - fn from(value: Uint128) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From> for &'a [u8; 16usize] { - #[track_caller] - fn from(value: Uint128Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From<&'a Uint128Reader<'a>> for &'a [u8; 16usize] { - #[track_caller] - fn from(value: &'a Uint128Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} #[derive(Clone)] pub struct Byte32(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Byte32 { @@ -1440,7 +1174,6 @@ impl<'r> molecule::prelude::Reader<'r> for Byte32Reader<'r> { Ok(()) } } -#[derive(Clone)] pub struct Byte32Builder(pub(crate) [Byte; 32]); impl ::core::fmt::Debug for Byte32Builder { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { @@ -1489,235 +1222,136 @@ impl Byte32Builder { pub const TOTAL_SIZE: usize = 32; pub const ITEM_SIZE: usize = 1; pub const ITEM_COUNT: usize = 32; - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into<[Byte; 32]>, - { - self.0 = v.into(); + pub fn set(mut self, v: [Byte; 32]) -> Self { + self.0 = v; self } - pub fn nth0(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[0] = v.into(); + pub fn nth0(mut self, v: Byte) -> Self { + self.0[0] = v; self } - pub fn nth1(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[1] = v.into(); + pub fn nth1(mut self, v: Byte) -> Self { + self.0[1] = v; self } - pub fn nth2(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[2] = v.into(); + pub fn nth2(mut self, v: Byte) -> Self { + self.0[2] = v; self } - pub fn nth3(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[3] = v.into(); + pub fn nth3(mut self, v: Byte) -> Self { + self.0[3] = v; self } - pub fn nth4(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[4] = v.into(); + pub fn nth4(mut self, v: Byte) -> Self { + self.0[4] = v; self } - pub fn nth5(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[5] = v.into(); + pub fn nth5(mut self, v: Byte) -> Self { + self.0[5] = v; self } - pub fn nth6(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[6] = v.into(); + pub fn nth6(mut self, v: Byte) -> Self { + self.0[6] = v; self } - pub fn nth7(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[7] = v.into(); + pub fn nth7(mut self, v: Byte) -> Self { + self.0[7] = v; self } - pub fn nth8(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[8] = v.into(); + pub fn nth8(mut self, v: Byte) -> Self { + self.0[8] = v; self } - pub fn nth9(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[9] = v.into(); + pub fn nth9(mut self, v: Byte) -> Self { + self.0[9] = v; self } - pub fn nth10(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[10] = v.into(); + pub fn nth10(mut self, v: Byte) -> Self { + self.0[10] = v; self } - pub fn nth11(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[11] = v.into(); + pub fn nth11(mut self, v: Byte) -> Self { + self.0[11] = v; self } - pub fn nth12(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[12] = v.into(); + pub fn nth12(mut self, v: Byte) -> Self { + self.0[12] = v; self } - pub fn nth13(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[13] = v.into(); + pub fn nth13(mut self, v: Byte) -> Self { + self.0[13] = v; self } - pub fn nth14(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[14] = v.into(); + pub fn nth14(mut self, v: Byte) -> Self { + self.0[14] = v; self } - pub fn nth15(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[15] = v.into(); + pub fn nth15(mut self, v: Byte) -> Self { + self.0[15] = v; self } - pub fn nth16(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[16] = v.into(); + pub fn nth16(mut self, v: Byte) -> Self { + self.0[16] = v; self } - pub fn nth17(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[17] = v.into(); + pub fn nth17(mut self, v: Byte) -> Self { + self.0[17] = v; self } - pub fn nth18(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[18] = v.into(); + pub fn nth18(mut self, v: Byte) -> Self { + self.0[18] = v; self } - pub fn nth19(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[19] = v.into(); + pub fn nth19(mut self, v: Byte) -> Self { + self.0[19] = v; self } - pub fn nth20(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[20] = v.into(); + pub fn nth20(mut self, v: Byte) -> Self { + self.0[20] = v; self } - pub fn nth21(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[21] = v.into(); + pub fn nth21(mut self, v: Byte) -> Self { + self.0[21] = v; self } - pub fn nth22(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[22] = v.into(); + pub fn nth22(mut self, v: Byte) -> Self { + self.0[22] = v; self } - pub fn nth23(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[23] = v.into(); + pub fn nth23(mut self, v: Byte) -> Self { + self.0[23] = v; self } - pub fn nth24(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[24] = v.into(); + pub fn nth24(mut self, v: Byte) -> Self { + self.0[24] = v; self } - pub fn nth25(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[25] = v.into(); + pub fn nth25(mut self, v: Byte) -> Self { + self.0[25] = v; self } - pub fn nth26(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[26] = v.into(); + pub fn nth26(mut self, v: Byte) -> Self { + self.0[26] = v; self } - pub fn nth27(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[27] = v.into(); + pub fn nth27(mut self, v: Byte) -> Self { + self.0[27] = v; self } - pub fn nth28(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[28] = v.into(); + pub fn nth28(mut self, v: Byte) -> Self { + self.0[28] = v; self } - pub fn nth29(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[29] = v.into(); + pub fn nth29(mut self, v: Byte) -> Self { + self.0[29] = v; self } - pub fn nth30(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[30] = v.into(); + pub fn nth30(mut self, v: Byte) -> Self { + self.0[30] = v; self } - pub fn nth31(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[31] = v.into(); + pub fn nth31(mut self, v: Byte) -> Self { + self.0[31] = v; self } } @@ -1769,87 +1403,6 @@ impl molecule::prelude::Builder for Byte32Builder { Byte32::new_unchecked(inner.into()) } } -impl From<[Byte; 32usize]> for Byte32 { - fn from(value: [Byte; 32usize]) -> Self { - Self::new_builder().set(value).build() - } -} -impl ::core::convert::TryFrom<&[Byte]> for Byte32 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[Byte]) -> Result { - Ok(Self::new_builder() - .set(<&[Byte; 32usize]>::try_from(value)?.clone()) - .build()) - } -} -impl From for [Byte; 32usize] { - #[track_caller] - fn from(value: Byte32) -> Self { - [ - value.nth0(), - value.nth1(), - value.nth2(), - value.nth3(), - value.nth4(), - value.nth5(), - value.nth6(), - value.nth7(), - value.nth8(), - value.nth9(), - value.nth10(), - value.nth11(), - value.nth12(), - value.nth13(), - value.nth14(), - value.nth15(), - value.nth16(), - value.nth17(), - value.nth18(), - value.nth19(), - value.nth20(), - value.nth21(), - value.nth22(), - value.nth23(), - value.nth24(), - value.nth25(), - value.nth26(), - value.nth27(), - value.nth28(), - value.nth29(), - value.nth30(), - value.nth31(), - ] - } -} -impl From<[u8; 32usize]> for Byte32 { - fn from(value: [u8; 32usize]) -> Self { - Byte32Reader::new_unchecked(&value).to_entity() - } -} -impl ::core::convert::TryFrom<&[u8]> for Byte32 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[u8]) -> Result { - Ok(<[u8; 32usize]>::try_from(value)?.into()) - } -} -impl From for [u8; 32usize] { - #[track_caller] - fn from(value: Byte32) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From> for &'a [u8; 32usize] { - #[track_caller] - fn from(value: Byte32Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From<&'a Byte32Reader<'a>> for &'a [u8; 32usize] { - #[track_caller] - fn from(value: &'a Byte32Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} #[derive(Clone)] pub struct Uint256(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Uint256 { @@ -2196,7 +1749,6 @@ impl<'r> molecule::prelude::Reader<'r> for Uint256Reader<'r> { Ok(()) } } -#[derive(Clone)] pub struct Uint256Builder(pub(crate) [Byte; 32]); impl ::core::fmt::Debug for Uint256Builder { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { @@ -2245,235 +1797,136 @@ impl Uint256Builder { pub const TOTAL_SIZE: usize = 32; pub const ITEM_SIZE: usize = 1; pub const ITEM_COUNT: usize = 32; - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into<[Byte; 32]>, - { - self.0 = v.into(); + pub fn set(mut self, v: [Byte; 32]) -> Self { + self.0 = v; self } - pub fn nth0(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[0] = v.into(); + pub fn nth0(mut self, v: Byte) -> Self { + self.0[0] = v; self } - pub fn nth1(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[1] = v.into(); + pub fn nth1(mut self, v: Byte) -> Self { + self.0[1] = v; self } - pub fn nth2(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[2] = v.into(); + pub fn nth2(mut self, v: Byte) -> Self { + self.0[2] = v; self } - pub fn nth3(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[3] = v.into(); + pub fn nth3(mut self, v: Byte) -> Self { + self.0[3] = v; self } - pub fn nth4(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[4] = v.into(); + pub fn nth4(mut self, v: Byte) -> Self { + self.0[4] = v; self } - pub fn nth5(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[5] = v.into(); + pub fn nth5(mut self, v: Byte) -> Self { + self.0[5] = v; self } - pub fn nth6(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[6] = v.into(); + pub fn nth6(mut self, v: Byte) -> Self { + self.0[6] = v; self } - pub fn nth7(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[7] = v.into(); + pub fn nth7(mut self, v: Byte) -> Self { + self.0[7] = v; self } - pub fn nth8(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[8] = v.into(); + pub fn nth8(mut self, v: Byte) -> Self { + self.0[8] = v; self } - pub fn nth9(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[9] = v.into(); + pub fn nth9(mut self, v: Byte) -> Self { + self.0[9] = v; self } - pub fn nth10(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[10] = v.into(); + pub fn nth10(mut self, v: Byte) -> Self { + self.0[10] = v; self } - pub fn nth11(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[11] = v.into(); + pub fn nth11(mut self, v: Byte) -> Self { + self.0[11] = v; self } - pub fn nth12(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[12] = v.into(); + pub fn nth12(mut self, v: Byte) -> Self { + self.0[12] = v; self } - pub fn nth13(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[13] = v.into(); + pub fn nth13(mut self, v: Byte) -> Self { + self.0[13] = v; self } - pub fn nth14(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[14] = v.into(); + pub fn nth14(mut self, v: Byte) -> Self { + self.0[14] = v; self } - pub fn nth15(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[15] = v.into(); + pub fn nth15(mut self, v: Byte) -> Self { + self.0[15] = v; self } - pub fn nth16(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[16] = v.into(); + pub fn nth16(mut self, v: Byte) -> Self { + self.0[16] = v; self } - pub fn nth17(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[17] = v.into(); + pub fn nth17(mut self, v: Byte) -> Self { + self.0[17] = v; self } - pub fn nth18(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[18] = v.into(); + pub fn nth18(mut self, v: Byte) -> Self { + self.0[18] = v; self } - pub fn nth19(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[19] = v.into(); + pub fn nth19(mut self, v: Byte) -> Self { + self.0[19] = v; self } - pub fn nth20(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[20] = v.into(); + pub fn nth20(mut self, v: Byte) -> Self { + self.0[20] = v; self } - pub fn nth21(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[21] = v.into(); + pub fn nth21(mut self, v: Byte) -> Self { + self.0[21] = v; self } - pub fn nth22(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[22] = v.into(); + pub fn nth22(mut self, v: Byte) -> Self { + self.0[22] = v; self } - pub fn nth23(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[23] = v.into(); + pub fn nth23(mut self, v: Byte) -> Self { + self.0[23] = v; self } - pub fn nth24(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[24] = v.into(); + pub fn nth24(mut self, v: Byte) -> Self { + self.0[24] = v; self } - pub fn nth25(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[25] = v.into(); + pub fn nth25(mut self, v: Byte) -> Self { + self.0[25] = v; self } - pub fn nth26(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[26] = v.into(); + pub fn nth26(mut self, v: Byte) -> Self { + self.0[26] = v; self } - pub fn nth27(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[27] = v.into(); + pub fn nth27(mut self, v: Byte) -> Self { + self.0[27] = v; self } - pub fn nth28(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[28] = v.into(); + pub fn nth28(mut self, v: Byte) -> Self { + self.0[28] = v; self } - pub fn nth29(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[29] = v.into(); + pub fn nth29(mut self, v: Byte) -> Self { + self.0[29] = v; self } - pub fn nth30(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[30] = v.into(); + pub fn nth30(mut self, v: Byte) -> Self { + self.0[30] = v; self } - pub fn nth31(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0[31] = v.into(); + pub fn nth31(mut self, v: Byte) -> Self { + self.0[31] = v; self } } @@ -2525,87 +1978,6 @@ impl molecule::prelude::Builder for Uint256Builder { Uint256::new_unchecked(inner.into()) } } -impl From<[Byte; 32usize]> for Uint256 { - fn from(value: [Byte; 32usize]) -> Self { - Self::new_builder().set(value).build() - } -} -impl ::core::convert::TryFrom<&[Byte]> for Uint256 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[Byte]) -> Result { - Ok(Self::new_builder() - .set(<&[Byte; 32usize]>::try_from(value)?.clone()) - .build()) - } -} -impl From for [Byte; 32usize] { - #[track_caller] - fn from(value: Uint256) -> Self { - [ - value.nth0(), - value.nth1(), - value.nth2(), - value.nth3(), - value.nth4(), - value.nth5(), - value.nth6(), - value.nth7(), - value.nth8(), - value.nth9(), - value.nth10(), - value.nth11(), - value.nth12(), - value.nth13(), - value.nth14(), - value.nth15(), - value.nth16(), - value.nth17(), - value.nth18(), - value.nth19(), - value.nth20(), - value.nth21(), - value.nth22(), - value.nth23(), - value.nth24(), - value.nth25(), - value.nth26(), - value.nth27(), - value.nth28(), - value.nth29(), - value.nth30(), - value.nth31(), - ] - } -} -impl From<[u8; 32usize]> for Uint256 { - fn from(value: [u8; 32usize]) -> Self { - Uint256Reader::new_unchecked(&value).to_entity() - } -} -impl ::core::convert::TryFrom<&[u8]> for Uint256 { - type Error = ::core::array::TryFromSliceError; - fn try_from(value: &[u8]) -> Result { - Ok(<[u8; 32usize]>::try_from(value)?.into()) - } -} -impl From for [u8; 32usize] { - #[track_caller] - fn from(value: Uint256) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From> for &'a [u8; 32usize] { - #[track_caller] - fn from(value: Uint256Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} -impl<'a> From<&'a Uint256Reader<'a>> for &'a [u8; 32usize] { - #[track_caller] - fn from(value: &'a Uint256Reader<'a>) -> Self { - ::core::convert::TryFrom::try_from(value.as_slice()).unwrap() - } -} #[derive(Clone)] pub struct Bytes(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Bytes { @@ -2779,7 +2151,7 @@ impl<'r> molecule::prelude::Reader<'r> for BytesReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct BytesBuilder(pub(crate) Vec); impl BytesBuilder { pub const ITEM_SIZE: usize = 1; @@ -2787,24 +2159,20 @@ impl BytesBuilder { self.0 = v; self } - pub fn push(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0.push(v.into()); + pub fn push(mut self, v: Byte) -> Self { + self.0.push(v); self } pub fn extend>(mut self, iter: T) -> Self { - self.0.extend(iter); + for elem in iter { + self.0.push(elem); + } self } - pub fn replace(&mut self, index: usize, v: T) -> Option - where - T: ::core::convert::Into, - { + pub fn replace(&mut self, index: usize, v: Byte) -> Option { self.0 .get_mut(index) - .map(|item| ::core::mem::replace(item, v.into())) + .map(|item| ::core::mem::replace(item, v)) } } impl molecule::prelude::Builder for BytesBuilder { @@ -2853,30 +2221,6 @@ impl ::core::iter::IntoIterator for Bytes { BytesIterator(self, 0, len) } } -impl ::core::iter::FromIterator for Bytes { - fn from_iter>(iter: T) -> Self { - Self::new_builder().extend(iter).build() - } -} -impl From> for Bytes { - fn from(v: Vec) -> Self { - Self::new_builder().set(v).build() - } -} -impl ::core::iter::FromIterator for Bytes { - fn from_iter>(iter: T) -> Self { - Self::new_builder() - .extend(iter.into_iter().map(Into::into)) - .build() - } -} -impl From> for Bytes { - fn from(v: Vec) -> Self { - Self::new_builder() - .set(v.into_iter().map(Into::into).collect()) - .build() - } -} #[derive(Clone)] pub struct BytesOpt(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BytesOpt { @@ -3011,14 +2355,11 @@ impl<'r> molecule::prelude::Reader<'r> for BytesOptReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct BytesOptBuilder(pub(crate) Option); impl BytesOptBuilder { - pub fn set(mut self, v: T) -> Self - where - T: ::core::convert::Into>, - { - self.0 = v.into(); + pub fn set(mut self, v: Option) -> Self { + self.0 = v; self } } @@ -3044,11 +2385,6 @@ impl molecule::prelude::Builder for BytesOptBuilder { BytesOpt::new_unchecked(inner.into()) } } -impl From for BytesOpt { - fn from(value: Bytes) -> Self { - Self::new_builder().set(Some(value)).build() - } -} #[derive(Clone)] pub struct BytesOptVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BytesOptVec { @@ -3272,31 +2608,27 @@ impl<'r> molecule::prelude::Reader<'r> for BytesOptVecReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct BytesOptVecBuilder(pub(crate) Vec); impl BytesOptVecBuilder { pub fn set(mut self, v: Vec) -> Self { self.0 = v; self } - pub fn push(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0.push(v.into()); + pub fn push(mut self, v: BytesOpt) -> Self { + self.0.push(v); self } pub fn extend>(mut self, iter: T) -> Self { - self.0.extend(iter); + for elem in iter { + self.0.push(elem); + } self } - pub fn replace(&mut self, index: usize, v: T) -> Option - where - T: ::core::convert::Into, - { + pub fn replace(&mut self, index: usize, v: BytesOpt) -> Option { self.0 .get_mut(index) - .map(|item| ::core::mem::replace(item, v.into())) + .map(|item| ::core::mem::replace(item, v)) } } impl molecule::prelude::Builder for BytesOptVecBuilder { @@ -3393,16 +2725,6 @@ impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for BytesOptVecReaderIterator<' self.2 - self.1 } } -impl ::core::iter::FromIterator for BytesOptVec { - fn from_iter>(iter: T) -> Self { - Self::new_builder().extend(iter).build() - } -} -impl From> for BytesOptVec { - fn from(v: Vec) -> Self { - Self::new_builder().set(v).build() - } -} #[derive(Clone)] pub struct BytesVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BytesVec { @@ -3626,31 +2948,27 @@ impl<'r> molecule::prelude::Reader<'r> for BytesVecReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct BytesVecBuilder(pub(crate) Vec); impl BytesVecBuilder { pub fn set(mut self, v: Vec) -> Self { self.0 = v; self } - pub fn push(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0.push(v.into()); + pub fn push(mut self, v: Bytes) -> Self { + self.0.push(v); self } pub fn extend>(mut self, iter: T) -> Self { - self.0.extend(iter); + for elem in iter { + self.0.push(elem); + } self } - pub fn replace(&mut self, index: usize, v: T) -> Option - where - T: ::core::convert::Into, - { + pub fn replace(&mut self, index: usize, v: Bytes) -> Option { self.0 .get_mut(index) - .map(|item| ::core::mem::replace(item, v.into())) + .map(|item| ::core::mem::replace(item, v)) } } impl molecule::prelude::Builder for BytesVecBuilder { @@ -3747,16 +3065,6 @@ impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for BytesVecReaderIterator<'t, self.2 - self.1 } } -impl ::core::iter::FromIterator for BytesVec { - fn from_iter>(iter: T) -> Self { - Self::new_builder().extend(iter).build() - } -} -impl From> for BytesVec { - fn from(v: Vec) -> Self { - Self::new_builder().set(v).build() - } -} #[derive(Clone)] pub struct Byte32Vec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Byte32Vec { @@ -3936,7 +3244,7 @@ impl<'r> molecule::prelude::Reader<'r> for Byte32VecReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct Byte32VecBuilder(pub(crate) Vec); impl Byte32VecBuilder { pub const ITEM_SIZE: usize = 32; @@ -3944,24 +3252,20 @@ impl Byte32VecBuilder { self.0 = v; self } - pub fn push(mut self, v: T) -> Self - where - T: ::core::convert::Into, - { - self.0.push(v.into()); + pub fn push(mut self, v: Byte32) -> Self { + self.0.push(v); self } pub fn extend>(mut self, iter: T) -> Self { - self.0.extend(iter); + for elem in iter { + self.0.push(elem); + } self } - pub fn replace(&mut self, index: usize, v: T) -> Option - where - T: ::core::convert::Into, - { + pub fn replace(&mut self, index: usize, v: Byte32) -> Option { self.0 .get_mut(index) - .map(|item| ::core::mem::replace(item, v.into())) + .map(|item| ::core::mem::replace(item, v)) } } impl molecule::prelude::Builder for Byte32VecBuilder { @@ -4033,16 +3337,6 @@ impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for Byte32VecReaderIterator<'t, self.2 - self.1 } } -impl ::core::iter::FromIterator for Byte32Vec { - fn from_iter>(iter: T) -> Self { - Self::new_builder().extend(iter).build() - } -} -impl From> for Byte32Vec { - fn from(v: Vec) -> Self { - Self::new_builder().set(v).build() - } -} #[derive(Clone)] pub struct ScriptOpt(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for ScriptOpt { @@ -4177,14 +3471,11 @@ impl<'r> molecule::prelude::Reader<'r> for ScriptOptReader<'r> { Ok(()) } } -#[derive(Clone, Debug, Default)] +#[derive(Debug, Default)] pub struct ScriptOptBuilder(pub(crate) Option