Skip to content

Commit

Permalink
fix: fix review issue by labs
Browse files Browse the repository at this point in the history
  • Loading branch information
XuNeal committed Jan 25, 2024
1 parent 5f8c948 commit e465bbc
Show file tree
Hide file tree
Showing 20 changed files with 234 additions and 121 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions imkey-core/ikc-wallet/coin-tron/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ impl TronSigner {
}
false => input.message.into_bytes(),
};

// this code is from tron wallet
let header = match input.is_tron_header {
true => "\x19TRON Signed Message:\n32".as_bytes(),
false => "\x19Ethereum Signed Message:\n32".as_bytes(),
Expand Down
10 changes: 6 additions & 4 deletions token-core/tcx-btc-kin/src/bch_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ fn remove_bch_prefix(addr: &str) -> String {
if let Some(sep) = addr.rfind(':') {
if addr.len() > sep + 1 {
return addr.split_at(sep + 1).1.to_owned();
} else {
return "".to_string();
}
}
addr.to_owned()
Expand Down Expand Up @@ -107,7 +109,6 @@ mod tests {
use tcx_common::FromHex;

use crate::address::WIFDisplay;
use crate::BtcKinAddress;
use tcx_constants::coin_info::coin_info_from_param;
use tcx_constants::{CoinInfo, CurveType};
use tcx_keystore::Address;
Expand Down Expand Up @@ -210,7 +211,8 @@ mod tests {
remove_bch_prefix("qq2ug6v04ht22n0daxxzl0rzlvsmzwcdwuymj77ymy"),
"qq2ug6v04ht22n0daxxzl0rzlvsmzwcdwuymj77ymy"
);
assert_eq!(remove_bch_prefix("bitcoincash:"), "bitcoincash:");

assert_eq!(remove_bch_prefix("bitcoincash:"), "");
assert_eq!(
remove_bch_prefix("qq2ug6v04ht22n0daxxzl0rzlvsmzwcdwuymj77ymy"),
"qq2ug6v04ht22n0daxxzl0rzlvsmzwcdwuymj77ymy"
Expand Down Expand Up @@ -282,9 +284,9 @@ mod tests {
TypedPrivateKey::from_slice(CurveType::SECP256k1, &Vec::from_hex(prv_str).unwrap())
.unwrap()
.public_key();
let mut coin_info = CoinInfo {
let coin_info = CoinInfo {
coin: "BITCOINCASH".to_string(),
derivation_path: "m/44'/2'/0'/0/0".to_string(),
derivation_path: "".to_string(),
curve: CurveType::SECP256k1,
network: "MAINNET".to_string(),
seg_wit: "NONE".to_string(),
Expand Down
1 change: 1 addition & 0 deletions token-core/tcx-btc-kin/src/bitcoin_cash_sighash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ impl BitcoinCashSighash {
let mut single_enc = Sighash::engine();
self.tx.output[input_index].consensus_encode(&mut single_enc)?;
Sighash::from_engine(single_enc).consensus_encode(&mut writer)?;
// padding zero hash, copy form bitcoin core
} else {
zero_hash.consensus_encode(&mut writer)?;
}
Expand Down
4 changes: 2 additions & 2 deletions token-core/tcx-btc-kin/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ mod tests {
vout: 0,
amount: 100000,
address: "qzld7dav7d2sfjdl6x9snkvf6raj8lfxjcj5fa8y2r".to_string(),
derived_path: "m/44'/145'/0'/1/0".to_string(),
derived_path: "".to_string(),
}];

let tx_input = BtcKinTxInput {
Expand All @@ -635,7 +635,7 @@ mod tests {
chain_type: BITCOINCASH.to_string(),
network: "MAINNET".to_string(),
seg_wit: "NONE".to_string(),
derivation_path: "m/44'/145'/0'/0/0".to_string(),
derivation_path: "".to_string(),
};

let actual = ks.sign_transaction(&params, &tx_input).unwrap();
Expand Down
7 changes: 6 additions & 1 deletion token-core/tcx-eos/src/signer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::transaction::{EosMessageInput, EosMessageOutput, EosTxInput, EosTxOutput, SigData};
use tcx_keystore::{
Keystore, MessageSigner, Result, SignatureParameters, Signer, TransactionSigner,
tcx_ensure, Keystore, MessageSigner, Result, SignatureParameters, Signer, TransactionSigner,
};

use anyhow::anyhow;
use bitcoin::util::base58;
use tcx_common::{ripemd160, sha256, FromHex, ToHex};

Expand Down Expand Up @@ -58,6 +59,10 @@ impl MessageSigner<EosMessageInput, EosMessageOutput> for Keystore {
sha256(bytes).to_vec()
};

tcx_ensure!(
data_hashed.len() == 32,
anyhow!("{}", "hashed data must be 32 bytes")
);
let sign_result =
self.secp256k1_ecdsa_sign_recoverable(data_hashed.as_slice(), &params.derivation_path)?;
// EOS need v r s
Expand Down
1 change: 1 addition & 0 deletions token-core/tcx-eth2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ tcx-keystore = { path = "../tcx-keystore" }
tcx-constants = { path = "../tcx-constants" }
tcx-primitive = { path = "../tcx-primitive" }
tcx-crypto = { path = "../tcx-crypto" }
tcx-eth = { path = "../tcx-eth" }

prost = "=0.11.2"
bytes = "=1.4.0"
Expand Down
76 changes: 5 additions & 71 deletions token-core/tcx-eth2/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ use crate::Error;
use keccak_hash;
use regex::Regex;
use tcx_common::{FromHex, ToHex};
use tcx_keystore::{Keystore, Result, Signer};
use tcx_constants::CoinInfo;
use tcx_eth::address::EthAddress;
use tcx_keystore::{Address, Keystore, Result, Signer};

impl SignBlsToExecutionChangeParam {
pub fn sign_bls_to_execution_change(
&self,
keystore: &mut Keystore,
) -> Result<SignBlsToExecutionChangeResult> {
let valid_result = is_valid_address(self.eth1_withdrawal_address.as_str())?;
let valid_result =
EthAddress::is_valid(self.eth1_withdrawal_address.as_str(), &CoinInfo::default());
if !valid_result {
return Err(Error::InvalidEthAddress.into());
}
Expand Down Expand Up @@ -50,72 +53,3 @@ impl SignBlsToExecutionChangeParam {
Ok(SignBlsToExecutionChangeResult { signeds })
}
}

fn is_valid_address(address: &str) -> Result<bool> {
if address.is_empty() || address.len() != 42 || !address.starts_with("0x") {
return Ok(false);
}

let eth_addr_regex = Regex::new(r"^(0x)?[0-9a-fA-F]{40}$").unwrap();
if !eth_addr_regex.is_match(address.as_ref()) {
return Ok(false);
}

let address_temp = &address[2..];
let lower_address_bytes = address_temp.to_lowercase();
let mut hash = [0u8; 32];
keccak_hash::keccak_256(lower_address_bytes.as_bytes(), &mut hash);
let hash_str = hash.to_hex();

for (i, c) in address_temp.chars().enumerate() {
let char_int = u8::from_str_radix(&hash_str.chars().nth(i).unwrap().to_string(), 16)?;
if (c.is_uppercase() && char_int <= 7) || (c.is_lowercase() && char_int > 7) {
return Ok(false);
}
}
Ok(true)
}

#[cfg(test)]
mod test {
use crate::signer::is_valid_address;

#[test]
fn test_is_valid_address() {
let eth_address = "0x8c1Ff978036F2e9d7CC382Eff7B4c8c53C22ac15";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(true, result);

let eth_address = "0x52908400098527886E0F7030069857D2E4169EE7";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(true, result);

let eth_address = "0xde709f2102306220921060314715629080e2fb77";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(true, result);

let eth_address = "0x8C1Ff978036F2e9d7CC382Eff7B4c8c53C22ac15";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(false, result);

let eth_address = "0x8c1Ff978036F2e9d7CC382Eff7B4c8c53C22ac1500";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(false, result);

let eth_address = "8c1Ff978036F2e9d7CC382Eff7B4c8c53C22ac15";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(false, result);

let eth_address = "0x8c1Ff978036F2e9d7CC382Eff7B4c8c53C22ac1*";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(false, result);

let eth_address = "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(true, result);

let eth_address = "0x80427Ae1f55bCf60ee4CD2db7549b8BC69a74303";
let result = is_valid_address(eth_address).unwrap();
assert_eq!(true, result);
}
}
3 changes: 3 additions & 0 deletions token-core/tcx-filecoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ pub enum Error {

#[error("invalid_number")]
InvalidNumber,

#[error("invalid_method_id")]
InvalidMethodId,
}

pub mod filecoin {
Expand Down
47 changes: 45 additions & 2 deletions token-core/tcx-filecoin/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use forest_vm::{Serialized, TokenAmount};
use std::convert::TryFrom;
use std::str::FromStr;
use tcx_constants::CurveType;
use tcx_keystore::{Keystore, Result, SignatureParameters, Signer, TransactionSigner};
use tcx_keystore::{tcx_ensure, Keystore, Result, SignatureParameters, Signer, TransactionSigner};

impl TryFrom<&UnsignedMessage> for ForestUnsignedMessage {
type Error = crate::Error;
Expand All @@ -30,6 +30,7 @@ impl TryFrom<&UnsignedMessage> for ForestUnsignedMessage {
let message_params_bytes =
base64::decode(&message.params).map_err(|_| Error::InvalidParam)?;
let params = Serialized::new(message_params_bytes);
tcx_ensure!(message.method == 0, Error::InvalidMethodId);

let tmp = ForestUnsignedMessage::builder()
.to(to)
Expand Down Expand Up @@ -84,6 +85,7 @@ impl TransactionSigner<UnsignedMessage, SignedMessage> for Keystore {
&sign_context.derivation_path,
"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",
)?;
// use unsigned_message https://github.com/filecoin-project/lotus/issues/101
cid = unsigned_message.cid()?;
}
_ => return Err(Error::InvalidCurveType.into()),
Expand Down Expand Up @@ -154,6 +156,47 @@ mod tests {
assert_eq!(signature.data, "MCTI+WjYRozaU/7gYWAwSeOixkSmIHDWHwsU1NVPTrtH4IkXPUrgRcZh4DduJqvHLzoek31LYZxhWkGAzd0j9wA=");
}

#[test]
fn test_invalid_method_id() {
let unsigned_message = UnsignedMessage {
to: "f1zlkjwo5pnm6petm4u4luj6gb6e64eecrw4t4stq".to_string(),
from: "f12i3bop43tprlnymx2c75u6uvlq7iur2rcd7qsey".to_string(),
nonce: 1,
value: "10000000000000000".to_string(),
gas_limit: 491585,
gas_fee_cap: "151367".to_string(),
gas_premium: "150313".to_string(),
method: 1,
params: "".to_string(),
};

let key_info =
KeyInfo::from_lotus(
&Vec::from_hex("7b2254797065223a22736563703235366b31222c22507269766174654b6579223a222f5059574777574e577a58614d5675437a613958502b314b4a695a4474696f4c76777863754268783041553d227d").unwrap()).unwrap();
let private_key = key_info.decode_private_key().unwrap();
let mut ks = Keystore::from_private_key(
&private_key.to_hex(),
"Password",
CurveType::SECP256k1,
Metadata::default(),
None,
)
.unwrap();
ks.unlock_by_password("Password").unwrap();

let sign_context = SignatureParameters {
curve: CurveType::SECP256k1,
derivation_path: "".to_string(),
chain_type: "FILECOIN".to_string(),
..Default::default()
};
let signed_message = ks.sign_transaction(&sign_context, &unsigned_message);
assert_eq!(
format!("{}", signed_message.err().unwrap()),
"invalid_method_id"
);
}

#[test]
fn test_sign_bls() {
let unsigned_message = UnsignedMessage {
Expand All @@ -175,7 +218,7 @@ mod tests {
let mut ks = Keystore::from_private_key(
&private_key.to_hex(),
"Password",
CurveType::SECP256k1,
CurveType::BLS,
Metadata::default(),
None,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,39 @@
{"address":"2MwN441dq8qudMvtM5eLVwC3u4zfKuGSQAB","imTokenMeta":{"source":"RECOVERED_IDENTITY","timestamp":"1703213076.948025","backup":[],"mode":"normal","name":"BTC","version":"iOS-2.14.1.1742","passwordHint":"","chain":"BITCOIN","network":"TESTNET","segWit":"P2WPKH"},"id":"00fc0804-7cea-46d8-9e95-ed1efac65358","encMnemonic":{"nonce":"406c972f073ebf5b9102d262e6713408","encStr":"76b940d06641023f995cffde6ee9c4bc7c063a780897b5debd619aafc769b37db684eafb10dd48c3c3cbcb810952bb4455984fde5aa34a1dfb4d5ad93293c0d3f3a78124639a4530b4c2"},"xpub":"tpubDCwNET9ErXmBracx3ZBfi6rXQZRjYkpitFe23FAW9M3RcCw4aveNC4SAV5yYrFDjtP3b46eFfv4VtiYP3EXoTZsbnJia2yNznExS8EEcACv","crypto":{"kdfparams":{"dklen":32,"r":8,"salt":"8fac63b4cc6d75817269a380bc8107572ecba3a8fe1ab87e46e30ab696ce2320","p":1,"n":262144},"mac":"6daa39ee727416a135b02d6183c71624de0b7cf74fb3a3d1562488e66f308c76","cipher":"aes-128-ctr","ciphertext":"cdde8cafd9eff3f9715ef40577913e2ded3b8a9f009781d3367e4a1b02e95894c45ab6ef2658e7ef99b8437cba0f05f5c12caca60e97745b71581075f086a57afac8f626f3d2f7c94813edb6eb26b5cf8147fd32419a3abc762d71dc2be77d555cb75e983a74fa45f7b08e59ce7945","cipherparams":{"iv":"a575c61a89577eea45af32df6aa4005a"},"kdf":"scrypt"},"version":44,"mnemonicPath":"m\/49'\/1'\/0'"}
{
"address": "2MwN441dq8qudMvtM5eLVwC3u4zfKuGSQAB",
"imTokenMeta": {
"source": "RECOVERED_IDENTITY",
"timestamp": "1703213076.948025",
"backup": [],
"mode": "normal",
"name": "BTC",
"version": "iOS-2.14.1.1742",
"passwordHint": "",
"chain": "BITCOIN",
"network": "TESTNET",
"segWit": "P2WPKH"
},
"id": "00fc0804-7cea-46d8-9e95-ed1efac65358",
"encMnemonic": {
"nonce": "406c972f073ebf5b9102d262e6713408",
"encStr": "76b940d06641023f995cffde6ee9c4bc7c063a780897b5debd619aafc769b37db684eafb10dd48c3c3cbcb810952bb4455984fde5aa34a1dfb4d5ad93293c0d3f3a78124639a4530b4c2"
},
"xpub": "tpubDCwNET9ErXmBracx3ZBfi6rXQZRjYkpitFe23FAW9M3RcCw4aveNC4SAV5yYrFDjtP3b46eFfv4VtiYP3EXoTZsbnJia2yNznExS8EEcACv",
"crypto": {
"kdfparams": {
"dklen": 32,
"r": 8,
"salt": "8fac63b4cc6d75817269a380bc8107572ecba3a8fe1ab87e46e30ab696ce2320",
"p": 1,
"n": 262144
},
"mac": "6daa39ee727416a135b02d6183c71624de0b7cf74fb3a3d1562488e66f308c76",
"cipher": "aes-128-ctr",
"ciphertext": "cdde8cafd9eff3f9715ef40577913e2ded3b8a9f009781d3367e4a1b02e95894c45ab6ef2658e7ef99b8437cba0f05f5c12caca60e97745b71581075f086a57afac8f626f3d2f7c94813edb6eb26b5cf8147fd32419a3abc762d71dc2be77d555cb75e983a74fa45f7b08e59ce7945",
"cipherparams": {
"iv": "a575c61a89577eea45af32df6aa4005a"
},
"kdf": "scrypt"
},
"version": 44,
"mnemonicPath": "m/49'/1'/0'"
}
Loading

0 comments on commit e465bbc

Please sign in to comment.