Skip to main content

ethrex_l2_common/
utils.rs

1pub fn get_address_from_secret_key(
2    secret_key_bytes: &[u8],
3) -> Result<ethrex_common::Address, String> {
4    let signing_key = k256::ecdsa::SigningKey::from_bytes(secret_key_bytes.into())
5        .map_err(|e| format!("Failed to parse secret key from slice: {e}"))?;
6
7    let public_key = signing_key
8        .verifying_key()
9        .to_encoded_point(false)
10        .to_bytes();
11    let public_key_without_prefix = public_key
12        .get(1..)
13        .ok_or("Failed to get_address_from_secret_key: public key too short")?;
14    let hash = ethrex_common::utils::keccak(public_key_without_prefix);
15
16    // Get the last 20 bytes of the hash
17    let address_bytes: [u8; 20] = hash
18        .as_ref()
19        .get(12..32)
20        .ok_or("Failed to get_address_from_secret_key: error slicing address_bytes".to_owned())?
21        .try_into()
22        .map_err(|err| format!("Failed to get_address_from_secret_key: {err}"))?;
23
24    Ok(ethrex_common::Address::from(address_bytes))
25}