Skip to content

Commit

Permalink
Merge pull request #185 from nervina-labs/refactor-rust
Browse files Browse the repository at this point in the history
refactor rust language
  • Loading branch information
duanyytop authored Sep 5, 2023
2 parents 65938e0 + ff112ce commit f24e3b6
Show file tree
Hide file tree
Showing 46 changed files with 268 additions and 281 deletions.
8 changes: 4 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,10 @@ pub async fn get_issuer_info(params: Params) -> Result<Value, Error> {
lock_hash,
} = FetchIssuerReq::from_map(&map).map_err(rpc_err)?;
let lock_hash_ = if lock_script.is_some() {
blake2b_256(&lock_script.unwrap())
blake2b_256(lock_script.unwrap())
} else if address.is_some() {
let lock = script_from_address(address.unwrap()).map_err(rpc_err)?;
blake2b_256(&lock.as_slice())
blake2b_256(lock.as_slice())
} else {
lock_hash.unwrap()
};
Expand Down Expand Up @@ -350,10 +350,10 @@ pub async fn get_joyid_info(params: Params) -> Result<Value, Error> {
address,
} = FetchJoyIDReq::from_map(&map).map_err(rpc_err)?;
let lock_hash = if lock_script.is_some() {
blake2b_256(&lock_script.unwrap())
blake2b_256(lock_script.unwrap())
} else {
let lock = script_from_address(address.unwrap()).map_err(rpc_err)?;
blake2b_256(&lock.as_slice())
blake2b_256(lock.as_slice())
};
let joyid_info_opt = get_joyid_info_by_lock_hash(lock_hash).map_err(rpc_err)?;
parse_joyid_metadata_response(joyid_info_opt, tip_number()?).map_err(rpc_err)
Expand Down
4 changes: 2 additions & 2 deletions src/business/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn address_from_script(slice: &[u8]) -> Result<String, Error> {
Err(_e) => false,
};
let payload =
AddressPayload::from(Script::from_slice(slice).map_err(|_| Error::CKBScriptError)?);
AddressPayload::from(Script::from_slice(slice).map_err(|_| Error::CKBScriptInvalid)?);
let network = if is_mainnet {
NetworkType::Mainnet
} else {
Expand All @@ -23,7 +23,7 @@ pub fn address_from_script(slice: &[u8]) -> Result<String, Error> {
}

pub fn script_from_address(address: String) -> Result<Script, Error> {
let addr = Address::from_str(&address).map_err(|e| Error::CKBRPCError(e.to_string()))?;
let addr = Address::from_str(&address).map_err(|e| Error::CKBRPCInvalid(e))?;
let payload = addr.payload();
let script = Script::new_builder()
.hash_type(payload.hash_type().into())
Expand Down
6 changes: 3 additions & 3 deletions src/ckb/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub async fn get_cota_smt_root(lock_script: &[u8]) -> Result<Option<[u8; 32]>, E
ret.copy_from_slice(&cell_data[1..]);
Ok(Some(ret))
}
_ => Err(Error::CKBIndexerError(
_ => Err(Error::CKBIndexerInvalid(
"CoTA cell data length error".to_owned(),
)),
}
Expand Down Expand Up @@ -61,10 +61,10 @@ async fn build_rpc<T: DeserializeOwned>(method: &str, params: Option<Value>) ->
match output {
jsonrpc_core::response::Output::Success(success) => {
serde_json::from_value::<T>(success.result)
.map_err(|_e| Error::CKBIndexerError("Parse response error".to_owned()))
.map_err(|_e| Error::CKBIndexerInvalid("Parse response error".to_owned()))
}
jsonrpc_core::response::Output::Failure(failure) => {
Err(Error::CKBIndexerError(failure.error.message))
Err(Error::CKBIndexerInvalid(failure.error.message))
}
}
}
Expand Down
25 changes: 12 additions & 13 deletions src/ckb/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ pub async fn get_withdraw_info(
let mut client = ckb_node_client()?;
let block = client
.get_block_by_number(Uint64::from(block_number))
.map_err(|_e| Error::CKBRPCError("get_block_by_number".to_string()))?
.ok_or(Error::CKBRPCError("get_block error".to_string()))?;
.map_err(|_e| Error::CKBRPCInvalid("get_block_by_number".to_string()))?
.ok_or(Error::CKBRPCInvalid("get_block error".to_string()))?;
let block_hash = block.header.hash;
let block_number = block.header.inner.number.value();
let mut output_index = Uint32::default();
Expand All @@ -56,20 +56,19 @@ pub async fn get_withdraw_info(
let position = tx.inner.outputs.clone().into_iter().position(|output| {
let lock: Script = output.lock.clone().into();
let lock_ret: bool = blake2b_256(lock.as_slice()) == withdrawal_lock_hash;
let type_ret: bool = output.type_.clone().map_or(false, |type_: RPCScript| {
type_.code_hash.as_bytes() == &cota_code_hash
let type_ret: bool = output.type_.map_or(false, |type_: RPCScript| {
type_.code_hash.as_bytes() == cota_code_hash
});
lock_ret && type_ret
});
if position.is_some() {
output_index =
Uint32::from_slice(&(position.unwrap() as u32).to_be_bytes()).unwrap();
if let Some(pos) = position {
output_index = Uint32::from_slice(&(pos).to_be_bytes()).unwrap();
}
tx.hash.as_bytes() == &withdrawal_tx_hash
tx.hash.as_bytes() == withdrawal_tx_hash
})
.collect();
if txs.is_empty() {
return Err(Error::CKBRPCError(format!(
return Err(Error::CKBRPCInvalid(format!(
"The tx dose not exist in the block#{:?}",
block_number
)));
Expand All @@ -89,7 +88,7 @@ pub async fn get_withdraw_info(

let transaction_proof = client
.get_transaction_proof(vec![tx_view.hash], Some(block_hash.clone()))
.map_err(|_e| Error::CKBRPCError("get_transaction_proof".to_string()))?;
.map_err(|_e| Error::CKBRPCInvalid("get_transaction_proof".to_string()))?;
let tx_proof = get_tx_proof(transaction_proof);

let withdraw_info = WithdrawRawTx {
Expand All @@ -112,7 +111,7 @@ pub async fn get_node_tip_block_number() -> Result<u64, Error> {
let mut client = ckb_node_client()?;
let block_number = client
.get_tip_block_number()
.map_err(|_e| Error::CKBRPCError("get_tip_block_number".to_string()))?;
.map_err(|_e| Error::CKBRPCInvalid("get_tip_block_number".to_string()))?;
Ok(u64::from(block_number))
})
.await
Expand All @@ -124,8 +123,8 @@ pub async fn get_block_timestamp(block_number: u64) -> Result<u64, Error> {
let mut client = ckb_node_client()?;
let header = client
.get_header_by_number(BlockNumber::from(block_number))
.map_err(|_e| Error::CKBRPCError("get_header_by_number".to_string()))?
.ok_or(Error::CKBRPCError("get_header_by_number".to_string()))?;
.map_err(|_e| Error::CKBRPCInvalid("get_header_by_number".to_string()))?
.ok_or(Error::CKBRPCInvalid("get_header_by_number".to_string()))?;
Ok(header.inner.timestamp.value())
})
.await
Expand Down
6 changes: 3 additions & 3 deletions src/entries/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,19 +114,19 @@ pub async fn generate_claim_smt(
generate_history_smt(&mut claim_smt, claim_lock_hash, claim_smt_root)?;
claim_smt
.update_all(claim_update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
claim_smt.save_root_and_leaves(previous_leaves.clone())?;
claim_smt.commit()
})?;

let leaf_keys: Vec<H256> = claim_update_leaves.iter().map(|leave| leave.0).collect();
let claim_merkle_proof = claim_smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Claim SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Claim".to_string())
Error::SMTProofInvalid("Claim".to_string())
})?;
let claim_merkle_proof_compiled = claim_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Claim SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Claim".to_string())
Error::SMTProofInvalid("Claim".to_string())
})?;

let merkel_proof_vec: Vec<u8> = claim_merkle_proof_compiled.into();
Expand Down
8 changes: 4 additions & 4 deletions src/entries/claim_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn generate_claim_update_smt(
}
let is_receiver = sender_withdrawals
.iter()
.any(|withdrawal| &withdrawal.receiver_lock_script == &claim_lock_script);
.any(|withdrawal| withdrawal.receiver_lock_script == claim_lock_script);
if !is_receiver {
return Err(Error::CotaIdAndTokenIndexHasNotWithdrawn);
}
Expand Down Expand Up @@ -127,20 +127,20 @@ pub async fn generate_claim_update_smt(
generate_history_smt(&mut claim_smt, claim_lock_hash, claim_smt_root)?;
claim_smt
.update_all(claim_update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
claim_smt.save_root_and_leaves(previous_leaves.clone())?;
claim_smt.commit()
})?;

let leaf_keys: Vec<H256> = claim_update_leaves.iter().map(|leave| leave.0).collect();
let claim_update_merkle_proof = claim_smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Claim update SMT proof error: {:?}", e.to_string());
Error::SMTProofError("ClaimUpdate".to_string())
Error::SMTProofInvalid("ClaimUpdate".to_string())
})?;
let claim_update_merkle_proof_compiled =
claim_update_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Claim update SMT proof error: {:?}", e.to_string());
Error::SMTProofError("ClaimUpdate".to_string())
Error::SMTProofInvalid("ClaimUpdate".to_string())
})?;

let merkel_proof_vec: Vec<u8> = claim_update_merkle_proof_compiled.into();
Expand Down
6 changes: 3 additions & 3 deletions src/entries/define.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,19 @@ pub async fn generate_define_smt(
with_lock(lock_hash, || {
generate_history_smt(&mut smt, lock_hash, smt_root)?;
smt.update(key, value)
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
smt.save_root_and_leaves(previous_leaves.clone())?;
smt.commit()
})?;

let leaf_keys: Vec<H256> = update_leaves.iter().map(|leave| leave.0).collect();
let define_merkle_proof = smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Define SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Mint".to_string())
Error::SMTProofInvalid("Mint".to_string())
})?;
let define_merkle_proof_compiled = define_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Define SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Define".to_string())
Error::SMTProofInvalid("Define".to_string())
})?;

let merkel_proof_vec: Vec<u8> = define_merkle_proof_compiled.into();
Expand Down
22 changes: 11 additions & 11 deletions src/entries/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub async fn generate_ext_subkey_smt(
if let Some(leaf) = leaf_opt {
previous_leaves.push((key, H256::from(leaf.value)));
} else {
return Err(Error::CKBRPCError(
return Err(Error::CKBRPCInvalid(
"Extension old subkey value does not exist".to_string(),
));
}
Expand All @@ -67,20 +67,20 @@ pub async fn generate_ext_subkey_smt(
with_lock(lock_hash, || {
generate_history_smt(&mut smt, lock_hash, smt_root)?;
smt.update_all(update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
smt.save_root_and_leaves(previous_leaves.clone())?;
smt.commit()
})?;

let leaf_keys: Vec<H256> = update_leaves.iter().map(|leave| leave.0).collect();
let extension_merkle_proof = smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Extension subkey SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension subkey".to_string())
Error::SMTProofInvalid("Extension subkey".to_string())
})?;
let extension_merkle_proof_compiled =
extension_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Extension subkey SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension subkey".to_string())
Error::SMTProofInvalid("Extension subkey".to_string())
})?;

let merkel_proof_vec: Vec<u8> = extension_merkle_proof_compiled.into();
Expand Down Expand Up @@ -146,7 +146,7 @@ pub async fn generate_ext_social_smt(
if let Some(leaf) = leaf_opt {
previous_leaves.push((key, H256::from(leaf.value)));
} else {
return Err(Error::CKBRPCError(
return Err(Error::CKBRPCInvalid(
"Extension old social value does not exist".to_string(),
));
}
Expand All @@ -160,20 +160,20 @@ pub async fn generate_ext_social_smt(
with_lock(lock_hash, || {
generate_history_smt(&mut smt, lock_hash, smt_root)?;
smt.update_all(update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
smt.save_root_and_leaves(previous_leaves.clone())?;
smt.commit()
})?;

let leaf_keys: Vec<H256> = update_leaves.iter().map(|leave| leave.0).collect();
let extension_merkle_proof = smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Extension social SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension social".to_string())
Error::SMTProofInvalid("Extension social".to_string())
})?;
let extension_merkle_proof_compiled =
extension_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Extension social SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension social".to_string())
Error::SMTProofInvalid("Extension social".to_string())
})?;

let merkel_proof_vec: Vec<u8> = extension_merkle_proof_compiled.into();
Expand Down Expand Up @@ -245,17 +245,17 @@ pub async fn generate_adding_subkey_smt(
let transaction = &StoreTransaction::new(ROCKS_DB.transaction());
let mut smt = init_smt(transaction, lock_hash)?;
smt.update_all(update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;

let leaf_keys: Vec<H256> = update_leaves.iter().map(|leave| leave.0).collect();
let extension_merkle_proof = smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Extension subkey SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension subkey".to_string())
Error::SMTProofInvalid("Extension subkey".to_string())
})?;
let extension_merkle_proof_compiled =
extension_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Extension subkey SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Extension subkey".to_string())
Error::SMTProofInvalid("Extension subkey".to_string())
})?;

let merkel_proof_vec: Vec<u8> = extension_merkle_proof_compiled.into();
Expand Down
9 changes: 3 additions & 6 deletions src/entries/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,9 @@ fn generate_social_leaf_value(
recovery_mode: &u8,
must: &u8,
total: &u8,
signers: &Vec<Vec<u8>>,
signers: &[Vec<u8>],
) -> (SocialValue, H256) {
let friends: Vec<common::Bytes> = signers
.into_iter()
.map(|signer| vec_to_bytes(&signer))
.collect();
let friends: Vec<common::Bytes> = signers.iter().map(|signer| vec_to_bytes(signer)).collect();
let signers = LockScriptVecBuilder::default().set(friends).build();
let social_value = SocialValueBuilder::default()
.recovery_mode(Byte::from_slice(&[*recovery_mode]).unwrap())
Expand All @@ -271,7 +268,7 @@ pub fn with_lock<F>(lock_hash: [u8; 32], mut operator: F) -> Result<(), Error>
where
F: FnMut() -> Result<(), Error>,
{
let &(ref lock, ref cond) = &*Arc::clone(&SMT_LOCK);
let (lock, cond) = &*Arc::clone(&SMT_LOCK);
{
let mut set = lock.lock();
while !set.insert(lock_hash) {
Expand Down
6 changes: 3 additions & 3 deletions src/entries/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub async fn generate_mint_smt(mint_req: MintReq) -> Result<(H256, MintCotaNFTV1
with_lock(lock_hash, || {
generate_history_smt(&mut smt, lock_hash, smt_root)?;
smt.update_all(update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
smt.save_root_and_leaves(previous_leaves.clone())?;
smt.commit()
})?;
Expand All @@ -120,11 +120,11 @@ pub async fn generate_mint_smt(mint_req: MintReq) -> Result<(H256, MintCotaNFTV1
let leaf_keys: Vec<H256> = update_leaves.iter().map(|leave| leave.0).collect();
let mint_merkle_proof = smt.merkle_proof(leaf_keys.clone()).map_err(|e| {
error!("Mint SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Mint".to_string())
Error::SMTProofInvalid("Mint".to_string())
})?;
let mint_merkle_proof_compiled = mint_merkle_proof.compile(leaf_keys).map_err(|e| {
error!("Mint SMT proof error: {:?}", e.to_string());
Error::SMTProofError("Mint".to_string())
Error::SMTProofInvalid("Mint".to_string())
})?;
diff_time(start_time, "Generate mint smt proof");

Expand Down
14 changes: 7 additions & 7 deletions src/entries/sequential_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub async fn generate_sequential_transfer_smt(

if index == transfers_len - 1 {
current_withdrawal = withdrawals.first().unwrap().clone();
if &current_withdrawal.receiver_lock_script != &transfer_lock_script {
if current_withdrawal.receiver_lock_script != transfer_lock_script {
return Err(Error::CotaIdAndTokenIndexHasNotWithdrawn);
}
let is_claimed = is_exist_in_claim(
Expand Down Expand Up @@ -145,12 +145,12 @@ pub async fn generate_sequential_transfer_smt(
generate_history_smt(&mut transfer_smt, transfer_lock_hash, transfer_smt_root)?;
transfer_smt
.update_all(transfer_pervious_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
current_subkey_entries =
generate_subkey_smt(transfer_lock_hash, &subkey_opt, &transfer_smt)?;
transfer_smt
.update_all(transfer_update_leaves.clone())
.map_err(|e| Error::SMTError(e.to_string()))?;
.map_err(|e| Error::SMTInvalid(e.to_string()))?;
next_subkey_entries = generate_subkey_smt(transfer_lock_hash, &subkey_opt, &transfer_smt)?;
transfer_smt.save_root_and_leaves(previous_leaves.clone())?;
transfer_smt.commit()
Expand All @@ -159,10 +159,10 @@ pub async fn generate_sequential_transfer_smt(
let leaf_keys: Vec<H256> = transfer_update_leaves.iter().map(|leave| leave.0).collect();
let transfer_merkle_proof = transfer_smt
.merkle_proof(leaf_keys.clone())
.map_err(|_e| Error::SMTProofError("Transfer".to_string()))?;
.map_err(|_e| Error::SMTProofInvalid("Transfer".to_string()))?;
let transfer_merkle_proof_compiled = transfer_merkle_proof
.compile(leaf_keys)
.map_err(|_e| Error::SMTProofError("Transfer".to_string()))?;
.map_err(|_e| Error::SMTProofInvalid("Transfer".to_string()))?;

let transfer_merkel_proof_vec: Vec<u8> = transfer_merkle_proof_compiled.into();
let transfer_merkel_proof_bytes = BytesBuilder::default()
Expand Down Expand Up @@ -238,10 +238,10 @@ fn generate_subkey_smt(

let subkey_merkle_proof = smt
.merkle_proof(vec![key])
.map_err(|_| Error::SMTProofError("Subkey unlock".to_owned()))?;
.map_err(|_| Error::SMTProofInvalid("Subkey unlock".to_owned()))?;
let subkey_merkle_proof_compiled = subkey_merkle_proof
.compile(vec![key])
.map_err(|_| Error::SMTProofError("Subkey unlock".to_owned()))?;
.map_err(|_| Error::SMTProofInvalid("Subkey unlock".to_owned()))?;

let merkel_proof_vec: Vec<u8> = subkey_merkle_proof_compiled.into();
let merkel_proof_bytes = joyid_smt::common::BytesBuilder::default()
Expand Down
Loading

0 comments on commit f24e3b6

Please sign in to comment.