From d46f220d12bc5ccbc3a70657ffd7885f99564883 Mon Sep 17 00:00:00 2001 From: aya015757881 <2581015450@qq.com> Date: Mon, 25 Nov 2024 10:24:11 +0800 Subject: [PATCH] fix: ethereum from_str() --- Cargo.lock | 2 +- crates/anychain-ethereum/Cargo.toml | 2 +- crates/anychain-ethereum/src/address.rs | 28 ++++++++----------------- 3 files changed, 11 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d896127..0760023 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -188,7 +188,7 @@ dependencies = [ [[package]] name = "anychain-ethereum" -version = "0.1.19" +version = "0.1.20" dependencies = [ "anychain-core", "ethabi", diff --git a/crates/anychain-ethereum/Cargo.toml b/crates/anychain-ethereum/Cargo.toml index 49fdf76..1ef031d 100644 --- a/crates/anychain-ethereum/Cargo.toml +++ b/crates/anychain-ethereum/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "anychain-ethereum" description = "A Rust library for Ethereum-focused cryptocurrency wallets, enabling seamless transactions on the Ethereum blockchain" -version = "0.1.19" +version = "0.1.20" keywords = ["blockchain", "crypto", "ethereum", "wallet"] categories = ["cryptography::cryptocurrencies"] diff --git a/crates/anychain-ethereum/src/address.rs b/crates/anychain-ethereum/src/address.rs index 903668d..7f83963 100644 --- a/crates/anychain-ethereum/src/address.rs +++ b/crates/anychain-ethereum/src/address.rs @@ -85,26 +85,16 @@ impl FromStr for EthereumAddress { type Err = AddressError; fn from_str(address: &str) -> Result { - let regex = Regex::new(r"^0x").unwrap(); - let address = address.to_lowercase(); - let address = regex.replace_all(&address, "").to_string(); - - if address.len() != 40 { - let err = AddressError::InvalidByteLength(address.len()); - return Err(err); + let addr = match address.starts_with("0x") { + true => &address[2..], + false => address, + }; + if addr.len() != 40 { + return Err(AddressError::InvalidCharacterLength(addr.len())); } - - let hash = to_hex_string(&keccak256(address.as_bytes())); - let mut checksum_address = "0x".to_string(); - for c in 0..40 { - let ch = match &hash[c..=c] { - "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" => address[c..=c].to_lowercase(), - _ => address[c..=c].to_uppercase(), - }; - checksum_address.push_str(&ch); - } - - Ok(EthereumAddress(checksum_address)) + let addr = addr.to_lowercase(); + let _ = hex::decode(addr)?; + Ok(EthereumAddress(address.to_string())) } }