use std::str::FromStr;
use bitcoin::{Address, Network};
use redgold_schema::public_key::ToPublicKey;
use redgold_schema::structs::{ErrorInfo, PublicKey};
use bitcoin::util::key;
use hex::ToHex;
use redgold_schema::ErrorInfoContext;
use sha3::{Digest, Keccak256};
pub trait ToBitcoinAddress {
fn to_bitcoin_address(&self) -> Result<String, ErrorInfo>;
}
pub trait ToEthereumAddress {
fn to_ethereum_address(&self) -> Result<String, ErrorInfo>;
}
impl ToBitcoinAddress for PublicKey {
fn to_bitcoin_address(&self) -> Result<String, ErrorInfo> {
let pk = &key::PublicKey::from_slice(&self.bytes()?).error_info("public key conversion")?;
let address = Address::p2wpkh(pk, Network::Bitcoin);
Ok(address.to_string())
}
}
impl ToEthereumAddress for PublicKey {
fn to_ethereum_address(&self) -> Result<String, ErrorInfo> {
let data = self.to_lib_public_key()?.serialize_uncompressed().to_vec()[1..].to_vec();
let mut hasher = Keccak256::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
let vec = result[12..].to_vec();
let string = get_checksum_address(hex::encode(vec));
Ok(string)
}
}
pub fn get_checksum_address(a: String) -> String {
let addr = a.trim_start_matches("0x").to_lowercase();
let address_hash = {
let mut hasher = Keccak256::new();
let x = addr.as_bytes();
hasher.update(x);
hex::encode(hasher.finalize().to_vec())
};
addr
.char_indices()
.fold(String::from("0x"), |mut acc, (index, address_char)| {
let n = u16::from_str_radix(&address_hash[index..index + 1], 16).unwrap();
if n > 7 {
acc.push_str(&address_char.to_uppercase().to_string())
} else {
acc.push(address_char)
}
acc
})
}