Skip to main content

cast/cmd/wallet/
mod.rs

1use crate::cmd::{confirm_continue, rpc_provider};
2use alloy_chains::Chain;
3use alloy_dyn_abi::TypedData;
4use alloy_primitives::{Address, B256, Signature, U256, hex};
5use alloy_provider::Provider;
6use alloy_rpc_types::Authorization;
7use alloy_signer::Signer;
8use alloy_signer_local::{
9    MnemonicBuilder, PrivateKeySigner,
10    coins_bip39::{English, Entropy, Mnemonic, WordCount},
11};
12use clap::Parser;
13use eyre::{Context, Result};
14use foundry_cli::{
15    json::{print_json_success, print_scalar},
16    opts::{ChainValueParser, RpcOpts},
17    utils::parse_json,
18};
19use foundry_common::{
20    errors::FsPathError,
21    fs,
22    fs::canonicalize_path,
23    sh_println, shell,
24    tempo::configurable_account::{
25        LINKED_ACCOUNT_SUFFIX, ca_error, ensure_link_available, link_keystore, parse_p256_key,
26        sign_p256, unlink_keystore,
27    },
28};
29use foundry_config::Config;
30use foundry_wallets::{BrowserWalletOpts, RawWalletOpts, WalletOpts, WalletSigner};
31use rand_08::{RngCore, thread_rng};
32use serde_json::{Value, json};
33use std::{
34    ffi::OsString,
35    path::{Path, PathBuf},
36    str::FromStr,
37};
38use yansi::Paint;
39
40pub mod vanity;
41use vanity::VanityArgs;
42
43pub mod list;
44use list::ListArgs;
45
46mod process_tree;
47
48pub mod session;
49use session::SessionArgs;
50
51mod touch_id;
52use touch_id::TouchIdArgs;
53
54pub(crate) mod configurable_account;
55use configurable_account::{AssembleArgs, OwnersArgs, UpgradeArgs};
56
57/// CLI arguments for `cast wallet`.
58#[derive(Debug, Parser)]
59pub enum WalletSubcommands {
60    /// Create a new random keypair, or a Tempo configurable account on Tempo
61    ///
62    /// With a Tempo signal, the new key becomes the only owner of a Tempo configurable account
63    /// (TIP-1107) with threshold 1 and salt 0, and both the account address and the owner key
64    /// address are printed. Send from the account address. A Tempo signal is `--chain` (or
65    /// `CHAIN` with `--configurable-account`), `chain` or a Tempo network in `foundry.toml`, or an
66    /// RPC (`--rpc-url`, `ETH_RPC_URL` or `foundry.toml`) that serves a Tempo chain. The account is
67    /// only created where the T14 hardfork is active: the RPC is asked when one is given,
68    /// otherwise the compiled Tempo hardfork schedule is read for the chain. Without a Tempo
69    /// signal, or before T14, it creates a plain key (EOA). Pass `--eoa` to always create one: MPP
70    /// payment channels need an EOA.
71    ///
72    /// The account needs no saved configuration: it is recomputed from the key. A keystore is
73    /// linked to its account in a `<keystore>.tempo-account` file next to it, so that
74    /// `--account <name>` sends from the account on T14; pass `--eoa` there to send from the key.
75    ///
76    /// Examples:
77    /// - cast wallet new (print a new private key and address)
78    /// - cast wallet new my-wallet (save to the default keystore directory)
79    /// - cast wallet new ~/.foundry/keystores dev (save to an encrypted keystore)
80    /// - cast wallet new --chain tempo (create a Tempo configurable account)
81    /// - cast wallet new --chain tempo --eoa (create a plain key on Tempo)
82    #[command(verbatim_doc_comment, visible_alias = "n")]
83    New {
84        /// If provided, then keypair will be written to an encrypted JSON keystore.
85        ///
86        /// A single bare argument that is not an existing directory is treated as ACCOUNT_NAME and
87        /// saved under the default keystore directory (`~/.foundry/keystores`), matching
88        /// `cast wallet import <name>`.
89        path: Option<String>,
90
91        /// Account name for the keystore file. If provided, the keystore file
92        /// will be named using this account name.
93        #[arg(value_name = "ACCOUNT_NAME")]
94        account_name: Option<String>,
95
96        /// Triggers a hidden password prompt for the JSON keystore.
97        ///
98        /// Deprecated: prompting for a hidden password is now the default.
99        #[arg(long, short, conflicts_with = "unsafe_password")]
100        password: bool,
101
102        /// Password for the JSON keystore in cleartext.
103        ///
104        /// This is UNSAFE to use and we recommend using the --password.
105        #[arg(long, env = "CAST_PASSWORD", value_name = "PASSWORD")]
106        unsafe_password: Option<String>,
107
108        /// Number of wallets to generate.
109        #[arg(long, short, default_value = "1")]
110        number: u32,
111
112        /// Overwrite existing keystore files without prompting.
113        #[arg(long)]
114        force: bool,
115
116        /// Enroll the keystore for Touch ID-assisted authentication on macOS.
117        ///
118        /// The macOS login password and explicit keystore passwords remain available.
119        #[arg(long, hide = !cfg!(all(target_os = "macos", feature = "touch-id")))]
120        touch_id: bool,
121
122        /// Create a Tempo configurable account owned by the new key. This is the default when a
123        /// Tempo signal is present and T14 is active there; the flag also reports when there is
124        /// none.
125        #[arg(long)]
126        configurable_account: bool,
127
128        /// Create a plain key (EOA) even with a Tempo signal.
129        #[arg(long, conflicts_with = "configurable_account")]
130        eoa: bool,
131
132        /// The chain to create the wallet for. A Tempo chain creates a configurable account.
133        /// Defaults to `CHAIN` with `--configurable-account`.
134        #[arg(long, value_parser = ChainValueParser::default())]
135        chain: Option<Chain>,
136
137        #[command(flatten)]
138        rpc: RpcOpts,
139    },
140
141    /// Generates a random BIP39 mnemonic phrase
142    #[command(visible_alias = "nm")]
143    NewMnemonic {
144        /// Number of words for the mnemonic
145        #[arg(long, short, default_value = "12")]
146        words: usize,
147
148        /// Number of accounts to display
149        #[arg(long, short, default_value = "1")]
150        accounts: u8,
151
152        /// Entropy to use for the mnemonic
153        #[arg(long, short, conflicts_with = "words")]
154        entropy: Option<String>,
155    },
156
157    /// Generate a vanity address.
158    #[command(visible_alias = "va")]
159    Vanity(VanityArgs),
160
161    /// Convert a private key to an address.
162    #[command(visible_aliases = &["a", "addr"])]
163    Address {
164        /// If provided, the address will be derived from the specified private key.
165        #[arg(value_name = "PRIVATE_KEY")]
166        private_key_override: Option<String>,
167
168        #[command(flatten)]
169        wallet: WalletOpts,
170
171        #[command(flatten)]
172        browser: BrowserWalletOpts,
173    },
174
175    /// Derive accounts from a mnemonic
176    ///
177    /// Examples:
178    /// - cast wallet derive "test test test test test test test test test test test junk"
179    /// - cast wallet derive "$MNEMONIC" --accounts 5
180    #[command(verbatim_doc_comment, visible_alias = "d")]
181    Derive {
182        /// The accounts will be derived from the specified mnemonic phrase.
183        #[arg(value_name = "MNEMONIC")]
184        mnemonic: String,
185
186        /// Number of accounts to display.
187        #[arg(long, short, default_value = "1")]
188        accounts: Option<u8>,
189
190        /// Insecure mode: display private keys in the terminal.
191        #[arg(long, default_value = "false")]
192        insecure: bool,
193    },
194
195    /// Sign a message or typed data
196    ///
197    /// Examples:
198    /// - cast wallet sign "hello" --account dev
199    /// - cast wallet sign "hello" --private-key $PK
200    /// - cast wallet sign --data --from-file typed_data.json --ledger
201    /// - cast wallet sign --no-hash --p256 $DIGEST --private-key $P256_KEY
202    #[command(verbatim_doc_comment, visible_alias = "s")]
203    Sign {
204        /// The message, typed data, or hash to sign.
205        ///
206        /// Messages starting with 0x are expected to be hex encoded, which get decoded before
207        /// being signed.
208        ///
209        /// The message will be prefixed with the Ethereum Signed Message header and hashed before
210        /// signing, unless `--no-hash` is provided.
211        ///
212        /// Typed data can be provided as a json string or a file name.
213        /// Use --data flag to denote the message is a string of typed data.
214        /// Use --data --from-file to denote the message is a file name containing typed data.
215        /// The data will be combined and hashed using the EIP712 specification before signing.
216        /// The data should be formatted as JSON.
217        message: String,
218
219        /// Treat the message as JSON typed data.
220        #[arg(long)]
221        data: bool,
222
223        /// Treat the message as a file containing JSON typed data. Requires `--data`.
224        #[arg(long, requires = "data")]
225        from_file: bool,
226
227        /// Treat the message as a raw 32-byte hash and sign it directly without hashing it again.
228        #[arg(long, conflicts_with = "data")]
229        no_hash: bool,
230
231        /// Sign the hash with a raw P-256 private key, from `--private-key` or `--interactive`,
232        /// and print a Tempo P-256 signature. A P-256 owner of a configurable account approves
233        /// the digest from `cast mktx --raw-unsigned --tempo.digest` this way, for `cast wallet
234        /// assemble`. Requires `--no-hash`.
235        #[arg(
236            long,
237            requires = "no_hash",
238            conflicts_with_all = [
239                "browser", "ledger", "trezor", "mnemonic", "aws", "gcp", "turnkey",
240            ]
241        )]
242        p256: bool,
243
244        #[command(flatten)]
245        wallet: WalletOpts,
246
247        #[command(flatten)]
248        browser: BrowserWalletOpts,
249    },
250
251    /// EIP-7702 sign authorization.
252    #[command(visible_alias = "sa")]
253    SignAuth {
254        /// Address to sign authorization for.
255        address: Address,
256
257        #[command(flatten)]
258        rpc: RpcOpts,
259
260        #[arg(long)]
261        nonce: Option<u64>,
262
263        #[arg(long)]
264        chain: Option<Chain>,
265
266        /// Skip the confirmation prompt for wildcard chain authorizations.
267        #[arg(long)]
268        force: bool,
269
270        /// If set, indicates the authorization will be broadcast by the signing account itself.
271        /// This means the nonce used will be the current nonce + 1 (to account for the
272        /// transaction that will include this authorization).
273        #[arg(long, conflicts_with = "nonce")]
274        self_broadcast: bool,
275
276        #[command(flatten)]
277        wallet: WalletOpts,
278    },
279
280    /// Verify the signature of a message
281    ///
282    /// Examples:
283    /// - cast wallet verify --address $ADDRESS "hello" $SIGNATURE
284    /// - cast wallet verify --address $ADDRESS --no-hash $HASH $SIGNATURE
285    #[command(verbatim_doc_comment, visible_alias = "v")]
286    Verify {
287        /// The original message.
288        ///
289        /// Treats 0x-prefixed strings as hex encoded bytes.
290        /// Non 0x-prefixed strings are treated as raw input message.
291        ///
292        /// The message will be prefixed with the Ethereum Signed Message header and hashed before
293        /// signing, unless `--no-hash` is provided.
294        ///
295        /// Typed data can be provided as a json string or a file name.
296        /// Use --data flag to denote the message is a string of typed data.
297        /// Use --data --from-file to denote the message is a file name containing typed data.
298        /// The data will be combined and hashed using the EIP712 specification before signing.
299        /// The data should be formatted as JSON.
300        message: String,
301
302        /// The signature to verify.
303        signature: Signature,
304
305        /// The address of the message signer.
306        #[arg(long, short)]
307        address: Address,
308
309        /// Treat the message as JSON typed data.
310        #[arg(long)]
311        data: bool,
312
313        /// Treat the message as a file containing JSON typed data. Requires `--data`.
314        #[arg(long, requires = "data")]
315        from_file: bool,
316
317        /// Treat the message as a raw 32-byte hash and sign it directly without hashing it again.
318        #[arg(long, conflicts_with = "data")]
319        no_hash: bool,
320    },
321
322    /// Import a private key into an encrypted keystore
323    ///
324    /// Examples:
325    /// - cast wallet import dev --interactive (prompt for the private key)
326    /// - cast wallet import dev --private-key $PK
327    /// - cast wallet import dev --mnemonic "$MNEMONIC" --mnemonic-index 1
328    #[command(verbatim_doc_comment, visible_alias = "i")]
329    Import {
330        /// The name for the account in the keystore.
331        #[arg(value_name = "ACCOUNT_NAME")]
332        account_name: String,
333        /// If provided, keystore will be saved here instead of the default keystores directory
334        /// (~/.foundry/keystores)
335        #[arg(long, short)]
336        keystore_dir: Option<String>,
337        /// Password for the JSON keystore in cleartext
338        /// This is unsafe, we recommend using the default hidden password prompt
339        #[arg(long, env = "CAST_UNSAFE_PASSWORD", value_name = "PASSWORD")]
340        unsafe_password: Option<String>,
341        /// Enroll the keystore for Touch ID-assisted authentication on macOS.
342        ///
343        /// The macOS login password and explicit keystore passwords remain available.
344        #[arg(long, hide = !cfg!(all(target_os = "macos", feature = "touch-id")))]
345        touch_id: bool,
346        #[command(flatten)]
347        raw_wallet_options: RawWalletOpts,
348    },
349
350    /// List all the accounts in the keystore default directory
351    #[command(visible_alias = "ls")]
352    List(ListArgs),
353
354    /// Manage temporary Tempo wallet sessions.
355    Session(SessionArgs),
356
357    /// Manage Touch ID enrollment for encrypted keystores.
358    TouchId(TouchIdArgs),
359
360    /// Show or change the owners of a Tempo configurable account.
361    ///
362    /// The configuration is rebuilt from the chain, from the account's latest configuration event.
363    ///
364    /// Examples:
365    /// - cast wallet owners $ACCOUNT (show the owners and threshold)
366    /// - cast wallet owners add $ACCOUNT $OWNER --threshold 2 --account dev
367    /// - cast wallet owners remove $ACCOUNT $OWNER --account dev
368    /// - cast wallet owners threshold $ACCOUNT 1 --account dev
369    #[command(verbatim_doc_comment)]
370    Owners(OwnersArgs),
371
372    /// Upgrade an EOA to a Tempo configurable account in place (TIP-1113).
373    ///
374    /// The account keeps its address, and its key can no longer sign for it: only the owners
375    /// can. This is irreversible, and the account can no longer act as an MPP voucher signer.
376    ///
377    /// Examples:
378    /// - cast wallet upgrade --account dev (the account's key becomes its only owner)
379    /// - cast wallet upgrade --owner $A --owner $B:2 --threshold 2 --account dev
380    #[command(verbatim_doc_comment)]
381    Upgrade(UpgradeArgs),
382
383    /// Combine owner signatures into a signed Tempo configurable account transaction.
384    ///
385    /// Owners on other machines sign the digest from `cast mktx --raw-unsigned --tempo.digest`.
386    /// Prints the signed raw transaction for `cast publish`.
387    ///
388    /// Examples:
389    /// - read TX DIGEST <<< "$(cast mktx $TO 'f()' --from $ACCOUNT --raw-unsigned --tempo.digest)"
390    /// - cast wallet sign --no-hash $DIGEST --account owner1 (on each owner's machine)
391    /// - cast wallet assemble $TX $SIG1 $SIG2 --from $ACCOUNT
392    /// - cast wallet assemble $TX passkey-assertion.json --from $ACCOUNT
393    #[command(verbatim_doc_comment)]
394    Assemble(AssembleArgs),
395
396    /// Remove a wallet from the keystore.
397    ///
398    /// This command requires the wallet alias and will prompt for a password to ensure that only
399    /// an authorized user can remove the wallet.
400    #[command(visible_aliases = &["rm"], override_usage = "cast wallet remove --name <NAME>")]
401    Remove {
402        /// The alias (or name) of the wallet to remove.
403        #[arg(long, required = true)]
404        name: String,
405        /// Optionally provide the keystore directory if not provided. default directory will be
406        /// used (~/.foundry/keystores).
407        #[arg(long)]
408        dir: Option<String>,
409        /// Password for the JSON keystore in cleartext
410        /// This is unsafe, we recommend using the default hidden password prompt
411        #[arg(long, env = "CAST_UNSAFE_PASSWORD", value_name = "PASSWORD")]
412        unsafe_password: Option<String>,
413    },
414
415    /// Derives private key from mnemonic
416    ///
417    /// Examples:
418    /// - cast wallet private-key "test test test test test test test test test test test junk"
419    /// - cast wallet private-key "$MNEMONIC" 1 (derive the key at index 1)
420    /// - cast wallet private-key "$MNEMONIC" "m/44'/60'/0'/0/1" (use a custom path)
421    #[command(verbatim_doc_comment, name = "private-key", visible_alias = "pk", aliases = &["derive-private-key", "--derive-private-key"])]
422    PrivateKey {
423        /// If provided, the private key will be derived from the specified mnemonic phrase.
424        #[arg(value_name = "MNEMONIC")]
425        mnemonic_override: Option<String>,
426
427        /// If provided, the private key will be derived using the
428        /// specified mnemonic index (if integer) or derivation path.
429        #[arg(value_name = "MNEMONIC_INDEX_OR_DERIVATION_PATH")]
430        mnemonic_index_or_derivation_path_override: Option<String>,
431
432        #[command(flatten)]
433        wallet: WalletOpts,
434    },
435    /// Get the public key for the given private key.
436    #[command(visible_aliases = &["pubkey"])]
437    PublicKey {
438        /// If provided, the public key will be derived from the specified private key.
439        #[arg(long = "raw-private-key", value_name = "PRIVATE_KEY")]
440        private_key_override: Option<String>,
441
442        #[command(flatten)]
443        wallet: WalletOpts,
444    },
445    /// Decrypt a keystore file to get the private key
446    #[command(name = "decrypt-keystore", visible_alias = "dk")]
447    DecryptKeystore {
448        /// The name for the account in the keystore.
449        #[arg(value_name = "ACCOUNT_NAME")]
450        account_name: String,
451        /// If not provided, keystore will try to be located at the default keystores directory
452        /// (~/.foundry/keystores)
453        #[arg(long, short)]
454        keystore_dir: Option<String>,
455        /// Password for the JSON keystore in cleartext
456        /// This is unsafe, we recommend using the default hidden password prompt
457        #[arg(long, env = "CAST_UNSAFE_PASSWORD", value_name = "PASSWORD")]
458        unsafe_password: Option<String>,
459    },
460
461    /// Change the password of a keystore file
462    #[command(name = "change-password", visible_alias = "cp")]
463    ChangePassword {
464        /// The name for the account in the keystore.
465        #[arg(value_name = "ACCOUNT_NAME")]
466        account_name: String,
467        /// If not provided, keystore will try to be located at the default keystores directory
468        /// (~/.foundry/keystores)
469        #[arg(long, short)]
470        keystore_dir: Option<String>,
471        /// Current password for the JSON keystore in cleartext
472        /// This is unsafe, we recommend using the default hidden password prompt
473        #[arg(long, env = "CAST_UNSAFE_PASSWORD", value_name = "PASSWORD")]
474        unsafe_password: Option<String>,
475        /// New password for the JSON keystore in cleartext
476        /// This is unsafe, we recommend using the default hidden password prompt
477        #[arg(long, env = "CAST_UNSAFE_NEW_PASSWORD", value_name = "NEW_PASSWORD")]
478        unsafe_new_password: Option<String>,
479    },
480}
481
482impl WalletSubcommands {
483    pub async fn run(self) -> Result<()> {
484        match self {
485            Self::New {
486                path,
487                mut account_name,
488                unsafe_password,
489                number,
490                password,
491                force,
492                touch_id,
493                configurable_account,
494                eoa,
495                chain,
496                rpc,
497            } => {
498                ensure_touch_id_available(touch_id)?;
499                let configurable = configurable_account::new_wallet_is_configurable(
500                    eoa,
501                    configurable_account,
502                    chain,
503                    &rpc,
504                )
505                .await?;
506
507                let path = match path {
508                    Some(path) => Some(resolve_new_dir(path, &mut account_name)?),
509                    None if unsafe_password.is_some() || password || touch_id => {
510                        let path = resolve_keystore_dir(None)?;
511                        fs::create_dir_all(&path)?;
512                        Some(path)
513                    }
514                    None => None,
515                };
516
517                if let Some(name) = &account_name {
518                    ensure_account_name_available(name)?;
519                }
520
521                let json = match path {
522                    Some(path) => new_keystores(
523                        &path,
524                        account_name.as_deref(),
525                        unsafe_password,
526                        number,
527                        force,
528                        touch_id,
529                        configurable,
530                    )?,
531                    None => new_keypairs(number, configurable)?,
532                };
533                if shell::is_json() {
534                    print_json_success(json)?;
535                }
536            }
537            Self::NewMnemonic { words, accounts, entropy } => {
538                let phrase = if let Some(entropy) = entropy {
539                    let entropy = Entropy::from_slice(&hex::decode(entropy)?)?;
540                    Mnemonic::<English>::new_from_entropy(entropy).to_phrase()
541                } else {
542                    let mut entropy = vec![0u8; WordCount::try_from(words)?.entropy_bytes()];
543                    thread_rng().fill_bytes(&mut entropy);
544                    Mnemonic::<English>::new_from_entropy(Entropy::from_slice(&entropy)?)
545                        .to_phrase()
546                };
547
548                let format_json = shell::is_json();
549                if !format_json {
550                    sh_println!("{}", "Generating mnemonic from provided entropy...".yellow())?;
551                }
552
553                let builder = MnemonicBuilder::<English>::default().phrase(phrase.as_str());
554                let wallets = (0..accounts)
555                    .map(|i| -> Result<_> {
556                        Ok(builder
557                            .clone()
558                            .derivation_path(format!("m/44'/60'/0'/0/{i}"))?
559                            .build()?)
560                    })
561                    .collect::<Result<Vec<_>>>()?;
562
563                if !format_json {
564                    sh_println!("{}", "Successfully generated a new mnemonic.".green())?;
565                    sh_println!("Phrase:\n{}", phrase.as_str())?;
566                    sh_println!("\nAccounts:")?;
567                }
568
569                let mut accounts = Vec::new();
570                for (i, wallet) in wallets.iter().enumerate() {
571                    let public_key = hex::encode_prefixed(wallet.public_key());
572                    let private_key = hex::encode_prefixed(wallet.to_bytes());
573                    if format_json {
574                        let mut account = serde_json::Map::new();
575                        account.insert("address".into(), json!(wallet.address().to_string()));
576                        if shell::verbosity() > 0 {
577                            account.insert("public_key".into(), json!(public_key));
578                        }
579                        account.insert("private_key".into(), json!(private_key));
580                        accounts.push(Value::Object(account));
581                    } else {
582                        sh_println!("- Account {i}:")?;
583                        sh_println!("Address:     {}", wallet.address())?;
584                        if shell::verbosity() > 0 {
585                            sh_println!("Public key:  {public_key}")?;
586                        }
587                        sh_println!("Private key: {private_key}\n")?;
588                    }
589                }
590
591                if format_json {
592                    print_json_success(
593                        json!({ "mnemonic": phrase.as_str(), "accounts": accounts }),
594                    )?;
595                }
596            }
597            Self::Vanity(cmd) => {
598                cmd.run()?;
599            }
600            Self::Address { wallet, browser, private_key_override } => {
601                let addr = if let Some(pk) = private_key_override {
602                    raw_wallet(RawWalletOpts { private_key: Some(pk), ..Default::default() })
603                        .signer()
604                        .await?
605                        .address()
606                } else if let Some(browser) = browser.run::<alloy_network::Ethereum>().await? {
607                    browser.address()
608                } else {
609                    wallet.signer().await?.address()
610                };
611                print_scalar(addr.to_checksum(None))?;
612            }
613            Self::Derive { mnemonic, accounts, insecure } => {
614                let format_json = shell::is_json();
615                let mut accounts_json = Vec::new();
616                for i in 0..accounts.unwrap_or(1) {
617                    let wallet = raw_wallet(RawWalletOpts {
618                        mnemonic: Some(mnemonic.clone()),
619                        mnemonic_index: i as u32,
620                        ..Default::default()
621                    })
622                    .signer()
623                    .await?;
624                    let WalletSigner::Local(wallet) = wallet else {
625                        eyre::bail!("Only local wallets are supported by this command");
626                    };
627
628                    let address = wallet.address().to_checksum(None);
629                    let private_key = hex::encode_prefixed(wallet.to_bytes());
630                    if format_json {
631                        accounts_json.push(if insecure {
632                            json!({ "address": address, "private_key": private_key })
633                        } else {
634                            json!({ "address": address })
635                        });
636                    } else {
637                        sh_println!("- Account {i}:")?;
638                        if insecure {
639                            sh_println!("Address:     {address}")?;
640                            sh_println!("Private key: {private_key}\n")?;
641                        } else {
642                            sh_println!("Address:     {address}\n")?;
643                        }
644                    }
645                }
646
647                if format_json {
648                    print_json_success(accounts_json)?;
649                }
650            }
651            Self::PublicKey { wallet, private_key_override } => {
652                let wallet = private_key_override
653                    .map(|pk| {
654                        raw_wallet(RawWalletOpts { private_key: Some(pk), ..Default::default() })
655                    })
656                    .unwrap_or(wallet)
657                    .signer()
658                    .await?;
659                let WalletSigner::Local(wallet) = wallet else {
660                    eyre::bail!("Only local wallets are supported by this command");
661                };
662                print_scalar(hex::encode_prefixed(wallet.public_key()))?;
663            }
664            Self::Sign { message, data, from_file, no_hash, p256, wallet, browser } => {
665                if browser.browser && no_hash {
666                    eyre::bail!("Raw hash signing is not supported with a browser wallet");
667                }
668
669                let typed_data = data.then(|| parse_typed_data(&message, from_file)).transpose()?;
670
671                let (signature, address) = if p256 {
672                    let private_key = match wallet.raw.private_key {
673                        _ if wallet.raw.interactive => {
674                            rpassword::prompt_password("Enter P-256 private key: ")?
675                        }
676                        Some(private_key) => private_key,
677                        None => eyre::bail!(
678                            "--p256 signs with a raw P-256 private key; pass it with \
679                             --private-key or --interactive"
680                        ),
681                    };
682                    let hash = B256::from_str(&message).wrap_err("invalid 32-byte hash")?;
683                    let sig = sign_p256(&parse_p256_key(&private_key)?, &hash)?;
684                    let address = sig.recover_signer(&hash).map_err(ca_error)?;
685                    (sig.to_bytes().to_vec(), address)
686                } else if let Some(browser) = browser.run::<alloy_network::Ethereum>().await? {
687                    let sig = if let Some(typed_data) = &typed_data {
688                        browser.sign_dynamic_typed_data(typed_data).await?
689                    } else {
690                        browser.sign_message(&hex_str_to_bytes(&message)?).await?
691                    };
692                    (sig.as_bytes().to_vec(), browser.address())
693                } else {
694                    let wallet = wallet.signer().await?;
695                    let sig = if let Some(typed_data) = &typed_data {
696                        wallet.sign_dynamic_typed_data(typed_data).await?
697                    } else if no_hash {
698                        wallet.sign_hash(&hex::decode(&message)?[..].try_into()?).await?
699                    } else {
700                        wallet.sign_message(&hex_str_to_bytes(&message)?).await?
701                    };
702                    (sig.as_bytes().to_vec(), wallet.address())
703                };
704
705                let signature = hex::encode(signature);
706                if shell::verbosity() == 0 {
707                    print_scalar(format!("0x{signature}"))?;
708                } else if shell::is_json() {
709                    print_json_success(json!({
710                        "message": message,
711                        "address": address,
712                        "signature": signature,
713                    }))?;
714                } else {
715                    sh_status!("Successfully signed!")?;
716                    sh_status!("   Message: {message}")?;
717                    sh_status!("   Address: {address}")?;
718                    sh_println!("0x{signature}")?;
719                }
720            }
721            Self::SignAuth { rpc, nonce, chain, force, wallet, address, self_broadcast } => {
722                let provider = rpc_provider(&rpc)?;
723                let chain_id = match chain {
724                    Some(chain) => chain.id(),
725                    None => provider.get_chain_id().await?,
726                };
727                if chain_id == 0 && !force {
728                    sh_warn!(
729                        "Chain ID 0 creates an EIP-7702 authorization that is valid on every chain."
730                    )?;
731                    if !confirm_continue()? {
732                        return Ok(());
733                    }
734                }
735
736                let wallet = wallet.signer().await?;
737                let nonce = match nonce {
738                    Some(nonce) => nonce,
739                    // When self-broadcasting, the authorization nonce needs to be +1 because the
740                    // transaction itself will consume the current nonce.
741                    None => {
742                        provider.get_transaction_count(wallet.address()).await?
743                            + u64::from(self_broadcast)
744                    }
745                };
746                let auth = Authorization { chain_id: U256::from(chain_id), address, nonce };
747                let signature = wallet.sign_hash(&auth.signature_hash()).await?;
748                let signed = hex::encode_prefixed(alloy_rlp::encode(auth.into_signed(signature)));
749
750                if shell::verbosity() == 0 {
751                    print_scalar(signed)?;
752                } else if shell::is_json() {
753                    print_json_success(json!({
754                        "nonce": nonce,
755                        "chain_id": chain_id,
756                        "address": wallet.address(),
757                        "signature": signed,
758                    }))?;
759                } else {
760                    sh_status!("Successfully signed!")?;
761                    sh_status!("   Nonce: {nonce}")?;
762                    sh_status!("   Chain ID: {chain_id}")?;
763                    sh_status!("   Address: {}", wallet.address())?;
764                    sh_println!("{signed}")?;
765                }
766            }
767            Self::Verify { message, signature, address, data, from_file, no_hash } => {
768                let recovered_address =
769                    recover_signer(&message, &signature, data, from_file, no_hash)?;
770
771                if address != recovered_address {
772                    eyre::bail!("Validation failed. Address {address} did not sign this message.");
773                }
774                if shell::is_json() {
775                    print_json_success(json!({"address": address, "result": true}))?;
776                } else {
777                    sh_println!("Validation succeeded. Address {address} signed this message.")?;
778                }
779            }
780            Self::Import {
781                account_name,
782                keystore_dir,
783                unsafe_password,
784                touch_id,
785                raw_wallet_options,
786            } => {
787                ensure_touch_id_available(touch_id)?;
788                ensure_account_name_available(&account_name)?;
789                let dir = resolve_keystore_dir(keystore_dir)?;
790                fs::create_dir_all(&dir)?;
791
792                let keystore_path = dir.join(&account_name);
793                if keystore_path.exists() {
794                    eyre::bail!("Keystore file already exists at {}", keystore_path.display());
795                }
796                if touch_id {
797                    ensure_touch_id_sidecar_available(&keystore_path)?;
798                }
799
800                let Some(WalletSigner::Local(wallet)) = raw_wallet_options.signer()? else {
801                    eyre::bail!(
802                        "\
803Did you set a private key or mnemonic?
804Run `cast wallet import --help` and use the corresponding CLI
805flag to set your key via:
806--private-key, --mnemonic-path or --interactive."
807                    );
808                };
809
810                let password = password_or_prompt(unsafe_password, "Enter password: ")?;
811                let (wallet, _) = PrivateKeySigner::encrypt_keystore(
812                    dir,
813                    &mut thread_rng(),
814                    wallet.to_bytes(),
815                    &password,
816                    Some(&account_name),
817                )?;
818                let address = wallet.address();
819                // An imported key is not linked to a configurable account; drop a link that a
820                // removed keystore of the same name left.
821                unlink_keystore(&keystore_path)?;
822
823                if touch_id {
824                    let action = format!("keystore was imported at {}", keystore_path.display());
825                    enroll_new_keystore(&keystore_path, &password, &action, 0)?;
826                }
827
828                if shell::is_json() {
829                    let mut result = json!({"account": account_name, "address": address});
830                    if touch_id {
831                        result["touch_id"] = json!(true);
832                    }
833                    print_json_success(result)?;
834                } else {
835                    sh_println!(
836                        "{}",
837                        format!(
838                            "`{account_name}` keystore was saved successfully. Address: {address:?}"
839                        )
840                        .green()
841                    )?;
842                    if touch_id {
843                        sh_status!("{TOUCH_ID_ENROLLED_STATUS}")?;
844                    }
845                }
846            }
847            Self::List(cmd) => {
848                cmd.run().await?;
849            }
850            Self::Session(args) => {
851                args.run().await?;
852            }
853            Self::TouchId(args) => {
854                args.run()?;
855            }
856            Self::Owners(args) => {
857                args.run().await?;
858            }
859            Self::Upgrade(args) => {
860                args.run().await?;
861            }
862            Self::Assemble(args) => {
863                args.run().await?;
864            }
865            Self::Remove { name, dir, unsafe_password } => {
866                let keystore_path = existing_keystore_path(&name, dir)?;
867                let password = password_or_prompt(unsafe_password, "Enter password: ")?;
868                if PrivateKeySigner::decrypt_keystore(&keystore_path, password).is_err() {
869                    eyre::bail!("Invalid password - wallet removal cancelled");
870                }
871
872                remove_touch_id_sidecar(&keystore_path)?;
873                unlink_keystore(&keystore_path)?;
874                std::fs::remove_file(&keystore_path).wrap_err_with(|| {
875                    format!("Failed to remove keystore file at {}", keystore_path.display())
876                })?;
877
878                if shell::is_json() {
879                    print_json_success(json!({"account": name, "removed": true}))?;
880                } else {
881                    sh_println!(
882                        "{}",
883                        format!("`{name}` keystore was removed successfully.").green()
884                    )?;
885                }
886            }
887            Self::PrivateKey {
888                wallet,
889                mnemonic_override,
890                mnemonic_index_or_derivation_path_override,
891            } => {
892                let (index_override, derivation_path_override) =
893                    match mnemonic_index_or_derivation_path_override {
894                        Some(value) => match value.parse::<u32>() {
895                            Ok(index) => (Some(index), None),
896                            Err(_) => (None, Some(value)),
897                        },
898                        None => (None, None),
899                    };
900                let wallet = WalletOpts {
901                    raw: RawWalletOpts {
902                        mnemonic: mnemonic_override.or(wallet.raw.mnemonic),
903                        mnemonic_index: index_override.unwrap_or(wallet.raw.mnemonic_index),
904                        hd_path: derivation_path_override.or(wallet.raw.hd_path),
905                        ..wallet.raw
906                    },
907                    ..wallet
908                }
909                .signer()
910                .await?;
911                let WalletSigner::Local(wallet) = wallet else {
912                    eyre::bail!("Only local wallets are supported by this command.");
913                };
914
915                let private_key = hex::encode_prefixed(wallet.to_bytes());
916                if shell::verbosity() == 0 {
917                    print_scalar(private_key)?;
918                } else if shell::is_json() {
919                    print_json_success(json!({
920                        "address": wallet.address(),
921                        "private_key": private_key,
922                    }))?;
923                } else {
924                    sh_println!("Address:     {}", wallet.address())?;
925                    sh_println!("Private key: {private_key}")?;
926                }
927            }
928            Self::DecryptKeystore { account_name, keystore_dir, unsafe_password } => {
929                let keypath = existing_keystore_path(&account_name, keystore_dir)?;
930                let password = password_or_prompt(unsafe_password, "Enter password: ")?;
931                let wallet = PrivateKeySigner::decrypt_keystore(keypath, password)?;
932
933                let private_key = wallet.to_bytes();
934                if shell::is_json() {
935                    print_json_success(
936                        json!({"account": account_name, "private_key": private_key}),
937                    )?;
938                } else {
939                    sh_println!(
940                        "{}",
941                        format!("{account_name}'s private key is: {private_key}").green()
942                    )?;
943                }
944            }
945            Self::ChangePassword {
946                account_name,
947                keystore_dir,
948                unsafe_password,
949                unsafe_new_password,
950            } => {
951                let keypath = existing_keystore_path(&account_name, keystore_dir)?;
952                let sidecar = touch_id_sidecar_path(&keypath);
953
954                let touch_id_enrolled = match touch_id_sidecar_state(&sidecar)? {
955                    TouchIdSidecarState::Missing => false,
956                    TouchIdSidecarState::Recognized => true,
957                    TouchIdSidecarState::Keystore => {
958                        eyre::bail!(
959                            "refusing to change the password because {} is an existing keystore",
960                            sidecar.display()
961                        );
962                    }
963                    TouchIdSidecarState::Unknown => {
964                        // Preserve useful structured errors such as UnsupportedVersion.
965                        #[cfg(all(target_os = "macos", feature = "touch-id"))]
966                        foundry_wallets::touch_id::policy(&keypath)?;
967
968                        // Never continue after an Unknown classification, even if another
969                        // parser happens to accept the file.
970                        eyre::bail!(
971                            "refusing to change the password because {} exists and is not a recognized Touch ID sidecar",
972                            sidecar.display()
973                        );
974                    }
975                };
976
977                #[cfg(all(target_os = "macos", feature = "touch-id"))]
978                let touch_id_policy = touch_id_enrolled
979                    .then(|| foundry_wallets::touch_id::policy(&keypath))
980                    .transpose()?;
981
982                let current_password =
983                    password_or_prompt(unsafe_password, "Enter current password: ")?;
984                // decrypt the keystore to verify the current password and get the private key
985                let wallet = PrivateKeySigner::decrypt_keystore(&keypath, current_password.clone())
986                    .map_err(|_| eyre::eyre!("Invalid password - password change cancelled"))?;
987
988                let new_password = password_or_prompt(unsafe_new_password, "Enter new password: ")?;
989                if current_password == new_password {
990                    eyre::bail!("New password cannot be the same as the current password");
991                }
992
993                let (wallet, _) = PrivateKeySigner::encrypt_keystore(
994                    keypath.parent().unwrap_or(Path::new("")),
995                    &mut thread_rng(),
996                    wallet.to_bytes(),
997                    &new_password,
998                    Some(&account_name),
999                )?;
1000
1001                #[cfg(all(target_os = "macos", feature = "touch-id"))]
1002                if let Some(policy) = touch_id_policy {
1003                    foundry_wallets::touch_id::enroll(&keypath, &new_password, policy).map_err(
1004                        |error| {
1005                            touch_id_enrollment_failure(
1006                                &keypath,
1007                                &format!(
1008                                    "password for keystore `{account_name}` was changed at {}",
1009                                    keypath.display()
1010                                ),
1011                                error,
1012                            )
1013                        },
1014                    )?;
1015                }
1016
1017                #[cfg(not(all(target_os = "macos", feature = "touch-id")))]
1018                if touch_id_enrolled {
1019                    match remove_touch_id_sidecar(&keypath) {
1020                        Ok(true) => {
1021                            sh_warn!(
1022                                "Removed the stale Touch ID enrollment after changing the password"
1023                            )?;
1024                        }
1025                        Ok(false) => {}
1026                        Err(cleanup_error) => {
1027                            eyre::bail!(
1028                                "password changed, but Touch ID sidecar cleanup failed: {cleanup_error}. The new password is valid; remove {} manually",
1029                                sidecar.display()
1030                            );
1031                        }
1032                    }
1033                }
1034
1035                let address = wallet.address();
1036                if shell::is_json() {
1037                    print_json_success(json!({"account": account_name, "address": address}))?;
1038                } else {
1039                    sh_println!(
1040                        "{}",
1041                        format!(
1042                            "Password for keystore `{account_name}` was changed successfully. Address: {address:?}"
1043                        )
1044                        .green()
1045                    )?;
1046                }
1047            }
1048        };
1049
1050        Ok(())
1051    }
1052}
1053
1054const TOUCH_ID_ENROLLED_STATUS: &str =
1055    "Touch ID-assisted unlock enrolled; password-based unlock remains available.";
1056
1057/// Creates `number` encrypted keystores in `dir`, returning their JSON records in JSON mode.
1058fn new_keystores(
1059    dir: &Path,
1060    account_name: Option<&str>,
1061    unsafe_password: Option<String>,
1062    number: u32,
1063    force: bool,
1064    touch_id: bool,
1065    configurable: bool,
1066) -> Result<Vec<Value>> {
1067    let password = password_or_prompt(unsafe_password, "Enter secret: ")?;
1068    let names = (0..number)
1069        .map(|i| account_name.map(|name| indexed_account_name(name, number, i)))
1070        .collect::<Vec<_>>();
1071
1072    if touch_id {
1073        for name in names.iter().flatten() {
1074            ensure_touch_id_sidecar_available(&dir.join(name))?;
1075        }
1076    }
1077    // A link must not replace a keystore that an earlier version created under its name.
1078    if configurable {
1079        for name in names.iter().flatten() {
1080            ensure_link_available(&dir.join(name))?;
1081        }
1082    }
1083
1084    // Prevent accidental overwriting: check all target files upfront.
1085    if !force {
1086        let existing =
1087            names.iter().flatten().filter(|name| dir.join(name).exists()).collect::<Vec<_>>();
1088        if !existing.is_empty() {
1089            sh_eprintln!("The following keystore file(s) already exist:")?;
1090            for file in &existing {
1091                sh_eprintln!("   - {file}")?;
1092            }
1093            let input: String = foundry_common::prompt!(
1094                "\nDo you want to overwrite all {} file(s)? [y/N]: ",
1095                existing.len()
1096            )?;
1097            if !input.trim().eq_ignore_ascii_case("y") {
1098                eyre::bail!("Operation cancelled. No keystores were modified.");
1099            }
1100        }
1101    }
1102
1103    let mut rng = thread_rng();
1104    let mut json_values = Vec::new();
1105    for (i, name) in names.iter().enumerate() {
1106        let (wallet, uuid) =
1107            PrivateKeySigner::new_keystore(dir, &mut rng, &password, name.as_deref())?;
1108        let keystore_path = dir.join(name.as_deref().unwrap_or(&uuid));
1109
1110        if touch_id {
1111            let action = format!("keystore was created at {}", keystore_path.display());
1112            enroll_new_keystore(&keystore_path, &password, &action, i)?;
1113        }
1114
1115        let owner = wallet.address().to_checksum(None);
1116        let account = new_account(wallet.address(), configurable)?;
1117        // Link the keystore to its configurable account, so that `--account` sends from it, and
1118        // drop a link that an overwritten keystore left.
1119        if configurable {
1120            link_keystore(&keystore_path, wallet.address())?;
1121        } else {
1122            unlink_keystore(&keystore_path)?;
1123        }
1124        if shell::is_json() {
1125            let mut result = json!({
1126                "address": account.as_deref().unwrap_or(&owner),
1127                "public_key": hex::encode_prefixed(wallet.public_key()),
1128                "path": format!("{}", keystore_path.display()),
1129            });
1130            if account.is_some() {
1131                result["owner"] = json!(owner);
1132            }
1133            if touch_id {
1134                result["touch_id"] = json!(true);
1135            }
1136            json_values.push(result);
1137        } else {
1138            sh_status!("Created new encrypted keystore file: {}", keystore_path.display())?;
1139            if touch_id {
1140                sh_status!("{TOUCH_ID_ENROLLED_STATUS}")?;
1141            }
1142            print_new_addresses(&owner, account.as_deref(), "Address:    ", "Owner key:  ")?;
1143            if shell::verbosity() > 0 {
1144                sh_status!("Public key: {}", hex::encode_prefixed(wallet.public_key()))?;
1145            }
1146            // The machine-readable stdout record duplicates the prose above when stdout is an
1147            // interactive terminal.
1148            if !shell::is_out_tty() {
1149                match &account {
1150                    Some(account) => sh_println!("{account}\t{owner}")?,
1151                    None => sh_println!("{owner}")?,
1152                }
1153            }
1154        }
1155    }
1156    Ok(json_values)
1157}
1158
1159/// Generates `number` random keypairs, returning their JSON records in JSON mode.
1160///
1161/// With `configurable`, each key is the only owner of a Tempo configurable account, whose address
1162/// leads the record.
1163fn new_keypairs(number: u32, configurable: bool) -> Result<Vec<Value>> {
1164    let mut rng = thread_rng();
1165    let mut json_values = Vec::new();
1166    for _ in 0..number {
1167        let wallet = PrivateKeySigner::random_with(&mut rng);
1168        let owner = wallet.address().to_checksum(None);
1169        let account = new_account(wallet.address(), configurable)?;
1170        let private_key = hex::encode_prefixed(wallet.to_bytes());
1171        if shell::is_json() {
1172            let mut result = json!({
1173                "address": account.as_deref().unwrap_or(&owner),
1174                "public_key": hex::encode_prefixed(wallet.public_key()),
1175                "private_key": private_key,
1176            });
1177            if account.is_some() {
1178                result["owner"] = json!(owner);
1179            }
1180            json_values.push(result);
1181        } else {
1182            if account.is_some() {
1183                sh_status!("Successfully created new Tempo configurable account.")?;
1184            } else {
1185                sh_status!("Successfully created new keypair.")?;
1186            }
1187            print_new_addresses(&owner, account.as_deref(), "Address:     ", "Owner key:   ")?;
1188            if shell::verbosity() > 0 {
1189                sh_status!("Public key:  {}", hex::encode_prefixed(wallet.public_key()))?;
1190            }
1191            sh_status!("Private key: {private_key}")?;
1192            // The machine-readable stdout record duplicates the prose above when stdout is an
1193            // interactive terminal. A configurable account appends its owner key's address.
1194            if !shell::is_out_tty() {
1195                match &account {
1196                    Some(account) => sh_println!("{account}\t{private_key}\t{owner}")?,
1197                    None => sh_println!("{owner}\t{private_key}")?,
1198                }
1199            }
1200        }
1201    }
1202    Ok(json_values)
1203}
1204
1205/// Returns the checksummed address of the configurable account that `owner` alone controls when
1206/// `configurable` is set.
1207fn new_account(owner: Address, configurable: bool) -> Result<Option<String>> {
1208    configurable
1209        .then(|| {
1210            Ok(foundry_common::tempo::configurable_account::single_owner_account(owner)?
1211                .to_checksum(None))
1212        })
1213        .transpose()
1214}
1215
1216/// Prints the address of a new wallet: the account and its owner key for a configurable account.
1217fn print_new_addresses(
1218    owner: &str,
1219    account: Option<&str>,
1220    address_label: &str,
1221    owner_label: &str,
1222) -> Result<()> {
1223    match account {
1224        Some(account) => {
1225            sh_status!("{address_label}{account}")?;
1226            sh_status!("{owner_label}{owner}")?;
1227        }
1228        None => sh_status!("{address_label}{owner}")?,
1229    }
1230    Ok(())
1231}
1232
1233fn raw_wallet(raw: RawWalletOpts) -> WalletOpts {
1234    WalletOpts { raw, ..Default::default() }
1235}
1236
1237/// Parses EIP-712 typed data from a JSON string, or from the file it names when `from_file`.
1238fn parse_typed_data(message: &str, from_file: bool) -> Result<TypedData> {
1239    if from_file { Ok(fs::read_json_file(Path::new(message))?) } else { Ok(parse_json(message)?) }
1240}
1241
1242/// Strips the 0x prefix from a hex string and decodes it to bytes.
1243///
1244/// Treats the string as raw bytes if it doesn't start with 0x.
1245fn hex_str_to_bytes(s: &str) -> Result<Vec<u8>> {
1246    Ok(match s.strip_prefix("0x") {
1247        Some(data) => hex::decode(data).wrap_err("Could not decode 0x-prefixed string.")?,
1248        None => s.as_bytes().to_vec(),
1249    })
1250}
1251
1252/// Returns `password` when given, otherwise prompts for it on the terminal.
1253fn password_or_prompt(password: Option<String>, prompt: &str) -> Result<String> {
1254    match password {
1255        Some(password) => Ok(password),
1256        None => Ok(rpassword::prompt_password(prompt)?),
1257    }
1258}
1259
1260/// Resolves the directory for `cast wallet new`.
1261///
1262/// A bare name that does not exist relative to the current directory is rewritten into
1263/// `account_name` and stored in the default keystore directory, matching
1264/// `cast wallet import <name>`. Path-like values and probe failures other than `NotFound` still
1265/// error.
1266fn resolve_new_dir(path: String, account_name: &mut Option<String>) -> Result<PathBuf> {
1267    // Probe the relative path instead of canonicalizing it: canonicalization also resolves the
1268    // current directory, which fails with `EPERM`/`EACCES` when one of its ancestors is not
1269    // accessible (e.g. macOS privacy-protected folders).
1270    if account_name.is_none()
1271        && is_bare_account_name(&path)
1272        && matches!(Path::new(&path).try_exists(), Ok(false))
1273    {
1274        *account_name = Some(path);
1275        let dir = resolve_keystore_dir(None)?;
1276        fs::create_dir_all(&dir)?;
1277        return Ok(dir);
1278    }
1279
1280    match canonicalize_path(&path) {
1281        Ok(dir) if dir.is_dir() => Ok(dir),
1282        Ok(dir) => eyre::bail!("`{}` is not a directory", dir.display()),
1283        Err(e) => eyre::bail!(
1284            "If you specified a directory, please make sure it exists, or create it before running `cast wallet new <DIR>`.\n{path} is not a directory.\nError: {e}"
1285        ),
1286    }
1287}
1288
1289/// Returns true when `value` is a bare keystore account name rather than a filesystem path.
1290///
1291/// Path-like values (`.`, `..`, anything containing a separator or `:`, including Windows
1292/// prefixes such as `C:foo` and ADS names such as `foo:bar`) stay on the existing
1293/// directory-resolution path for `cast wallet new`.
1294fn is_bare_account_name(value: &str) -> bool {
1295    !value.is_empty()
1296        && value != "."
1297        && value != ".."
1298        && !value.contains('/')
1299        && !value.contains('\\')
1300        // `C:foo` is a drive-relative path; `foo:bar` is an alternate data stream on
1301        // Windows. Joining either can write outside the default keystore directory
1302        // or hide the keystore in a stream so listing/loading miss it.
1303        && !value.contains(':')
1304}
1305
1306/// Resolves the keystore directory, defaulting to `~/.foundry/keystores`.
1307fn resolve_keystore_dir(dir: Option<String>) -> Result<PathBuf> {
1308    match dir {
1309        Some(dir) => Ok(PathBuf::from(dir)),
1310        None => Config::foundry_keystores_dir()
1311            .ok_or_else(|| eyre::eyre!("Could not find the default keystore directory.")),
1312    }
1313}
1314
1315/// Validates `account_name` and resolves its existing keystore file in `dir`.
1316fn existing_keystore_path(account_name: &str, dir: Option<String>) -> Result<PathBuf> {
1317    ensure_account_name_available(account_name)?;
1318    let keystore_path = resolve_keystore_dir(dir)?.join(account_name);
1319    if !keystore_path.exists() {
1320        eyre::bail!("Keystore file does not exist at {}", keystore_path.display());
1321    }
1322    Ok(keystore_path)
1323}
1324
1325fn ensure_touch_id_available(touch_id: bool) -> Result<()> {
1326    if !touch_id {
1327        return Ok(());
1328    }
1329
1330    #[cfg(all(target_os = "macos", feature = "touch-id"))]
1331    {
1332        if !foundry_wallets::touch_id::is_available() {
1333            eyre::bail!("Touch ID is unavailable on this Mac");
1334        }
1335        Ok(())
1336    }
1337
1338    #[cfg(not(all(target_os = "macos", feature = "touch-id")))]
1339    eyre::bail!("`--touch-id` requires macOS and a cast build with the `touch-id` feature");
1340}
1341
1342const TOUCH_ID_SIDECAR_SUFFIX: &str = ".touchid";
1343
1344fn ensure_account_name_available(name: &str) -> Result<()> {
1345    let file_name = Path::new(name).file_name().and_then(|s| s.to_str());
1346    if name.is_empty() || name.contains('\\') || file_name != Some(name) {
1347        eyre::bail!("account name must be a single path segment");
1348    }
1349    for suffix in [TOUCH_ID_SIDECAR_SUFFIX, LINKED_ACCOUNT_SUFFIX] {
1350        if name.ends_with(suffix) {
1351            eyre::bail!("account names ending in `{suffix}` are reserved");
1352        }
1353    }
1354    Ok(())
1355}
1356
1357fn touch_id_sidecar_path(keystore_path: &Path) -> PathBuf {
1358    let mut path = OsString::from(keystore_path.as_os_str());
1359    path.push(TOUCH_ID_SIDECAR_SUFFIX);
1360    path.into()
1361}
1362
1363/// Classification of a file at a `.touchid` path.
1364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1365enum TouchIdSidecarState {
1366    /// No filesystem entry exists at the path.
1367    Missing,
1368    /// The file strictly matches the currently supported Touch ID sidecar schema.
1369    Recognized,
1370    /// The file is an Ethereum keystore.
1371    Keystore,
1372    /// Anything else: malformed JSON, empty object, array, unrelated object,
1373    /// unsupported sidecar version, unknown policy, invalid hex, empty payload,
1374    /// truncated sealed payload, invalid X9.63 prefix, or future sidecar format.
1375    Unknown,
1376}
1377
1378/// The only sidecar version this Cast release understands.
1379const TOUCH_ID_SIDECAR_VERSION: u32 = 1;
1380
1381/// Minimum encoded ciphertext payload:
1382/// 65-byte P-256 X9.63 public key + 12-byte ChaChaPoly nonce + 16-byte tag.
1383///
1384/// The encrypted password itself may be empty, so 93 bytes is the true minimum.
1385const TOUCH_ID_SEALED_PASSWORD_MIN_LEN: usize = 65 + 12 + 16;
1386
1387/// X9.63 prefix for an uncompressed P-256 public key.
1388const TOUCH_ID_X963_UNCOMPRESSED_PREFIX: u8 = 0x04;
1389
1390/// Strict deserialization-only representation of the persisted sidecar format.
1391///
1392/// Uses `deny_unknown_fields` so that any unrecognized field (e.g. from a
1393/// future sidecar version) causes a parse failure, which maps to `Unknown`.
1394///
1395/// This duplicates `foundry_wallets::touch_id` on purpose: that module only exists on macOS
1396/// builds with the `touch-id` feature, while sidecar files must be classified everywhere.
1397#[derive(Debug, serde::Deserialize)]
1398#[serde(deny_unknown_fields)]
1399struct TouchIdSidecarWire {
1400    version: u32,
1401    policy: TouchIdPolicyWire,
1402    se_key: String,
1403    sealed_password: String,
1404}
1405
1406impl TouchIdSidecarWire {
1407    /// Whether this is a supported sidecar with plausible payload bytes: `se_key` is non-empty
1408    /// hex and `sealed_password` is hex of at least 93 bytes starting with 0x04.
1409    fn is_recognized(&self) -> bool {
1410        self.version == TOUCH_ID_SIDECAR_VERSION
1411            && hex::decode(&self.se_key).is_ok_and(|se_key| !se_key.is_empty())
1412            && hex::decode(&self.sealed_password).is_ok_and(|sealed| {
1413                sealed.len() >= TOUCH_ID_SEALED_PASSWORD_MIN_LEN
1414                    && sealed.first() == Some(&TOUCH_ID_X963_UNCOMPRESSED_PREFIX)
1415            })
1416    }
1417}
1418
1419/// The policy values currently recognised by this Cast release.
1420#[derive(Clone, Copy, Debug, serde::Deserialize)]
1421#[serde(rename_all = "kebab-case")]
1422enum TouchIdPolicyWire {
1423    UserPresence,
1424    CurrentBiometry,
1425}
1426
1427impl TouchIdPolicyWire {
1428    const fn as_str(self) -> &'static str {
1429        match self {
1430            Self::UserPresence => "user-presence",
1431            Self::CurrentBiometry => "current-biometry",
1432        }
1433    }
1434}
1435
1436/// Returns the state of the file at `path` with respect to the Touch ID sidecar schema.
1437///
1438/// Classification order:
1439/// 1. Not found → `Missing`
1440/// 2. Has both `version` and `crypto`/`Crypto` fields → `Keystore`
1441/// 3. Parses strictly as a v1 Touch ID sidecar + plausible payload → `Recognized`
1442/// 4. Everything else → `Unknown`
1443fn touch_id_sidecar_state(path: &Path) -> Result<TouchIdSidecarState> {
1444    let value = match fs::read_json_file::<Value>(path) {
1445        Ok(v) => v,
1446        Err(FsPathError::Read { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => {
1447            return Ok(TouchIdSidecarState::Missing);
1448        }
1449        Err(e) => return Err(e.into()),
1450    };
1451
1452    if value.get("version").is_some()
1453        && (value.get("crypto").is_some() || value.get("Crypto").is_some())
1454    {
1455        return Ok(TouchIdSidecarState::Keystore);
1456    }
1457
1458    Ok(match serde_json::from_value::<TouchIdSidecarWire>(value) {
1459        Ok(wire) if wire.is_recognized() => TouchIdSidecarState::Recognized,
1460        _ => TouchIdSidecarState::Unknown,
1461    })
1462}
1463
1464fn touch_id_sidecar_policy(path: &Path) -> Result<TouchIdPolicyWire> {
1465    let value = fs::read_json_file::<Value>(path)?;
1466    let wire = serde_json::from_value::<TouchIdSidecarWire>(value)
1467        .wrap_err_with(|| format!("failed to parse Touch ID sidecar at {}", path.display()))?;
1468    if !wire.is_recognized() {
1469        eyre::bail!("{} is not a recognized Touch ID sidecar", path.display());
1470    }
1471    Ok(wire.policy)
1472}
1473
1474fn is_touch_id_sidecar(path: &Path) -> Result<bool> {
1475    let is_sidecar_name = path
1476        .file_name()
1477        .and_then(|name| name.to_str())
1478        .is_some_and(|name| name.ends_with(TOUCH_ID_SIDECAR_SUFFIX));
1479    Ok(is_sidecar_name && touch_id_sidecar_state(path)? == TouchIdSidecarState::Recognized)
1480}
1481
1482fn ensure_touch_id_sidecar_available(keystore_path: &Path) -> Result<()> {
1483    let sidecar = touch_id_sidecar_path(keystore_path);
1484    match touch_id_sidecar_state(&sidecar)? {
1485        TouchIdSidecarState::Missing | TouchIdSidecarState::Recognized => Ok(()),
1486        TouchIdSidecarState::Keystore => {
1487            eyre::bail!(
1488                "refusing Touch ID enrollment because {} is an existing keystore",
1489                sidecar.display()
1490            );
1491        }
1492        TouchIdSidecarState::Unknown => {
1493            eyre::bail!(
1494                "refusing Touch ID enrollment because {} already exists and is not a recognized Touch ID sidecar",
1495                sidecar.display()
1496            );
1497        }
1498    }
1499}
1500
1501/// Recovers the signer of `message`, interpreted as EIP-712 typed data (`data`), a prehashed
1502/// digest (`no_hash`) or a plain message.
1503fn recover_signer(
1504    message: &str,
1505    signature: &Signature,
1506    data: bool,
1507    from_file: bool,
1508    no_hash: bool,
1509) -> Result<Address> {
1510    Ok(if data {
1511        let typed_data = parse_typed_data(message, from_file)?;
1512        signature.recover_address_from_prehash(&typed_data.eip712_signing_hash()?)?
1513    } else if no_hash {
1514        signature.recover_address_from_prehash(&hex::decode(message)?[..].try_into()?)?
1515    } else {
1516        signature.recover_address_from_msg(hex_str_to_bytes(message)?)?
1517    })
1518}
1519
1520fn indexed_account_name(base: &str, number: u32, index: u32) -> String {
1521    if number == 1 { base.to_string() } else { format!("{base}_{}", index + 1) }
1522}
1523
1524fn remove_touch_id_sidecar(keystore_path: &Path) -> Result<bool> {
1525    let sidecar = touch_id_sidecar_path(keystore_path);
1526    match touch_id_sidecar_state(&sidecar)? {
1527        TouchIdSidecarState::Missing => Ok(false),
1528        TouchIdSidecarState::Recognized => match std::fs::remove_file(&sidecar) {
1529            Ok(()) => Ok(true),
1530            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1531            Err(error) => Err(error).wrap_err_with(|| {
1532                format!("Failed to remove Touch ID sidecar at {}", sidecar.display())
1533            }),
1534        },
1535        TouchIdSidecarState::Keystore => {
1536            eyre::bail!("refusing to remove existing keystore at {}", sidecar.display());
1537        }
1538        TouchIdSidecarState::Unknown => {
1539            eyre::bail!(
1540                "refusing to remove {} because it is not a recognized Touch ID sidecar",
1541                sidecar.display()
1542            );
1543        }
1544    }
1545}
1546
1547/// Enrolls a freshly written keystore for Touch ID with the default policy.
1548///
1549/// `completed_action` describes the keystore write that already succeeded; `index` is the
1550/// keystore's position in a `cast wallet new --number` batch.
1551#[cfg(all(target_os = "macos", feature = "touch-id"))]
1552fn enroll_new_keystore(
1553    keystore_path: &Path,
1554    password: &str,
1555    completed_action: &str,
1556    index: usize,
1557) -> Result<()> {
1558    ensure_touch_id_sidecar_available(keystore_path).map_err(|e| {
1559        eyre::eyre!(
1560            "{completed_action}, but Touch ID enrollment preflight failed: {e}. The sidecar was left untouched and must be resolved manually before password-prompt fallback is reliable"
1561        )
1562    })?;
1563    foundry_wallets::touch_id::enroll(
1564        keystore_path,
1565        password,
1566        foundry_wallets::touch_id::Policy::default(),
1567    )
1568    .map_err(|error| {
1569        let note = if index == 0 { "" } else { " (earlier batch keystores were not rolled back)" };
1570        touch_id_enrollment_failure(keystore_path, &format!("{completed_action}{note}"), error)
1571    })
1572}
1573
1574/// Unreachable in practice: [`ensure_touch_id_available`] rejects `--touch-id` on this platform.
1575#[cfg(not(all(target_os = "macos", feature = "touch-id")))]
1576const fn enroll_new_keystore(_: &Path, _: &str, _: &str, _: usize) -> Result<()> {
1577    Ok(())
1578}
1579
1580#[cfg(all(target_os = "macos", feature = "touch-id"))]
1581fn touch_id_enrollment_failure(
1582    keystore_path: &Path,
1583    completed_action: &str,
1584    enrollment_error: impl std::fmt::Display,
1585) -> eyre::Report {
1586    match remove_touch_id_sidecar(keystore_path) {
1587        Ok(true) => eyre::eyre!(
1588            "{completed_action}, but Touch ID enrollment failed: {enrollment_error}. The stale Touch ID sidecar was removed; password-prompt fallback remains available"
1589        ),
1590        Ok(false) => eyre::eyre!(
1591            "{completed_action}, but Touch ID enrollment failed: {enrollment_error}. No stale Touch ID sidecar remained; password-prompt fallback remains available"
1592        ),
1593        Err(cleanup_error) => eyre::eyre!(
1594            "{completed_action}, but Touch ID enrollment failed: {enrollment_error}. The stale sidecar could not be removed: {cleanup_error}. Remove {} manually before password-prompt fallback is possible",
1595            touch_id_sidecar_path(keystore_path).display()
1596        ),
1597    }
1598}
1599
1600#[cfg(test)]
1601mod tests {
1602    use super::*;
1603    use alloy_primitives::address;
1604
1605    fn sidecar_json(version: u32, policy: &str, se_key: &str, sealed_password: &str) -> String {
1606        json!({
1607            "version": version,
1608            "policy": policy,
1609            "se_key": se_key,
1610            "sealed_password": sealed_password,
1611        })
1612        .to_string()
1613    }
1614
1615    fn sealed_password(prefix: &str, len: usize) -> String {
1616        format!("{prefix}{}", "00".repeat(len - 1))
1617    }
1618
1619    #[test]
1620    fn recovers_signer_for_each_message_kind() {
1621        let address = address!("0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf"); // private key = 1
1622
1623        let prehash = alloy_primitives::keccak256("hello");
1624        let signature = Signature::from_str("433ec3d37e4f1253df15e2dea412fed8e915737730f74b3dfb1353268f932ef5557c9158e0b34bce39de28d11797b42e9b1acb2749230885fe075aedc3e491a41b").unwrap();
1625        assert_eq!(
1626            recover_signer(&hex::encode(prehash), &signature, false, false, true).unwrap(),
1627            address
1628        );
1629
1630        let typed_data = r#"{"domain":{"name":"Test","version":"1","chainId":1,"verifyingContract":"0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"},"message":{"value":123},"primaryType":"Data","types":{"Data":[{"name":"value","type":"uint256"}]}}"#;
1631        let signature = Signature::from_str("0285ff83b93bd01c14e201943af7454fe2bc6c98be707a73888c397d6ae3b0b92f73ca559f81cbb19fe4e0f1dc4105bd7b647c6a84b033057977cf2ec982daf71b").unwrap();
1632        assert_eq!(recover_signer(typed_data, &signature, true, false, false).unwrap(), address);
1633    }
1634
1635    #[test]
1636    fn new_keystores_preflight_every_touch_id_sidecar() {
1637        let dir = tempfile::tempdir().unwrap();
1638        let sidecar = dir.path().join("batch_2.touchid");
1639        std::fs::write(&sidecar, r#"{"version":3,"crypto":{}}"#).unwrap();
1640
1641        let error =
1642            new_keystores(dir.path(), Some("batch"), Some("pw".into()), 2, false, true, false)
1643                .unwrap_err();
1644        assert_eq!(
1645            error.to_string(),
1646            format!(
1647                "refusing Touch ID enrollment because {} is an existing keystore",
1648                sidecar.display()
1649            )
1650        );
1651        assert!(!dir.path().join("batch_1").exists());
1652    }
1653
1654    #[test]
1655    fn classifies_touch_id_sidecars() {
1656        use TouchIdSidecarState::*;
1657
1658        let valid_sealed = sealed_password("04", TOUCH_ID_SEALED_PASSWORD_MIN_LEN);
1659        let cases = [
1660            (None, Missing),
1661            (Some(sidecar_json(1, "user-presence", "aa", &valid_sealed)), Recognized),
1662            (Some(sidecar_json(1, "current-biometry", "aa", &valid_sealed)), Recognized),
1663            (Some(r#"{"version":3,"crypto":{}}"#.to_string()), Keystore),
1664            (Some(r#"{"version":3,"Crypto":{}}"#.to_string()), Keystore),
1665            (Some("{}".to_string()), Unknown),
1666            (Some("[]".to_string()), Unknown),
1667            (Some(r#"{"application":"unrelated"}"#.to_string()), Unknown),
1668            // unsupported version
1669            (Some(sidecar_json(2, "user-presence", "aa", &valid_sealed)), Unknown),
1670            // unknown field is rejected by `deny_unknown_fields`
1671            (
1672                Some(
1673                    json!({
1674                        "version": 1,
1675                        "policy": "user-presence",
1676                        "se_key": "aa",
1677                        "sealed_password": valid_sealed,
1678                        "future_field": true
1679                    })
1680                    .to_string(),
1681                ),
1682                Unknown,
1683            ),
1684            (Some(sidecar_json(1, "future-policy", "aa", &valid_sealed)), Unknown),
1685            // invalid payloads
1686            (Some(sidecar_json(1, "user-presence", "", &valid_sealed)), Unknown),
1687            (Some(sidecar_json(1, "user-presence", "zz", &valid_sealed)), Unknown),
1688            (Some(sidecar_json(1, "user-presence", "aa", "")), Unknown),
1689            (Some(sidecar_json(1, "user-presence", "aa", "zz")), Unknown),
1690            (
1691                Some(sidecar_json(
1692                    1,
1693                    "user-presence",
1694                    "aa",
1695                    &sealed_password("04", TOUCH_ID_SEALED_PASSWORD_MIN_LEN - 1),
1696                )),
1697                Unknown,
1698            ),
1699            (
1700                Some(sidecar_json(
1701                    1,
1702                    "user-presence",
1703                    "aa",
1704                    &sealed_password("03", TOUCH_ID_SEALED_PASSWORD_MIN_LEN),
1705                )),
1706                Unknown,
1707            ),
1708        ];
1709
1710        for (content, expected) in cases {
1711            let dir = tempfile::tempdir().unwrap();
1712            let keystore = dir.path().join("account");
1713            let sidecar = touch_id_sidecar_path(&keystore);
1714            if let Some(content) = &content {
1715                std::fs::write(&sidecar, content).unwrap();
1716            }
1717
1718            assert_eq!(touch_id_sidecar_state(&sidecar).unwrap(), expected, "{content:?}");
1719            assert_eq!(is_touch_id_sidecar(&sidecar).unwrap(), expected == Recognized);
1720
1721            // Enrollment preflight and removal only ever touch recognized sidecars.
1722            let preflight = ensure_touch_id_sidecar_available(&keystore);
1723            let removal = remove_touch_id_sidecar(&keystore);
1724            match expected {
1725                Missing => {
1726                    preflight.unwrap();
1727                    assert!(!removal.unwrap());
1728                }
1729                Recognized => {
1730                    preflight.unwrap();
1731                    assert!(removal.unwrap());
1732                    assert!(!sidecar.exists());
1733                }
1734                Keystore => {
1735                    let err = preflight.unwrap_err().to_string();
1736                    assert!(err.contains("is an existing keystore"), "{err}");
1737                    let err = removal.unwrap_err().to_string();
1738                    assert!(err.contains("refusing to remove existing keystore"), "{err}");
1739                }
1740                Unknown => {
1741                    for err in [preflight.unwrap_err(), removal.unwrap_err()] {
1742                        let err = err.to_string();
1743                        assert!(err.contains("is not a recognized Touch ID sidecar"), "{err}");
1744                    }
1745                }
1746            }
1747            if expected != Recognized {
1748                assert_eq!(
1749                    std::fs::read_to_string(&sidecar).ok(),
1750                    content,
1751                    "file must be untouched"
1752                );
1753            }
1754        }
1755    }
1756
1757    #[test]
1758    fn malformed_json_propagates_error() {
1759        let dir = tempfile::tempdir().unwrap();
1760        let sidecar = dir.path().join("account.touchid");
1761        std::fs::write(&sidecar, "not json").unwrap();
1762        // Malformed JSON is an I/O/parse error, not Unknown.
1763        assert!(is_touch_id_sidecar(&sidecar).is_err());
1764        assert!(touch_id_sidecar_state(&sidecar).is_err());
1765    }
1766
1767    #[test]
1768    fn wallet_sign_auth_nonce_and_self_broadcast_conflict() {
1769        let result = WalletSubcommands::try_parse_from([
1770            "foundry-cli",
1771            "sign-auth",
1772            "0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF",
1773            "--nonce",
1774            "42",
1775            "--self-broadcast",
1776        ]);
1777        assert!(
1778            result.is_err(),
1779            "expected error when both --nonce and --self-broadcast are provided"
1780        );
1781    }
1782
1783    #[test]
1784    fn rejects_path_keystore_account_name() {
1785        assert!(ensure_account_name_available("dev").is_ok());
1786        assert!(ensure_account_name_available("testAccount").is_ok());
1787        for invalid in ["../pwned", "nested/alias", "foo/../bar", "..", ".", "", "foo\\bar"] {
1788            assert!(ensure_account_name_available(invalid).is_err(), "{invalid:?}");
1789        }
1790    }
1791
1792    #[test]
1793    fn can_parse_wallet_new_bare_account_name() {
1794        let args = WalletSubcommands::parse_from(["foundry-cli", "new", "my-wallet"]);
1795        match args {
1796            WalletSubcommands::New { path, account_name, .. } => {
1797                assert_eq!(path.as_deref(), Some("my-wallet"));
1798                assert_eq!(account_name, None);
1799            }
1800            _ => panic!("expected WalletSubcommands::New"),
1801        }
1802    }
1803
1804    #[test]
1805    fn bare_account_name_heuristic() {
1806        assert!(is_bare_account_name("my-wallet"));
1807        assert!(is_bare_account_name("dev"));
1808        assert!(!is_bare_account_name(""));
1809        assert!(!is_bare_account_name("."));
1810        assert!(!is_bare_account_name(".."));
1811        assert!(!is_bare_account_name("./missing-dir"));
1812        assert!(!is_bare_account_name("missing-dir/"));
1813        assert!(!is_bare_account_name("/tmp/keystores"));
1814        assert!(!is_bare_account_name(r"C:\keystores"));
1815        assert!(!is_bare_account_name("C:foo"));
1816        assert!(!is_bare_account_name("foo:bar"));
1817    }
1818}