aptos_testcontainer/
utils.rs

1use tiny_keccak::Hasher;
2
3/// Converts a given private key to its corresponding account address.
4///
5/// # Arguments
6///
7/// * `private_key` - A string slice representing the private key in hexadecimal format.
8///
9/// # Returns
10///
11/// * `String` - The derived account address in hexadecimal format.
12///
13/// # Example
14/// ```rust
15/// use aptos_testcontainer::aptos_container::AptosContainer;
16/// use aptos_testcontainer::utils::get_account_address;
17///
18/// #[tokio::main]
19/// async fn main() {
20///     let aptos_container = AptosContainer::init().await.unwrap();
21///     let accounts = aptos_container.get_initiated_accounts().await.unwrap();
22///     let module_account_private_key = accounts.first().unwrap();
23///     let module_account_address = get_account_address(module_account_private_key);
24/// }
25/// ```
26pub fn get_account_address(private_key: &str) -> String {
27    // Convert the private key from hexadecimal format to bytes, removing the "0x" prefix if present.
28    let signing_key = ed25519_dalek::SigningKey::try_from(
29        hex::decode(private_key.trim_start_matches("0x"))
30            .unwrap()
31            .as_slice(),
32    )
33    .unwrap();
34
35    // Derive the public key from the signing key.
36    let public_key = ed25519_dalek::VerifyingKey::from(&signing_key);
37
38    // Prepare public key bytes for hashing by appending a trailing zero.
39    let mut public_key_bytes = public_key.to_bytes().to_vec();
40    public_key_bytes.push(0);
41
42    // Initialize SHA3-256 hashing algorithm and update it with the public key bytes.
43    let mut sha3 = tiny_keccak::Sha3::v256();
44    sha3.update(&public_key_bytes);
45
46    // Finalize the hash and store it in `out_bytes`.
47    let mut out_bytes = [0; 32];
48    sha3.finalize(&mut out_bytes);
49
50    // Convert the hashed bytes to a hexadecimal string.
51    let mut public_key = "".to_string();
52    for byte in out_bytes.iter() {
53        public_key = format!("{}{:02x}", public_key, byte);
54    }
55    public_key
56}