Skip to content

Commit

Permalink
feat: add overwrite_id to support reset password
Browse files Browse the repository at this point in the history
  • Loading branch information
XuNeal committed Jun 3, 2024
1 parent 5443bb2 commit 3d06fa9
Show file tree
Hide file tree
Showing 18 changed files with 640 additions and 113 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.7.1
2.7.2
2 changes: 1 addition & 1 deletion token-core/tcx-constants/src/coin_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn get_xpub_prefix(network: &str) -> Vec<u8> {
}
}
/// Blockchain basic config
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct CoinInfo {
pub coin: String,
pub derivation_path: String,
Expand Down
2 changes: 1 addition & 1 deletion token-core/tcx-keystore/src/keystore/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use tcx_constants::{CoinInfo, CurveType};
pub use self::{
guard::KeystoreGuard, hd::fingerprint_from_mnemonic, hd::fingerprint_from_seed,
hd::mnemonic_to_seed, hd::HdKeystore, private::fingerprint_from_private_key,
private::PrivateKeystore,
private::private_key_to_account, private::PrivateKeystore,
};

use crate::identity::Identity;
Expand Down
42 changes: 19 additions & 23 deletions token-core/tcx-keystore/src/keystore/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,24 @@ pub fn fingerprint_from_private_key(data: &[u8]) -> Result<String> {
Ok(hashed.to_0x_hex())
}

pub fn private_key_to_account<A: Address>(coin: &CoinInfo, private_key: &[u8]) -> Result<Account> {
let tsk = TypedPrivateKey::from_slice(coin.curve, private_key)?;
let pub_key = tsk.public_key();
let address = A::from_public_key(&pub_key, coin)?;

let acc = Account {
address: address.to_string(),
derivation_path: "".to_string(),
curve: coin.curve,
coin: coin.coin.to_owned(),
network: coin.network.to_string(),
seg_wit: coin.seg_wit.to_string(),
ext_pub_key: "".to_string(),
public_key: pub_key,
};

Ok(acc)
}
#[derive(Clone)]
pub struct PrivateKeystore {
store: Store,
Expand Down Expand Up @@ -83,7 +101,7 @@ impl PrivateKeystore {
"private_key_curve_not_match"
);

let account = Self::private_key_to_account::<A>(coin_info, sk)?;
let account = private_key_to_account::<A>(coin_info, sk)?;

Ok(account)
}
Expand Down Expand Up @@ -139,28 +157,6 @@ impl PrivateKeystore {
})
}

pub(crate) fn private_key_to_account<A: Address>(
coin: &CoinInfo,
private_key: &[u8],
) -> Result<Account> {
let tsk = TypedPrivateKey::from_slice(coin.curve, private_key)?;
let pub_key = tsk.public_key();
let address = A::from_public_key(&pub_key, coin)?;

let acc = Account {
address: address.to_string(),
derivation_path: "".to_string(),
curve: coin.curve,
coin: coin.coin.to_owned(),
network: coin.network.to_string(),
seg_wit: coin.seg_wit.to_string(),
ext_pub_key: "".to_string(),
public_key: pub_key,
};

Ok(acc)
}

fn decrypt_private_key(&self, key: &Key) -> Result<Vec<u8>> {
self.store.crypto.use_key(key)?.plaintext()
}
Expand Down
4 changes: 2 additions & 2 deletions token-core/tcx-keystore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ mod signer;

pub use keystore::{
fingerprint_from_mnemonic, fingerprint_from_private_key, fingerprint_from_seed,
mnemonic_to_seed, Account, Address, HdKeystore, Keystore, KeystoreGuard, Metadata,
PrivateKeystore, PublicKeyEncoder, Source,
mnemonic_to_seed, private_key_to_account, Account, Address, HdKeystore, Keystore,
KeystoreGuard, Metadata, PrivateKeystore, PublicKeyEncoder, Source,
};

pub use signer::{MessageSigner, SignatureParameters, Signer, TransactionSigner};
Expand Down
4 changes: 2 additions & 2 deletions token-core/tcx-proto/src/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ message ImportMnemonicParam {
string network = 3;
string name = 4;
string passwordHint = 5;
bool overwrite = 6;
string overwriteId = 6;
}

message ImportPrivateKeyResult {
Expand Down Expand Up @@ -123,7 +123,7 @@ message ImportPrivateKeyParam {
string name = 3;
string passwordHint = 4;
string network = 5;
bool overwrite = 6;
string overwriteId = 6;
}

// FUNCTION: keystore_common_exists(KeystoreCommonExistsParam): ExistsKeystoreResult
Expand Down
8 changes: 4 additions & 4 deletions token-core/tcx/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,8 @@ pub struct ImportMnemonicParam {
pub name: ::prost::alloc::string::String,
#[prost(string, tag = "5")]
pub password_hint: ::prost::alloc::string::String,
#[prost(bool, tag = "6")]
pub overwrite: bool,
#[prost(string, tag = "6")]
pub overwrite_id: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
Expand Down Expand Up @@ -450,8 +450,8 @@ pub struct ImportPrivateKeyParam {
pub password_hint: ::prost::alloc::string::String,
#[prost(string, tag = "5")]
pub network: ::prost::alloc::string::String,
#[prost(bool, tag = "6")]
pub overwrite: bool,
#[prost(string, tag = "6")]
pub overwrite_id: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
Expand Down
39 changes: 29 additions & 10 deletions token-core/tcx/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ use crate::macros::{impl_to_key, use_chains};
use crate::migration::{
read_all_identity_wallet_ids, remove_all_identity_wallets, remove_old_keystore_by_id,
};
use crate::reset_password::assert_seed_equals;

use_chains!(
tcx_btc_kin::bitcoin,
Expand Down Expand Up @@ -129,7 +130,7 @@ fn key_data_from_any_format_pk(pk: &str) -> Result<Vec<u8>> {
}
}

fn fingerprint_from_any_format_pk(pk: &str) -> Result<String> {
pub(crate) fn fingerprint_from_any_format_pk(pk: &str) -> Result<String> {
let key_data = if pk.starts_with("edsk") {
parse_tezos_private_key(pk)?
} else {
Expand All @@ -143,6 +144,7 @@ fn import_private_key_internal(
source: Option<Source>,
original: Option<String>,
) -> Result<ImportPrivateKeyResult> {
let overwrite_id = param.overwrite_id.to_string();
let mut founded_id: Option<String> = None;
{
let fingerprint = fingerprint_from_any_format_pk(&param.private_key)?;
Expand All @@ -155,8 +157,13 @@ fn import_private_key_internal(
}
}

if founded_id.is_some() && !param.overwrite {
return Err(anyhow!("{}", "address_already_exist"));
if founded_id.is_some() && Some(overwrite_id.to_string()) != founded_id {
return Err(anyhow!("{}", "seed_already_exist"));
}

if !overwrite_id.is_empty() {
assert_seed_equals(&overwrite_id, &param.private_key, false)?;
founded_id = Some(overwrite_id);
}

let decoded_ret = decode_private_key(&param.private_key)?;
Expand Down Expand Up @@ -225,15 +232,15 @@ fn import_private_key_internal(
Ok(wallet)
}

struct DecodedPrivateKey {
bytes: Vec<u8>,
pub(crate) struct DecodedPrivateKey {
pub bytes: Vec<u8>,
network: String,
curve: CurveType,
chain_types: Vec<String>,
source: Source,
}

fn decode_private_key(private_key: &str) -> Result<DecodedPrivateKey> {
pub(crate) fn decode_private_key(private_key: &str) -> Result<DecodedPrivateKey> {
let private_key_bytes: Vec<u8>;
let mut network = "".to_string();
let mut chain_types: Vec<String> = vec![];
Expand Down Expand Up @@ -525,8 +532,13 @@ pub fn import_mnemonic(data: &[u8]) -> Result<Vec<u8>> {
}
}

if founded_id.is_some() && !param.overwrite {
return Err(anyhow!("{}", "address_already_exist"));
if founded_id.is_some() && Some(param.overwrite_id.to_string()) != founded_id {
return Err(anyhow!("{}", "seed_already_exist"));
}

if !param.overwrite_id.is_empty() {
assert_seed_equals(param.overwrite_id.as_str(), &param.mnemonic, true)?;
founded_id = Some(param.overwrite_id);
}

let meta = Metadata {
Expand Down Expand Up @@ -947,7 +959,7 @@ pub(crate) fn import_json(data: &[u8]) -> Result<Vec<u8>> {
name,
password_hint: "".to_string(),
network: "".to_string(),
overwrite: param.overwrite,
overwrite_id: "".to_string(),
};
let mut ret = import_private_key_internal(
&pk_import_param,
Expand All @@ -968,7 +980,7 @@ pub(crate) fn import_json(data: &[u8]) -> Result<Vec<u8>> {
name,
password_hint: "".to_string(),
network: "".to_string(),
overwrite: param.overwrite,
overwrite_id: "".to_string(),
};
let mut ret = import_private_key_internal(
&pk_import_param,
Expand Down Expand Up @@ -1282,6 +1294,13 @@ pub(crate) fn eth_batch_personal_sign(data: &[u8]) -> Result<Vec<u8>> {
encode_message(EthBatchPersonalSignResult { signatures })
}

pub(crate) fn private_key_to_account_dynamic(
coin_info: &CoinInfo,
sec_key: &[u8],
) -> Result<Account> {
private_key_to_account_internal(coin_info, sec_key)
}

#[cfg(test)]
mod tests {
use tcx_constants::CurveType;
Expand Down
1 change: 1 addition & 0 deletions token-core/tcx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::api::{GeneralResult, TcxAction};
pub mod error_handling;
pub mod handler;
pub mod migration;
pub mod reset_password;
use anyhow::Error;
use std::result;

Expand Down
20 changes: 18 additions & 2 deletions token-core/tcx/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::str::FromStr;

use anyhow::anyhow;

use tcx_constants::CoinInfo;
use tcx_keystore::{
Address, Keystore, MessageSigner, PublicKeyEncoder, SignatureParameters, TransactionSigner,
};

use anyhow::anyhow;
use tcx_primitive::TypedPublicKey;

#[allow(clippy::derive_partial_eq_without_eq)]
Expand Down Expand Up @@ -141,6 +142,21 @@ macro_rules! use_chains {
Err(anyhow!("unsupported_chain"))
}

#[allow(dead_code)]
fn private_key_to_account_internal(coin_info:&CoinInfo, sec_key: &[u8]) -> Result<Account> {
type Address = MockAddress;
let faker_address = std::any::TypeId::of::<MockAddress>();

$({
use $chain::*;
if CHAINS.contains(&coin_info.coin.as_str()) && std::any::TypeId::of::<Address>() != faker_address {
return tcx_keystore::private_key_to_account::<Address>(coin_info, sec_key)
}
})*

Err(anyhow!("unsupported_chain"))
}

#[allow(dead_code)]
fn derive_sub_account(xpub: &TypedDeterministicPublicKey, coin_info:&CoinInfo) -> Result<Account> {
type Address = MockAddress;
Expand Down
3 changes: 2 additions & 1 deletion token-core/tcx/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use std::path::Path;
use std::str::FromStr;
use tcx_common::{FromHex, ToHex};
use tcx_constants::coin_info::get_xpub_prefix;
use tcx_constants::CoinInfo;
use tcx_eth::address::to_checksum;
use tcx_keystore::keystore::IdentityNetwork;
use tcx_keystore::Metadata;
Expand Down Expand Up @@ -346,7 +347,6 @@ pub(crate) fn scan_legacy_keystores() -> Result<ScanLegacyKeystoresResult> {
if version == 11000 || version == 11001 {
// let keystore = Keystore::from_json(&contents)?;
let mut keystore_result = parse_tcx_keystore(&v)?;
dbg!(&keystore_result);
keystore_result.source =
merge_migrate_source(&keystore_result.id, &keystore_result.source);
keystores.push(keystore_result);
Expand Down Expand Up @@ -520,6 +520,7 @@ fn merge_migrate_source(id: &str, ori_source: &str) -> String {
ori_source.to_string()
}
}

#[cfg(test)]
mod tests {
use std::fs;
Expand Down
Loading

0 comments on commit 3d06fa9

Please sign in to comment.