Skip to content

Commit

Permalink
fix: fix import private key
Browse files Browse the repository at this point in the history
  • Loading branch information
XuNeal committed Dec 18, 2023
1 parent 915a4f5 commit b2e4802
Show file tree
Hide file tree
Showing 18 changed files with 404 additions and 244 deletions.
4 changes: 1 addition & 3 deletions token-core/tcx-btc-kin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ pub use bch_address::BchAddress;
pub use network::BtcKinNetwork;
use tcx_constants::{CoinInfo, CurveType};
use tcx_keystore::Address;
use tcx_primitive::{
get_account_path, Bip32DeterministicPublicKey, Derive, DeterministicPublicKey, TypedPublicKey,
};
use tcx_primitive::{Bip32DeterministicPublicKey, Derive, DeterministicPublicKey, TypedPublicKey};
pub use transaction::{BtcKinTxInput, BtcKinTxOutput, OmniTxInput, Utxo};

pub const BITCOIN: &'static str = "BITCOIN";
Expand Down
5 changes: 0 additions & 5 deletions token-core/tcx-examples/RN/ios/RN/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,6 @@ message DeriveAccountsResult {
repeated AccountResponse accounts = 1;
}

// FUNCTION: hd_store_export(ExportResult): ExistsKeystoreResult
//
// export the mnemonic from a hd keystore
message ExportResult {
string id = 1;
KeyType type = 2;
Expand Down Expand Up @@ -103,8 +100,6 @@ message PrivateKeyStoreExportParam {
//
// delete the keystore

// FUNCTION: keystore_common_exists(KeystoreCommonExistsParam): ExistsKeystoreResult
//
// Check is there a keystore was generate by the special privateKey or mnemonic
message KeystoreCommonExistsParam {
KeyType type = 1;
Expand Down
3 changes: 2 additions & 1 deletion token-core/tcx-filecoin/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ mod tests {
&Vec::from_hex("7b2254797065223a22626c73222c22507269766174654b6579223a2269376b4f2b7a78633651532b7637597967636d555968374d55595352657336616e6967694c684b463830383d227d").unwrap()).unwrap();
let private_key = key_info.decode_private_key().unwrap();
let mut ks =
Keystore::from_private_key(&private_key.to_hex(), "Password", Metadata::default()).unwrap();
Keystore::from_private_key(&private_key.to_hex(), "Password", Metadata::default())
.unwrap();
ks.unlock_by_password("Password").unwrap();

let sign_context = SignatureParameters {
Expand Down
3 changes: 2 additions & 1 deletion token-core/tcx-keystore/src/keystore/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ mod tests {

assert!(ks.is_locked());

let mut ks = Keystore::from_private_key(PRIVATE_KEY, TEST_PASSWORD, Metadata::default()).unwrap();
let mut ks =
Keystore::from_private_key(PRIVATE_KEY, TEST_PASSWORD, Metadata::default()).unwrap();
let derived_key = ks.get_derived_key(&TEST_PASSWORD).unwrap();

{
Expand Down
3 changes: 2 additions & 1 deletion token-core/tcx-keystore/src/keystore/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,8 @@ pub(crate) mod tests {
#[test]
fn test_private_keystore() {
let mut keystore =
Keystore::from_private_key(TEST_PRIVATE_KEY, TEST_PASSWORD, Metadata::default()).unwrap();
Keystore::from_private_key(TEST_PRIVATE_KEY, TEST_PASSWORD, Metadata::default())
.unwrap();

assert!(keystore
.unlock(&Key::Password(TEST_PASSWORD.to_owned()))
Expand Down
24 changes: 17 additions & 7 deletions token-core/tcx-keystore/src/keystore/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,20 @@ use crate::identity::Identity;
use crate::keystore::Store;

use tcx_common::{ripemd160, sha256, FromHex, ToHex};
use tcx_primitive::{PrivateKey, Secp256k1PrivateKey, TypedPrivateKey};
use tcx_primitive::{
PrivateKey, PublicKey, Secp256k1PrivateKey, Sr25519PrivateKey, TypedPrivateKey,
};
use uuid::Uuid;

pub fn key_hash_from_private_key(data: &[u8]) -> Result<String> {
let private_key = Secp256k1PrivateKey::from_slice(data)?;
let public_key_data = private_key.public_key().to_compressed();
// TODO: Sr25519
let public_key_data = if data.len() == 32 {
let private_key = Secp256k1PrivateKey::from_slice(data)?;
private_key.public_key().to_compressed()
} else {
let private_key = Sr25519PrivateKey::from_slice(data)?;
private_key.public_key().to_bytes()
};
let hashed = ripemd160(&sha256(&public_key_data));
Ok(hashed[0..4].to_0x_hex())
}
Expand Down Expand Up @@ -140,10 +148,10 @@ impl PrivateKeystore {

#[cfg(test)]
mod tests {
use crate::{HdKeystore, Metadata, PrivateKeystore, Source, key_hash_from_private_key};
use crate::{key_hash_from_private_key, HdKeystore, Metadata, PrivateKeystore, Source};
use bitcoin_hashes::hex::FromHex;
use tcx_constants::{TEST_MNEMONIC, TEST_PASSWORD, TEST_PRIVATE_KEY};
use tcx_crypto::Key;
use bitcoin_hashes::hex::FromHex;

#[test]
fn test_from_private_key() {
Expand All @@ -156,7 +164,8 @@ mod tests {
"a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6",
TEST_PASSWORD,
meta,
).unwrap();
)
.unwrap();

keystore
.unlock(&Key::Password(TEST_PASSWORD.to_owned()))
Expand All @@ -173,7 +182,8 @@ mod tests {
#[test]
fn test_verify_password() {
let mut keystore =
PrivateKeystore::from_private_key(TEST_PRIVATE_KEY, TEST_PASSWORD, Metadata::default()).unwrap();
PrivateKeystore::from_private_key(TEST_PRIVATE_KEY, TEST_PASSWORD, Metadata::default())
.unwrap();

assert!(keystore.verify_password(TEST_PASSWORD));
assert!(!keystore.verify_password("WrongPassword"));
Expand Down
2 changes: 0 additions & 2 deletions token-core/tcx-primitive/src/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,6 @@ impl TraitPublicKey for Secp256k1PublicKey {

impl Ss58Codec for Secp256k1PrivateKey {
fn from_ss58check_with_version(wif: &str) -> Result<(Self, Vec<u8>)> {
let data_with_check = base58::from(wif)?;
dbg!(data_with_check.to_0x_hex());
let data = base58::from_check(wif)?;

let compressed = match data.len() {
Expand Down
3 changes: 3 additions & 0 deletions token-core/tcx-primitive/src/sr25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ impl TraitPrivateKey for Sr25519PrivateKey {
//
// let kp = mini_key.expand_to_keypair(ExpansionMode::Ed25519);
let pk = SecretKey::from_ed25519_bytes(data).map_err(|_| KeyError::InvalidSr25519Key)?;
// let pk = SecretKey::from_bytes(data).map_err(|_| KeyError::InvalidSr25519Key)?;
Ok(Sr25519PrivateKey(Pair::from(pk)))
}

Expand All @@ -58,6 +59,8 @@ impl TraitPrivateKey for Sr25519PrivateKey {

fn to_bytes(&self) -> Vec<u8> {
self.0.to_raw_vec()
// self.0.clone_into(target)
// self.0.
}
}

Expand Down
11 changes: 11 additions & 0 deletions token-core/tcx-proto/src/api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ message ExportPrivateKeyParam {
string curve = 5;
string path = 6;
}

//
//// FUNCTION: export_private_key(ExportPrivateKeyParam): ExportResult
////
//// export the private key from a private key keystore or a hd keystore
message ExportJsonParam {
string id = 1;
string password = 2;
string chainType = 3;
string path = 4;
}
//
///// Keystore Common
//
Expand Down
48 changes: 34 additions & 14 deletions token-core/tcx-proto/src/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -84,21 +84,28 @@ message DeriveAccountsResult {
repeated AccountResponse accounts = 1;
}

// FUNCTION: hd_store_export(ExportResult): ExistsKeystoreResult
//
// export the mnemonic from a hd keystore
message ExportResult {
message ExportMnemonicResult {
string id = 1;
string mnemonic = 2;
}

message ExportPrivateKeyResult {
string id = 1;
KeyType type = 2;
string value = 3;
string privateKey = 2;
}

// only support two types
enum KeyType {
MNEMONIC = 0;
PRIVATE_KEY = 1;
message ExportJsonResult {
string id = 1;
string json = 2;
}

// // only support two types
// enum KeyType {
// MNEMONIC = 0;
// PRIVATE_KEY = 1;
// }

/// Private Key Store

// FUNCTION: import_private_key(ImportPrivateKeyParam): KeystoreResult
Expand All @@ -125,11 +132,11 @@ message PrivateKeyStoreExportParam {
// FUNCTION: keystore_common_exists(KeystoreCommonExistsParam): ExistsKeystoreResult
//
// Check is there a keystore was generate by the special privateKey or mnemonic
message KeystoreCommonExistsParam {
KeyType type = 1;
string value = 2;
string encoding = 3;
}
// message KeystoreCommonExistsParam {
// KeyType type = 1;
// string value = 2;
// string encoding = 3;
// }

message ExistsMnemonicParam {
string mnemonic = 1;
Expand All @@ -139,11 +146,24 @@ message ExistsPrivateKeyParam {
string private_key = 1;
}


message ExistsJsonParam {
string json = 1;
string password = 2;
}

message ExistsKeystoreResult {
bool isExists = 1;
string id = 2;
}

message ImportJsonParam {
string json = 1;
string password = 2;
bool overwrite = 3;
}


// FUNCTION: keystore_common_accounts(KeystoreCommonAccountsParam): DeriveAccountsResult
//
// List all accounts from the keystore
Expand Down
9 changes: 0 additions & 9 deletions token-core/tcx-proto/src/substrate.proto
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,7 @@ syntax = "proto3";
package transaction;


message ImportJsonParam {
string keystore = 1;
string password = 2;
bool overwrite = 4;
}


message ExportJsonResult {
string keystore = 1;
}

message SubstrateRawTxIn {
string rawData = 1;
Expand Down
18 changes: 18 additions & 0 deletions token-core/tcx-substrate/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ mod test_super {
use super::*;
use tcx_common::FromHex;
use tcx_constants::{CoinInfo, CurveType};
use tcx_primitive::{PrivateKey, Sr25519PrivateKey};

#[test]
fn test_address_from_public() {
Expand Down Expand Up @@ -92,6 +93,23 @@ mod test_super {
let addr = SubstrateAddress::from_public_key(&typed_key, &addr_and_coin.1).unwrap();
assert_eq!(addr.to_string(), addr_and_coin.0);
}

let sec_key_data = &Vec::<u8>::from_hex_auto("00ea01b0116da6ca425c477521fd49cc763988ac403ab560f4022936a18a4341016e7df1f5020068c9b150e0722fea65a264d5fbb342d4af4ddf2f1cdbddf1fd").unwrap();
let sec_key = Sr25519PrivateKey::from_slice(&sec_key_data).unwrap();
let pub_key = sec_key.public_key();
let typed_key = TypedPublicKey::Sr25519(pub_key);
let kusama_coin_info = CoinInfo {
coin: "KUSAMA".to_string(),
derivation_path: "//imToken//kusama/0".to_string(),
curve: CurveType::SubSr25519,
network: "".to_string(),
seg_wit: "".to_string(),
};
let addr = SubstrateAddress::from_public_key(&typed_key, &kusama_coin_info).unwrap();
assert_eq!(
addr.to_string(),
"JHBkzZJnLZ3S3HLvxjpFAjd6ywP7WAk5miL7MwVCn9a7jHS"
)
}

#[test]
Expand Down
24 changes: 14 additions & 10 deletions token-core/tcx-substrate/src/keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use regex::Regex;
use serde::__private::{fmt, PhantomData};
use std::io::Cursor;
use std::time::{SystemTime, UNIX_EPOCH};
use tcx_common::{random_u8_32, FromHex};
use tcx_common::{random_u8_32, FromHex, ToHex};
use tcx_constants::{CoinInfo, Result};
use tcx_primitive::{
DeterministicPrivateKey, PrivateKey, PublicKey, Sr25519PrivateKey, TypedPublicKey,
Expand Down Expand Up @@ -322,15 +322,19 @@ fn password_to_key(password_bytes: &[u8]) -> [u8; 32] {

pub fn decode_substrate_keystore(keystore: &SubstrateKeystore, password: &str) -> Result<Vec<u8>> {
let (secret_key, pub_key) = keystore.decrypt(password)?;
let priv_key = if secret_key.len() == 32 {
Sr25519PrivateKey::from_seed(&secret_key)
} else {
Sr25519PrivateKey::from_slice(&secret_key)
}?;
if priv_key.public_key().to_bytes() != pub_key {
return Err(Error::KeystorePublicKeyUnmatch.into());
}
Ok(secret_key)
dbg!(secret_key.to_hex());
// let priv_key = if secret_key.len() == 32 {
// Sr25519PrivateKey::from_seed(&secret_key)
// } else {
// Sr25519PrivateKey::from_slice(&secret_key)
// }?;
let priv_key = Sr25519PrivateKey::from_slice(&secret_key)?;
// if priv_key.public_key().to_bytes() != pub_key {
// return Err(Error::KeystorePublicKeyUnmatch.into());
// }
dbg!("decode_substrate_keystore success");
dbg!(priv_key.to_bytes().to_0x_hex());
Ok(priv_key.to_bytes())
}

pub fn encode_substrate_keystore(
Expand Down
2 changes: 1 addition & 1 deletion token-core/tcx-substrate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod transaction;

pub use address::SubstrateAddress;
pub use keystore::{decode_substrate_keystore, encode_substrate_keystore, SubstrateKeystore};
pub use transaction::{ExportJsonResult, ImportJsonParam, SubstrateRawTxIn, SubstrateTxOut};
pub use transaction::{SubstrateRawTxIn, SubstrateTxOut};

pub(crate) const SIGNATURE_TYPE_SR25519: u8 = 0x01;
pub(crate) const PAYLOAD_HASH_THRESHOLD: usize = 256;
Expand Down
16 changes: 0 additions & 16 deletions token-core/tcx-substrate/src/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,5 @@
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportJsonParam {
#[prost(string, tag = "1")]
pub keystore: ::prost::alloc::string::String,
#[prost(string, tag = "2")]
pub password: ::prost::alloc::string::String,
#[prost(bool, tag = "4")]
pub overwrite: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ExportJsonResult {
#[prost(string, tag = "1")]
pub keystore: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SubstrateRawTxIn {
#[prost(string, tag = "1")]
pub raw_data: ::prost::alloc::string::String,
Expand Down
Loading

0 comments on commit b2e4802

Please sign in to comment.