rustrust-cargoprivate-keyethers.jsmnemonics

Convert private key to string using ether.rs


I'm new to rust and currently exploring ethers.rs library. I want to print wallet's private key on the console for this first I'm building a mnemonic using.

let mnemonic = Mnemonic::<English>::new(&mut rand::thread_rng());

now using this mnemonic I want to extract the private key. I know a mnemonic can have multiple private keys but I want to extract the first one. For this I did something like this.

let key = mnemonic.derive_key("m/44'/60'/0'/0/0", None).unwrap()

this gives me output of type XPriv. I am unable to understand how can I work with this type as it does not contain any function to give me private key in string form so I can print it to the console. Any help would be appreciated.

here's my entire function

async fn test() {
    let mnemonic = Mnemonic::<English>::new(&mut rand::thread_rng());

    println!("mnemonic: {}", mnemonic.to_phrase());

    let key = mnemonic
        .derive_key("m/44'/60'/0'/0/0", None)
        .expect("Failed to derive pkey");
}

here's my cargo.toml

name = "rust-basics"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ethers="2.0.7"
tokio = { version = "1", features = ["full"] }
bip39 = "2.0"
rand = "0.8"
dialoguer = "0.10.4"
serde = "1.0.164"
serde_json = "1.0.97"
password-hash = "0.5.0"
bcrypt = "0.14.0"

Solution

  • I did not find the Mnemonic, but there is the MnemonicBuilder: https://github.com/gakonst/ethers-rs/blob/master/examples/wallets/examples/mnemonic.rs

    After you get the wallet, you can get the private key using following code.

    let private_key = wallet
        .signer()
        .to_bytes()
        .iter()
        .map(|&i|format!("{:X}", i))
        .collect::<Vec<String>>()
        .join("");
    

    Hope it helps.