1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
//! Specific helper functions for creating/loading a mnemonic private key following BIP-39
//! specifications
use crate::{Wallet, WalletError};
use coins_bip32::path::DerivationPath;
use coins_bip39::{Mnemonic, Wordlist};
use ethers_core::{
k256::ecdsa::SigningKey,
types::PathOrString,
utils::{secret_key_to_address, to_checksum},
};
use rand::Rng;
use std::{fs::File, io::Write, marker::PhantomData, path::PathBuf, str::FromStr};
use thiserror::Error;
const DEFAULT_DERIVATION_PATH_PREFIX: &str = "m/44'/60'/0'/0/";
/// Represents a structure that can resolve into a `Wallet<SigningKey>`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MnemonicBuilder<W: Wordlist> {
/// The mnemonic phrase can be supplied to the builder as a string or a path to the file whose
/// contents are the phrase. A builder that has a valid phrase should `build` the wallet.
phrase: Option<PathOrString>,
/// The mnemonic builder can also be asked to generate a new random wallet by providing the
/// number of words in the phrase. By default this is set to 12.
word_count: usize,
/// The derivation path at which the extended private key child will be derived at. By default
/// the mnemonic builder uses the path: "m/44'/60'/0'/0/0".
derivation_path: DerivationPath,
/// Optional password for the mnemonic phrase.
password: Option<String>,
/// Optional field that if enabled, writes the mnemonic phrase to disk storage at the provided
/// path.
write_to: Option<PathBuf>,
/// PhantomData
_wordlist: PhantomData<W>,
}
/// Error produced by the mnemonic wallet module
#[derive(Error, Debug)]
pub enum MnemonicBuilderError {
/// Error suggests that a phrase (path or words) was expected but not found
#[error("Expected phrase not found")]
ExpectedPhraseNotFound,
/// Error suggests that a phrase (path or words) was not expected but found
#[error("Unexpected phrase found")]
UnexpectedPhraseFound,
}
impl<W: Wordlist> Default for MnemonicBuilder<W> {
fn default() -> Self {
Self {
phrase: None,
word_count: 12usize,
derivation_path: DerivationPath::from_str(&format!(
"{}{}",
DEFAULT_DERIVATION_PATH_PREFIX, 0
))
.expect("should parse the default derivation path"),
password: None,
write_to: None,
_wordlist: PhantomData,
}
}
}
impl<W: Wordlist> MnemonicBuilder<W> {
/// Sets the phrase in the mnemonic builder. The phrase can either be a string or a path to
/// the file that contains the phrase. Once a phrase is provided, the key will be generated
/// deterministically by calling the `build` method.
///
/// # Example
///
/// ```
/// use ethers_signers::{MnemonicBuilder, coins_bip39::English};
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
///
/// let wallet = MnemonicBuilder::<English>::default()
/// .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
/// .build()?;
///
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn phrase<P: Into<PathOrString>>(mut self, phrase: P) -> Self {
self.phrase = Some(phrase.into());
self
}
/// Sets the word count of a mnemonic phrase to be generated at random. If the `phrase` field
/// is set, then `word_count` will be ignored.
///
/// # Example
///
/// ```
/// use ethers_signers::{MnemonicBuilder, coins_bip39::English};
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
///
/// let mut rng = rand::thread_rng();
/// let wallet = MnemonicBuilder::<English>::default()
/// .word_count(24)
/// .build_random(&mut rng)?;
///
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn word_count(mut self, count: usize) -> Self {
self.word_count = count;
self
}
/// Sets the derivation path of the child key to be derived. The derivation path is calculated
/// using the default derivation path prefix used in Ethereum, i.e. "m/44'/60'/0'/0/{index}".
pub fn index<U: Into<u32>>(mut self, index: U) -> Result<Self, WalletError> {
self.derivation_path = DerivationPath::from_str(&format!(
"{}{}",
DEFAULT_DERIVATION_PATH_PREFIX,
index.into()
))?;
Ok(self)
}
/// Sets the derivation path of the child key to be derived.
pub fn derivation_path(mut self, path: &str) -> Result<Self, WalletError> {
self.derivation_path = DerivationPath::from_str(path)?;
Ok(self)
}
/// Sets the password used to construct the seed from the mnemonic phrase.
#[must_use]
pub fn password(mut self, password: &str) -> Self {
self.password = Some(password.to_string());
self
}
/// Sets the path to which the randomly generated phrase will be written to. This field is
/// ignored when building a wallet from the provided mnemonic phrase.
#[must_use]
pub fn write_to<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.write_to = Some(path.into());
self
}
/// Builds a `LocalWallet` using the parameters set in mnemonic builder. This method expects
/// the phrase field to be set.
pub fn build(&self) -> Result<Wallet<SigningKey>, WalletError> {
let mnemonic = match &self.phrase {
Some(path_or_string) => {
let phrase = path_or_string.read()?;
Mnemonic::<W>::new_from_phrase(&phrase)?
}
None => return Err(MnemonicBuilderError::ExpectedPhraseNotFound.into()),
};
self.mnemonic_to_wallet(&mnemonic)
}
/// Builds a `LocalWallet` using the parameters set in the mnemonic builder and constructing
/// the phrase using the provided random number generator.
pub fn build_random<R: Rng>(&self, rng: &mut R) -> Result<Wallet<SigningKey>, WalletError> {
let mnemonic = match &self.phrase {
None => Mnemonic::<W>::new_with_count(rng, self.word_count)?,
_ => return Err(MnemonicBuilderError::UnexpectedPhraseFound.into()),
};
let wallet = self.mnemonic_to_wallet(&mnemonic)?;
// Write the mnemonic phrase to storage if a directory has been provided.
if let Some(dir) = &self.write_to {
let mut file = File::create(dir.as_path().join(to_checksum(&wallet.address, None)))?;
file.write_all(mnemonic.to_phrase().as_bytes())?;
}
Ok(wallet)
}
fn mnemonic_to_wallet(
&self,
mnemonic: &Mnemonic<W>,
) -> Result<Wallet<SigningKey>, WalletError> {
let derived_priv_key =
mnemonic.derive_key(&self.derivation_path, self.password.as_deref())?;
let key: &coins_bip32::prelude::SigningKey = derived_priv_key.as_ref();
let signer = SigningKey::from_bytes(&key.to_bytes())?;
let address = secret_key_to_address(&signer);
Ok(Wallet::<SigningKey> { signer, address, chain_id: 1 })
}
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use crate::coins_bip39::English;
use tempfile::tempdir;
const TEST_DERIVATION_PATH: &str = "m/44'/60'/0'/2/1";
#[tokio::test]
async fn mnemonic_deterministic() {
// Testcases have been taken from MyCryptoWallet
const TESTCASES: [(&str, u32, Option<&str>, &str); 4] = [
(
"work man father plunge mystery proud hollow address reunion sauce theory bonus",
0u32,
Some("TREZOR123"),
"0x431a00DA1D54c281AeF638A73121B3D153e0b0F6",
),
(
"inject danger program federal spice bitter term garbage coyote breeze thought funny",
1u32,
Some("LEDGER321"),
"0x231a3D0a05d13FAf93078C779FeeD3752ea1350C",
),
(
"fire evolve buddy tenant talent favorite ankle stem regret myth dream fresh",
2u32,
None,
"0x1D86AD5eBb2380dAdEAF52f61f4F428C485460E9",
),
(
"thumb soda tape crunch maple fresh imitate cancel order blind denial giraffe",
3u32,
None,
"0xFB78b25f69A8e941036fEE2A5EeAf349D81D4ccc",
),
];
TESTCASES.iter().for_each(|(phrase, index, password, expected_addr)| {
let wallet = match password {
Some(psswd) => MnemonicBuilder::<English>::default()
.phrase(*phrase)
.index(*index)
.unwrap()
.password(psswd)
.build()
.unwrap(),
None => MnemonicBuilder::<English>::default()
.phrase(*phrase)
.index(*index)
.unwrap()
.build()
.unwrap(),
};
assert_eq!(&to_checksum(&wallet.address, None), expected_addr);
})
}
#[tokio::test]
async fn mnemonic_write_read() {
let dir = tempdir().unwrap();
// Construct a wallet from random mnemonic phrase and write it to the temp dir.
let mut rng = rand::thread_rng();
let wallet1 = MnemonicBuilder::<English>::default()
.word_count(24)
.derivation_path(TEST_DERIVATION_PATH)
.unwrap()
.write_to(dir.as_ref())
.build_random(&mut rng)
.unwrap();
// Ensure that only one file has been created.
let paths = std::fs::read_dir(dir.as_ref()).unwrap();
assert_eq!(paths.count(), 1);
// Use the newly created file's path to instantiate wallet.
let phrase_path = dir.as_ref().join(to_checksum(&wallet1.address, None));
let wallet2 = MnemonicBuilder::<English>::default()
.phrase(phrase_path.to_str().unwrap())
.derivation_path(TEST_DERIVATION_PATH)
.unwrap()
.build()
.unwrap();
// Ensure that both wallets belong to the same address.
assert_eq!(wallet1.address, wallet2.address);
dir.close().unwrap();
}
}