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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use anyhow::{anyhow, bail, Context, Ok, Result};
use eth_keystore::EthKeystore;
use forc_tracing::println_warning;
use fuels::accounts::wallet::DEFAULT_DERIVATION_PATH_PREFIX;
use home::home_dir;
use std::{
    fs,
    io::{BufRead, Read, Write},
    path::{Path, PathBuf},
};

/// The user's fuel directory (stores state related to fuel-core, wallet, etc).
pub fn user_fuel_dir() -> PathBuf {
    const USER_FUEL_DIR: &str = ".fuel";
    let home_dir = home_dir().expect("failed to retrieve user home directory");
    home_dir.join(USER_FUEL_DIR)
}

/// The directory under which `forc wallet` generates wallets.
pub fn user_fuel_wallets_dir() -> PathBuf {
    const WALLETS_DIR: &str = "wallets";
    user_fuel_dir().join(WALLETS_DIR)
}

/// The directory used to cache wallet account addresses.
pub fn user_fuel_wallets_accounts_dir() -> PathBuf {
    const ACCOUNTS_DIR: &str = "accounts";
    user_fuel_wallets_dir().join(ACCOUNTS_DIR)
}

/// Returns default wallet path which is `$HOME/.fuel/wallets/.wallet`.
pub fn default_wallet_path() -> PathBuf {
    const DEFAULT_WALLET_FILE_NAME: &str = ".wallet";
    user_fuel_wallets_dir().join(DEFAULT_WALLET_FILE_NAME)
}

/// Load a wallet from the given path.
pub fn load_wallet(wallet_path: &Path) -> Result<EthKeystore> {
    let file = fs::File::open(wallet_path).map_err(|e| {
        anyhow!(
            "Failed to load a wallet from {wallet_path:?}: {e}.\n\
            Please be sure to initialize a wallet before creating an account.\n\
            To initialize a wallet, use `forc-wallet new`"
        )
    })?;
    let reader = std::io::BufReader::new(file);
    serde_json::from_reader(reader).map_err(|e| {
        anyhow!(
            "Failed to deserialize keystore from {wallet_path:?}: {e}.\n\
            Please ensure that {wallet_path:?} is a valid wallet file."
        )
    })
}

pub(crate) fn wait_for_keypress() {
    let mut single_key = [0u8];
    std::io::stdin().read_exact(&mut single_key).unwrap();
}

/// Returns the derivation path with account index using the default derivation path from SDK
pub(crate) fn get_derivation_path(account_index: usize) -> String {
    format!("{DEFAULT_DERIVATION_PATH_PREFIX}/{account_index}'/0/0")
}

pub(crate) fn request_new_password() -> String {
    let password =
        rpassword::prompt_password("Please enter a password to encrypt this private key: ")
            .unwrap();

    let confirmation = rpassword::prompt_password("Please confirm your password: ").unwrap();

    if password != confirmation {
        println_warning("Passwords do not match -- try again!");
        std::process::exit(1);
    }
    password
}

/// Print a string to an alternate screen, so the string isn't printed to the terminal.
pub(crate) fn display_string_discreetly(
    discreet_string: &str,
    continue_message: &str,
) -> Result<()> {
    use termion::screen::IntoAlternateScreen;
    let mut screen = std::io::stdout().into_alternate_screen()?;
    writeln!(screen, "{discreet_string}")?;
    screen.flush()?;
    println!("{continue_message}");
    wait_for_keypress();
    Ok(())
}

/// Encrypts the given mnemonic with the given password and writes it to a file at the given path.
///
/// Ensures that the parent dir exists, but that we're not directly overwriting an existing file.
///
/// The resulting wallet file will be a keystore as per the [Web3 Secret Storage Definition][1].
/// [1]: https://ethereum.org/en/developers/docs/data-structures-and-encoding/web3-secret-storage.
pub(crate) fn write_wallet_from_mnemonic_and_password(
    wallet_path: &Path,
    mnemonic: &str,
    password: &str,
) -> Result<()> {
    // Ensure we're not overwriting an existing wallet or other file.
    // The wallet should have been removed in `ensure_no_wallet_exists`, but we check again to be safe.
    if wallet_path.exists() {
        bail!(
            "File or directory already exists at {wallet_path:?}. \
            Remove the existing file, or provide a different path."
        );
    }

    // Ensure the parent directory exists.
    let wallet_dir = wallet_path
        .parent()
        .ok_or_else(|| anyhow!("failed to retrieve parent directory of {wallet_path:?}"))?;
    std::fs::create_dir_all(wallet_dir)?;

    // Retrieve the wallet file name.
    let wallet_file_name = wallet_path
        .file_name()
        .and_then(|os_str| os_str.to_str())
        .ok_or_else(|| anyhow!("failed to retrieve file name from {wallet_path:?}"))?;

    // Encrypt and write the wallet file.
    eth_keystore::encrypt_key(
        wallet_dir,
        &mut rand::thread_rng(),
        mnemonic,
        password,
        Some(wallet_file_name),
    )
    .with_context(|| format!("failed to create keystore at {wallet_path:?}"))
    .map(|_| ())
}

/// Ensures there is no wallet at the given [Path], removing an existing wallet if the user has
/// provided the `--force` option or chooses to remove it in the CLI interaction.
/// Returns [Err] if there is an existing wallet and the user chooses not to remove it.
pub(crate) fn ensure_no_wallet_exists(
    wallet_path: &Path,
    force: bool,
    mut reader: impl BufRead,
) -> Result<()> {
    if wallet_path.exists() {
        if force {
            println_warning(&format!(
                "Because the `--force` argument was supplied, the wallet at {} will be removed.",
                wallet_path.display(),
            ));
            fs::remove_file(wallet_path).unwrap();
        } else {
            println_warning(&format!(
                "There is an existing wallet at {}. \
                Do you wish to replace it with a new wallet? (y/N) ",
                wallet_path.display(),
            ));
            let mut need_replace = String::new();
            reader.read_line(&mut need_replace).unwrap();
            if need_replace.trim() == "y" {
                fs::remove_file(wallet_path).unwrap();
            } else {
                bail!(
                    "Failed to create a new wallet at {} \
                    because a wallet already exists at that location.",
                    wallet_path.display(),
                );
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::test_utils::{with_tmp_dir, TEST_MNEMONIC, TEST_PASSWORD};
    // simulate input
    const INPUT_NOP: &[u8; 1] = b"\n";
    const INPUT_YES: &[u8; 2] = b"y\n";
    const INPUT_NO: &[u8; 2] = b"n\n";

    fn remove_wallet(wallet_path: &Path) {
        if wallet_path.exists() {
            fs::remove_file(wallet_path).unwrap();
        }
    }
    fn create_wallet(wallet_path: &Path) {
        if !wallet_path.exists() {
            fs::File::create(wallet_path).unwrap();
        }
    }

    #[test]
    fn handle_absolute_path_argument() {
        with_tmp_dir(|tmp_dir| {
            let tmp_dir_abs = tmp_dir.canonicalize().unwrap();
            let wallet_path = tmp_dir_abs.join("wallet.json");
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            load_wallet(&wallet_path).unwrap();
        })
    }

    #[test]
    fn handle_relative_path_argument() {
        let wallet_path = Path::new("test-wallet.json");
        let panic = std::panic::catch_unwind(|| {
            write_wallet_from_mnemonic_and_password(wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            load_wallet(wallet_path).unwrap();
        });
        let _ = std::fs::remove_file(wallet_path);
        if let Err(e) = panic {
            std::panic::resume_unwind(e);
        }
    }

    #[test]
    fn derivation_path() {
        let derivation_path = get_derivation_path(0);
        assert_eq!(derivation_path, "m/44'/1179993420'/0'/0/0");
    }
    #[test]
    fn encrypt_and_save_phrase() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            let phrase_recovered = eth_keystore::decrypt_key(wallet_path, TEST_PASSWORD).unwrap();
            let phrase = String::from_utf8(phrase_recovered).unwrap();
            assert_eq!(phrase, TEST_MNEMONIC)
        });
    }

    #[test]
    fn write_wallet() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            load_wallet(&wallet_path).unwrap();
        })
    }

    #[test]
    #[should_panic]
    fn write_wallet_to_existing_file_should_fail() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
        })
    }

    #[test]
    fn write_wallet_subdir() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("path").join("to").join("wallet");
            write_wallet_from_mnemonic_and_password(&wallet_path, TEST_MNEMONIC, TEST_PASSWORD)
                .unwrap();
            load_wallet(&wallet_path).unwrap();
        })
    }

    #[test]
    fn test_ensure_no_wallet_exists_no_wallet() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            remove_wallet(&wallet_path);
            ensure_no_wallet_exists(&wallet_path, false, &INPUT_NOP[..]).unwrap();
        });
    }

    #[test]
    #[should_panic]
    fn test_ensure_no_wallet_exists_throws_err() {
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            create_wallet(&wallet_path);
            ensure_no_wallet_exists(&wallet_path, false, &INPUT_NO[..]).unwrap();
        });
    }

    #[test]
    fn test_ensure_no_wallet_exists_exists_wallet() {
        // case: wallet path exist without --force and input[yes]
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            create_wallet(&wallet_path);
            ensure_no_wallet_exists(&wallet_path, false, &INPUT_YES[..]).unwrap();
        });
        // case: wallet path exist with --force
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            create_wallet(&wallet_path);
            ensure_no_wallet_exists(&wallet_path, true, &INPUT_NOP[..]).unwrap();
        });
        // case: wallet path exist without --force and supply a different wallet path
        with_tmp_dir(|tmp_dir| {
            let wallet_path = tmp_dir.join("wallet.json");
            create_wallet(&wallet_path);
            let diff_wallet_path = tmp_dir.join("custom-wallet.json");
            ensure_no_wallet_exists(&diff_wallet_path, false, &INPUT_NOP[..]).unwrap();
        });
    }
}

#[cfg(test)]
pub(crate) mod test_utils {
    use super::*;
    use std::{panic, path::Path};

    pub(crate) const TEST_MNEMONIC: &str = "rapid mechanic escape victory bacon switch soda math embrace frozen novel document wait motor thrive ski addict ripple bid magnet horse merge brisk exile";
    pub(crate) const TEST_PASSWORD: &str = "1234";

    /// Create a tmp folder and execute the given test function `f`
    pub(crate) fn with_tmp_dir<F>(f: F)
    where
        F: FnOnce(&Path) + panic::UnwindSafe,
    {
        let tmp_dir_name = format!("forc-wallet-test-{:x}", rand::random::<u64>());
        let tmp_dir = user_fuel_dir().join(".tmp").join(tmp_dir_name);
        std::fs::create_dir_all(&tmp_dir).unwrap();
        let panic = panic::catch_unwind(|| f(&tmp_dir));
        std::fs::remove_dir_all(&tmp_dir).unwrap();
        if let Err(e) = panic {
            panic::resume_unwind(e);
        }
    }

    /// Saves a default test mnemonic to the disk
    pub(crate) fn save_dummy_wallet_file(wallet_path: &Path) {
        write_wallet_from_mnemonic_and_password(wallet_path, TEST_MNEMONIC, TEST_PASSWORD).unwrap();
    }

    /// The same as `with_tmp_dir`, but also provides a test wallet.
    pub(crate) fn with_tmp_dir_and_wallet<F>(f: F)
    where
        F: FnOnce(&Path, &Path) + panic::UnwindSafe,
    {
        with_tmp_dir(|dir| {
            let wallet_path = dir.join("wallet.json");
            save_dummy_wallet_file(&wallet_path);
            f(dir, &wallet_path);
        })
    }
}