Skip to content

Commit

Permalink
Allow to specify entropy when generating new mnemonic with cast (#8145)
Browse files Browse the repository at this point in the history
* Allow to specify entropy when generating new mnemonic with cast

* change print color to yellow, a standard warning color

---------

Co-authored-by: poma <[email protected]>
  • Loading branch information
poma-keeps-building and poma authored Jun 13, 2024
1 parent 8e9cb1d commit b7dcf46
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
18 changes: 14 additions & 4 deletions crates/cast/bin/cmd/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, Signature, B256};
use alloy_signer::Signer;
use alloy_signer_wallet::{
coins_bip39::{English, Mnemonic},
coins_bip39::{English, Entropy, Mnemonic},
LocalWallet, MnemonicBuilder,
};
use clap::Parser;
Expand Down Expand Up @@ -61,6 +61,10 @@ pub enum WalletSubcommands {
/// Number of accounts to display
#[arg(long, short, default_value = "1")]
accounts: u8,

/// Entropy to use for the mnemonic
#[arg(long, short, conflicts_with = "words")]
entropy: Option<String>,
},

/// Generate a vanity address.
Expand Down Expand Up @@ -256,9 +260,15 @@ impl WalletSubcommands {
}
}
}
Self::NewMnemonic { words, accounts } => {
let mut rng = thread_rng();
let phrase = Mnemonic::<English>::new_with_count(&mut rng, words)?.to_phrase();
Self::NewMnemonic { words, accounts, entropy } => {
let phrase = if let Some(entropy) = entropy {
let entropy = Entropy::from_slice(&hex::decode(entropy)?)?;
println!("{}", "Generating mnemonic from provided entropy...".yellow());
Mnemonic::<English>::new_from_entropy(entropy).to_phrase()
} else {
let mut rng = thread_rng();
Mnemonic::<English>::new_with_count(&mut rng, words)?.to_phrase()
};

let builder = MnemonicBuilder::<English>::default().phrase(phrase.as_str());
let derivation_path = "m/44'/60'/0'/0/";
Expand Down
7 changes: 7 additions & 0 deletions crates/cast/tests/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,13 @@ casttest!(wallet_list_local_accounts, |prj, cmd| {
assert_eq!(list_output.matches('\n').count(), 10);
});

// tests that `cast wallet new-mnemonic --entropy` outputs the expected mnemonic
casttest!(wallet_mnemonic_from_entropy, |_prj, cmd| {
cmd.args(["wallet", "new-mnemonic", "--entropy", "0xdf9bf37e6fcdf9bf37e6fcdf9bf37e3c"]);
let output = cmd.stdout_lossy();
assert!(output.contains("test test test test test test test test test test test junk"));
});

// tests that `cast wallet private-key` with arguments outputs the private key
casttest!(wallet_private_key_from_mnemonic_arg, |_prj, cmd| {
cmd.args([
Expand Down

0 comments on commit b7dcf46

Please sign in to comment.