Skip to content

Commit

Permalink
chore: fmt rust code
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhenQian committed Jul 12, 2024
1 parent 8721d47 commit 600fcb7
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 82 deletions.
4 changes: 2 additions & 2 deletions rust/apps/ethereum/src/erc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct ParsedErc20Transaction {
pub value: String,
}

pub fn encode_erc20_transfer_calldata(to:H160,amount:U256) -> String {
pub fn encode_erc20_transfer_calldata(to: H160, amount: U256) -> String {
// transfer(address recipient, uint256 amount) function signature is 0xa9059cbb
let mut calldata = "a9059cbb".to_string();
calldata.push_str(&format!("{:0>64}", hex::encode(to)));
Expand Down Expand Up @@ -57,8 +57,8 @@ pub fn parse_erc20(input: &str, decimal: u32) -> Result<ParsedErc20Transaction,

#[cfg(test)]
mod tests {
use core::str::FromStr;
use super::*;
use core::str::FromStr;

#[test]
fn test_parse_erc20() {
Expand Down
47 changes: 18 additions & 29 deletions rust/apps/ethereum/src/legacy_transaction_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ use rlp::{Decodable, DecoderError, Encodable, Rlp};
use third_party::hex;

type Bytes = vec::Vec<u8>;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use third_party::ur_registry::pb::protoc::EthTx;
use crate::erc20::encode_erc20_transfer_calldata;
use crate::structs::EthereumSignature;


use serde::{Deserialize, Deserializer, Serialize, Serializer};
use third_party::ur_registry::pb::protoc::EthTx;

const CHAIN_ID: u64 = 1u64;
const LEGACY_TRANSACTION_TYPE : u64 = 0u64;
const LEGACY_TRANSACTION_TYPE: u64 = 0u64;
#[derive(Clone)]
pub struct TransactionRecoveryId(pub u64);

Expand Down Expand Up @@ -53,7 +51,6 @@ pub struct TransactionSignature {
s: H256,
}


impl TryFrom<EthereumSignature> for TransactionSignature {
type Error = ();

Expand Down Expand Up @@ -81,7 +78,6 @@ impl TransactionSignature {
}
}


pub fn v(&self) -> u64 {
self.v.0
}
Expand Down Expand Up @@ -119,11 +115,11 @@ pub struct LegacyTransactionV2 {
nonce: U256,
gas_price: U256,
gas_limit: U256,
chain_id:u64,
chain_id: u64,
to: Bytes,
value: U256,
data: Bytes,
r#type:U256,
r#type: U256,
access_list: Bytes,
signature: Option<TransactionSignature>,
}
Expand All @@ -136,33 +132,32 @@ fn add_hex_prefix(hex: &str) -> String {
}
}


impl LegacyTransactionV2 {
pub fn new(
nonce: u32,
gas_price: u64,
gas_limit: u64,
chain_id:u64,
chain_id: u64,
to: String,
value: u64,
data: String,
) -> Self {
let to : H160 = to.parse().unwrap();
let to: H160 = to.parse().unwrap();
Self {
nonce: U256::from(nonce),
gas_price: U256::from(gas_price),
gas_limit: U256::from(gas_limit),
chain_id,
to:Bytes::from(to.as_bytes()),
to: Bytes::from(to.as_bytes()),
value: U256::from(value),
data: Bytes::from(hex::decode(data).unwrap()),
signature: None,
r#type:U256::from(0),
access_list:Bytes::from(vec![]),
r#type: U256::from(0),
access_list: Bytes::from(vec![]),
}
}

pub fn set_signature(mut self,signature:TransactionSignature) -> Self {
pub fn set_signature(mut self, signature: TransactionSignature) -> Self {
self.signature = Some(signature);
self
}
Expand Down Expand Up @@ -235,7 +230,7 @@ impl TryFrom<EthTx> for LegacyTransactionV2 {
// generate erc20 transfer inputdata
let to = crate::H160::from_str(&eth_tx.to).unwrap();
let amount = crate::U256::from(eth_tx.value.parse::<u64>().unwrap());
let input_data = encode_erc20_transfer_calldata(to,amount);
let input_data = encode_erc20_transfer_calldata(to, amount);
let legacy_transaction = LegacyTransactionV2::new(
eth_tx.nonce as u32,
eth_tx.gas_price.parse::<u64>().unwrap(),
Expand Down Expand Up @@ -305,7 +300,6 @@ impl Encodable for LegacyTransactionV2 {
}
}


#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -318,7 +312,6 @@ mod tests {
assert_eq!(hex_nonce, "0x21");
}


#[test]
fn test_transfer_erc20_legacy_transaction() {
let tx = LegacyTransactionV2::new(
Expand Down Expand Up @@ -350,7 +343,7 @@ mod tests {
// raw tx
let signed_tx = tx.encode_raw();
let signed_tx_hex = hex::encode(&signed_tx);
// tx id === tx hash
// tx id === tx hash
let signed_tx_hash = keccak256(&signed_tx);
let signed_tx_hash_hex = hex::encode(&signed_tx_hash);

Expand All @@ -359,7 +352,6 @@ mod tests {
signed_tx_hash_hex
);


assert_eq!(
"f8af21850389dffde682b3b094fe2c232addf66539bfd5d1bd4b2cc91d358022a286b5e620f48000b844a9059cbb00000000000000000000000049ab56b91fc982fd6ec1ec7bb87d74efa6da30ab00000000000000000000000000000000000000000000000001480ff69d129e2d26a035df2b615912b8be79a13c9b0a1540ade55434ab68778a49943442a9e6d3141aa00a6e33134ba47c1f1cda59ec3ef62a59d4da6a9d111eb4e447828574c1c94f66",
signed_tx_hex
Expand All @@ -368,13 +360,12 @@ mod tests {
let decoded_tx = LegacyTransactionV2::decode_raw(&signed_tx).unwrap();
assert_eq!(decoded_tx.nonce, U256::from(33));
let hex_data = hex::encode(decoded_tx.data);
assert_eq!(decoded_tx.gas_price, U256::from(15198060006u64));
assert_eq!(decoded_tx.gas_price, U256::from(15198060006u64));
assert_eq!(decoded_tx.gas_limit, U256::from(46000));
assert_eq!(decoded_tx.chain_id, 1);
assert_eq!(200000000000000,decoded_tx.value.as_u64());
assert_eq!(200000000000000, decoded_tx.value.as_u64());
assert_eq!(hex_data, "a9059cbb00000000000000000000000049ab56b91fc982fd6ec1ec7bb87d74efa6da30ab00000000000000000000000000000000000000000000000001480ff69d129e2d");
assert_eq!(decoded_tx.r#type, U256::from(0));

}

#[test]
Expand All @@ -384,11 +375,11 @@ mod tests {
15198060006,
46000,
1,
"0xfe2c232adDF66539BFd5d1Bd4B2cc91D358022a2".to_string(),
"0xfe2c232adDF66539BFd5d1Bd4B2cc91D358022a2".to_string(),
200000000000000,
"".to_string(),
);
assert_eq!(0,tx.data.len());
assert_eq!(0, tx.data.len());
let unsigned_tx = tx.encode_raw();
let unsigned_tx_hex = hex::encode(&unsigned_tx);
assert_eq!(
Expand Down Expand Up @@ -430,13 +421,11 @@ mod tests {
assert_eq!(decoded_tx.gas_price, U256::from(15198060006u64));
assert_eq!(decoded_tx.gas_limit, U256::from(46000));
assert_eq!(decoded_tx.chain_id, 1);
assert_eq!(200000000000000,decoded_tx.value.as_u64());
assert_eq!(200000000000000, decoded_tx.value.as_u64());
assert_eq!(decoded_tx.data, Bytes::from("".as_bytes()));
assert_eq!(decoded_tx.r#type, U256::from(0));

}


#[test]
fn test_legacy_transaction2() {
let tx = LegacyTransactionV2::new(
Expand Down
14 changes: 9 additions & 5 deletions rust/apps/ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ pub mod eip712;
pub mod erc20;
pub mod errors;
mod legacy_transaction;
pub mod legacy_transaction_v2;
mod normalizer;
pub mod structs;
mod traits;
pub mod legacy_transaction_v2;
pub use ethereum_types::{H160, U256};
pub type Bytes = Vec<u8>;

Expand All @@ -26,12 +26,12 @@ use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

pub use legacy_transaction::*;
use crate::eip712::eip712::{Eip712, TypedData as Eip712TypedData};
use crate::legacy_transaction_v2::LegacyTransactionV2;
pub use legacy_transaction::*;
use third_party::hex;
use third_party::secp256k1::{Message, PublicKey};
use third_party::serde_json;
use crate::legacy_transaction_v2::LegacyTransactionV2;

pub fn parse_legacy_tx(tx_hex: Vec<u8>, from_key: PublicKey) -> Result<ParsedEthereumTransaction> {
ParsedEthereumTransaction::from_legacy(
Expand Down Expand Up @@ -90,7 +90,11 @@ pub fn sign_legacy_tx(sign_data: Vec<u8>, seed: &[u8], path: &String) -> Result<
}

/// Only used by hot wallet version2
pub fn sign_legacy_tx_v2(sign_data: Vec<u8>, seed: &[u8], path: &String) -> Result<EthereumSignature> {
pub fn sign_legacy_tx_v2(
sign_data: Vec<u8>,
seed: &[u8],
path: &String,
) -> Result<EthereumSignature> {
let tx = LegacyTransactionV2::decode_raw(sign_data.as_slice())?;
let hash = keccak256(sign_data.as_slice());
let message = Message::from_digest_slice(&hash).unwrap();
Expand Down Expand Up @@ -175,13 +179,13 @@ mod tests {

extern crate std;

use core::str::FromStr;
use crate::alloc::string::ToString;
use crate::eip712::eip712::{Eip712, TypedData as Eip712TypedData};
use crate::{
parse_fee_market_tx, parse_personal_message, parse_typed_data_message,
sign_personal_message, sign_typed_data_message,
};
use core::str::FromStr;
use keystore::algorithms::secp256k1::get_public_key_by_seed;
use third_party::hex;
use third_party::serde_json;
Expand Down
2 changes: 0 additions & 2 deletions rust/apps/ethereum/src/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ impl Decodable for TransactionAction {
}
}


impl Encodable for TransactionAction {
fn rlp_append(&self, s: &mut rlp::RlpStream) {
match self {
Expand All @@ -42,7 +41,6 @@ impl Encodable for TransactionAction {
}
()
}

}

#[derive(Clone, Debug)]
Expand Down
33 changes: 18 additions & 15 deletions rust/apps/wallets/src/keystone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@ use alloc::{
string::{String, ToString},
vec::Vec,
};
use third_party::ur_registry::bytes::Bytes;
use third_party::{
bitcoin::bip32::{ChildNumber},
bitcoin::bip32::ChildNumber,
ur_registry::{
crypto_hd_key::CryptoHDKey,
crypto_key_path::{CryptoKeyPath, PathComponent},
error::{URError, URResult},
extend::crypto_multi_accounts::CryptoMultiAccounts,
},
};
use third_party::ur_registry::bytes::Bytes;


use crate::companion_app::{generate_companion_app_sync_ur, AccountConfig, CoinConfig};
use crate::{common::get_path_component, ExtendedPublicKey, DEVICE_TYPE, DEVICE_VERSION};
use crate::companion_app::{AccountConfig, CoinConfig, generate_companion_app_sync_ur};

fn get_device_id(serial_number: &str) -> String {
use third_party::cryptoxide::hashing::sha256;
Expand All @@ -32,11 +31,14 @@ const LTC_PREFIX: &str = "m/49'/2'/0'";
const TRX_PREFIX: &str = "m/44'/195'/0'";
const XRP_PREFIX: &str = "m/44'/144'/0'";


const COLD_WALLET_VERSION :i32 = 31206;
const COLD_WALLET_VERSION: i32 = 31206;
fn path_to_coin_code(path: &str) -> String {

let path = path.split('/').take(4).collect::<Vec<&str>>().join("/").to_lowercase();
let path = path
.split('/')
.take(4)
.collect::<Vec<&str>>()
.join("/")
.to_lowercase();
rust_tools::debug!(format!("path: {}", path));
match path.as_str() {
BTC_LEGACY_PREFIX => "BTC_LEGACY".to_string(),
Expand Down Expand Up @@ -105,18 +107,20 @@ pub fn generate_crypto_multi_accounts(
Some(device_version.to_string()),
);


// convert crypto_multi_accounts to keystone sync ur
let mut coin_configs : Vec<CoinConfig> = vec![];
let mut coin_configs: Vec<CoinConfig> = vec![];
for key in data.get_keys() {
let mut accounts: Vec<AccountConfig> = vec![];
let hd_path = "M/".to_string() + &*key.get_origin().unwrap().get_path().unwrap();

let x_pub = key.get_bip32_key();
let x_pub = key.get_bip32_key();

let coin_code = path_to_coin_code(&hd_path);
rust_tools::debug!(format!("coin_code: {}, hd_path: {}, x_pub: {}", coin_code, hd_path, x_pub));
if coin_code == "Unknown"{
rust_tools::debug!(format!(
"coin_code: {}, hd_path: {}, x_pub: {}",
coin_code, hd_path, x_pub
));
if coin_code == "Unknown" {
continue;
}

Expand Down Expand Up @@ -159,7 +163,7 @@ pub fn generate_crypto_multi_accounts(
// Coin { coin_code: "XRP", active: true, accounts: [Account { hd_path: "M/44'/144'/0'", x_pub: "xpub6BmXbwNG7wfcEs5VUsBKK5CwJk3Vf8QFKF3wTeutW1zWwStQ7qGZJr9W6KxdBF5pyzju17Hrsus4kjdjvYfu3PB46BsUQY61WQ2d9rP5v7i", address_length: 1, is_multi_sign: false }] },
// Coin { coin_code: "DOT", active: true, accounts: [Account { hd_path: "//polkadot", x_pub: "xpub68wKPdEKjbZ4o1mSG7eN6b7b6vHXpShMTxJE4emZ98Fbs93cPxrkKxRmLkq7pi937qPyjxvXk4Zn2nUCvuQg6zbRvqQpVzXQyaM8miwcs7E", address_length: 1, is_multi_sign: false }] }] })) }),
// device_type: "keystone Pro", content: Some(ColdVersion(31206)) }
Ok(keystone_sync_ur)
Ok(keystone_sync_ur)
}

fn generate_k1_normal_key(
Expand Down Expand Up @@ -192,4 +196,3 @@ fn generate_k1_normal_key(
note,
))
}

2 changes: 1 addition & 1 deletion rust/apps/wallets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod blue_wallet;
mod common;
pub mod companion_app;
pub mod keplr;
pub mod keystone;
pub mod metamask;
pub mod okx;
pub mod solana;
Expand All @@ -28,7 +29,6 @@ pub mod tonkeeper;
mod utils;
pub mod xbull;
pub mod xrp_toolkit;
pub mod keystone;
//TODO: get these value from device
pub const DEVICE_TYPE: &str = "Keystone 3 Pro";
pub const DEVICE_VERSION: &str = "1.1.0";
Expand Down
Loading

0 comments on commit 600fcb7

Please sign in to comment.