I have hex string with private key. How I can get address for use in post request https://api.trongrid.io/wallet/getaccount
use std::str::FromStr;
use secp256k1::{Message, PublicKey, Secp256k1, SecretKey};
use sha3::{Digest, Keccak256};
use hex::FromHex;
use base58::{ToBase58, FromBase58};
pub fn private_key_to_address(private_key_hex: &str) ->String {
let secret_key = SecretKey::from_str(private_key_hex);
let pub_key = PublicKey::from_secret_key(&Secp256k1::new(), &secret_key.unwrap());
let key = &pub_key.serialize()[1..];
let mut hasher = Keccak256::new();
hasher.update(&key);
let digest = hasher.finalize();
let mut raw = [0x41; 21];
raw[1..21].copy_from_slice(&digest[digest.len() - 20..]);
hex::encode(raw).as_bytes().to_base58()
}
this my bad code, but from Trone I have response
{
"Error": "class java.lang.NullPointerException : null"
}
My result base58 from hex sXHkUo6PoX6YAcjwQnCXpm7EBbe1C5q7dqpuEnFUjvEMeVgcG1JHmkWCR
1
I this take solution from rust-tron lib convert algorithm to 1 function and add comment
https://github.com/andelf/rust-tron/tree/master
use secp256k1::{Message, PublicKey, Secp256k1, SecretKey};
use sha3::{Digest, Keccak256};
use hex::FromHex;
use base58::ToBase58;
use sha2::Sha256;
pub fn private_key_to_address(private_key_hex: &str) ->String {
// hex string private key to byte vector
let private_key = if private_key_hex.len() == 64 {
Vec::from_hex(private_key_hex).unwrap()
} else if private_key_hex.len() == 66 && (private_key_hex.starts_with("0x") || private_key_hex.starts_with("0X")) {
Vec::from_hex(&private_key_hex[2..]).unwrap()
} else {
panic!("error")
};
//convert vector to array
let mut raw = [0u8; 32];
raw[..32].copy_from_slice(&private_key);
//create public key from private key
let secret_key = SecretKey::from_slice(&raw).unwrap();
let pub_key = PublicKey::from_secret_key( &Secp256k1::new(),&secret_key);
//public key to byte array without first byte pub key have 65 byte size
let pub_key_bytes = pub_key.serialize_uncompressed();
let mut key = [0u8; 64];
key[..].copy_from_slice(&pub_key_bytes[1..]);
//hash array byte
let mut hasher = Keccak256::new();
hasher.update(key);
let digest = hasher.finalize();
//create address
//0x41 byte is prefix for tron blockchain and get 20 bytes from hash
let mut address_raw = [0x41; 21];
address_raw[1..21].copy_from_slice(&digest[digest.len() - 20..]);
//if you want to get hex address use hex::encode(address_raw)
// algorithm to convert address to Base58
let mut hasher = Sha256::new();
hasher.update(&address_raw);
let digest1 = hasher.finalize();
let mut hasher = Sha256::new();
hasher.update(&digest1);
let digest2 = hasher.finalize();
let mut address_with_checksum = address_raw.to_vec();
address_with_checksum.extend(&digest2[..4]);
address_with_checksum.to_base58()
}
dependencies
secp256k1 = "0.29"
sha3 = "0.10.8"
hex = "0.4.3"
base58 = "0.2.0"
sha2 = "0.10.8