rusk-wallet 0.3.0

A library providing functionalities to create wallets compatible with Dusk
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use std::fmt::Display;
use std::path::PathBuf;
use std::str::FromStr;
use std::{io::stdout, println};

use crossterm::{
    ExecutableCommand,
    cursor::{Hide, Show},
};

use anyhow::Result;
use bip39::{ErrorKind, Language, Mnemonic};

use inquire::error::InquireResult;
use inquire::ui::{RenderConfig, Styled};
use inquire::validator::Validation;
use inquire::{
    Confirm, CustomType, CustomUserError, InquireError, Password,
    PasswordDisplayMode, Select, Text,
};
use rusk_wallet::dat::version_without_pre_higher;
use rusk_wallet::{
    Address, Error, MAX_CONVERTIBLE, MIN_CONVERTIBLE,
    currency::{Dusk, Lux},
    dat::FileVersion as DatFileVersion,
    gas::{self, MempoolGasPrices},
};
use rusk_wallet::{PBKDF2_ROUNDS, SALT_SIZE};
use sha2::{Digest, Sha256};
use zeroize::Zeroize;

use crate::command::TransactionHistory;

pub(crate) trait Prompt {
    /// Prompt the user to enter a password
    fn create_new_password(&self) -> InquireResult<String> {
        create_new_password()
    }

    /// Prompt the user to enter text
    fn prompt_text(&self, text_prompt: Text) -> InquireResult<String> {
        text_prompt.prompt()
    }
}

pub(crate) struct Prompter;

impl Prompt for Prompter {}

pub(crate) const GO_BACK_HELP: &str = "esc to go back";
pub(crate) const EXIT_HELP: &str = "ctrl+c to exit";
pub(crate) const MOVE_HELP: &str = "↑↓ to move";
pub(crate) const SELECT_HELP: &str = "enter to select";
pub(crate) const FILTER_HELP: &str = "type to filter";

pub(crate) fn ask_pwd(msg: &str) -> Result<String, InquireError> {
    Password::new(msg)
        .with_display_toggle_enabled()
        .without_confirmation()
        .with_display_mode(PasswordDisplayMode::Masked)
        .with_help_message(&[GO_BACK_HELP, EXIT_HELP].join(", "))
        .prompt()
}

pub(crate) fn create_new_password() -> Result<String, InquireError> {
    Password::new("Password:")
        .with_display_toggle_enabled()
        .with_display_mode(PasswordDisplayMode::Hidden)
        .with_custom_confirmation_message("Confirm password: ")
        .with_custom_confirmation_error_message("The passwords doesn't match")
        .with_help_message(&[GO_BACK_HELP, EXIT_HELP].join(", "))
        .prompt()
}

/// Request the user to authenticate with a password and return the derived key
pub(crate) fn derive_key_from_password(
    msg: &str,
    password: &Option<String>,
    salt: Option<&[u8; SALT_SIZE]>,
    file_version: DatFileVersion,
) -> anyhow::Result<Vec<u8>> {
    let mut pwd = match password.as_ref() {
        Some(p) => p.to_string(),

        None => ask_pwd(msg)?,
    };

    let key = derive_key(file_version, &pwd, salt);
    pwd.zeroize();
    key
}

/// Request the user to create a wallet password and return the derived key
pub(crate) fn derive_key_from_new_password(
    password: &Option<String>,
    salt: Option<&[u8; SALT_SIZE]>,
    file_version: DatFileVersion,
    prompter: &dyn Prompt,
) -> anyhow::Result<Vec<u8>> {
    let mut pwd = match password.as_ref() {
        Some(p) => p.to_string(),
        None => prompter.create_new_password()?,
    };

    let key = derive_key(file_version, &pwd, salt);
    pwd.zeroize();
    key
}

/// Display the mnemonic phrase to the user and ask for confirmation
pub(crate) fn confirm_mnemonic_phrase<S>(phrase: &S) -> anyhow::Result<()>
where
    S: std::fmt::Display,
{
    // inform the user about the mnemonic phrase
    let msg = format!(
        "The following phrase is essential for you to regain access to your wallet\nin case you lose access to this computer. Please print it or write it down and store it somewhere safe.\n> {} \nHave you backed up this phrase?",
        phrase
    );

    // let the user confirm they have backed up their phrase
    let confirm = Confirm::new(&msg)
        .with_help_message(
            "It is important you backup the mnemonic phrase before proceeding",
        )
        .prompt()?;

    if !confirm {
        confirm_mnemonic_phrase(phrase)?
    }

    Ok(())
}

/// Request the user to input the mnemonic phrase
pub(crate) fn request_mnemonic_phrase(
    prompter: &dyn Prompt,
) -> anyhow::Result<String> {
    // let the user input the mnemonic phrase
    let mut attempt = 1;
    loop {
        let phrase = prompter.prompt_text(
            Text::new("Please enter the mnemonic phrase: ")
                .with_help_message(&[GO_BACK_HELP, EXIT_HELP].join(", ")),
        )?;

        match Mnemonic::from_phrase(&phrase, Language::English) {
            Ok(phrase) => break Ok(phrase.to_string()),

            Err(err) if attempt > 2 => match err.downcast_ref::<ErrorKind>() {
                Some(ErrorKind::InvalidWord) => {
                    Err(Error::AttemptsExhausted)?;
                }
                _ => return Err(err),
            },
            Err(_) => {
                println!("Invalid mnemonic phrase, please try again");
                attempt += 1;
            }
        }
    }
}

pub(crate) fn derive_key(
    file_version: DatFileVersion,
    pwd: &str,
    salt: Option<&[u8; SALT_SIZE]>,
) -> anyhow::Result<Vec<u8>> {
    match file_version {
        DatFileVersion::RuskBinaryFileFormat(version) => {
            if version_without_pre_higher(version) >= (0, 0, 2, 0) {
                let salt = salt
                    .ok_or_else(|| anyhow::anyhow!("Couldn't find the salt"))?;
                Ok(pbkdf2::pbkdf2_hmac_array::<Sha256, SALT_SIZE>(
                    pwd.as_bytes(),
                    salt,
                    PBKDF2_ROUNDS,
                )
                .to_vec())
            } else {
                let mut hasher = Sha256::new();
                hasher.update(pwd.as_bytes());
                Ok(hasher.finalize().to_vec())
            }
        }
        _ => Ok(blake3::hash(pwd.as_bytes()).as_bytes().to_vec()),
    }
}

/// Request a directory
pub(crate) fn request_dir(
    what_for: &str,
    profile: PathBuf,
) -> Result<std::path::PathBuf> {
    let validator = |dir: &str| {
        let path = PathBuf::from(dir);

        if path.is_dir() {
            Ok(Validation::Valid)
        } else {
            Ok(Validation::Invalid("Not a valid directory".into()))
        }
    };

    let msg = format!("Please enter a directory to {}:", what_for);
    let q = match profile.to_str() {
        Some(p) => Text::new(msg.as_str())
            .with_default(p)
            .with_validator(validator)
            .prompt(),
        None => Text::new(msg.as_str()).with_validator(validator).prompt(),
    }?;

    let p = PathBuf::from(q);

    Ok(p)
}

/// Asks the user for confirmation
pub(crate) fn ask_confirm() -> anyhow::Result<bool> {
    Ok(Confirm::new("Transaction ready. Proceed?")
        .with_default(true)
        .prompt()?)
}

/// Asks the user for confirmation before deleting cache
pub(crate) fn ask_confirm_erase_cache(msg: &str) -> anyhow::Result<bool> {
    Ok(Confirm::new(msg).prompt()?)
}

/// Request a receiver address
pub(crate) fn request_rcvr_addr(addr_for: &str) -> anyhow::Result<Address> {
    // let the user input the receiver address
    Ok(Address::from_str(
        &Text::new(format!("Please enter the {} address:", addr_for).as_str())
            .with_validator(|addr: &str| {
                if Address::from_str(addr).is_ok() {
                    Ok(Validation::Valid)
                } else {
                    Ok(Validation::Invalid(
                        "Please introduce a valid DUSK address".into(),
                    ))
                }
            })
            .prompt()?,
    )?)
}

/// Request an amount of token larger than a given min.
fn request_token(
    action: &str,
    min: Dusk,
    balance: Dusk,
    default: Option<f64>,
) -> anyhow::Result<Dusk> {
    // Checks if the value is larger than the given min and smaller than the
    // min of the balance and `MAX_CONVERTIBLE`.
    let validator = move |value: &f64| {
        let max = std::cmp::min(balance, MAX_CONVERTIBLE);

        match (min..=max).contains(&Dusk::try_from(*value)?) {
            true => Ok(Validation::Valid),
            false => Ok(Validation::Invalid(
                format!("The amount has to be between {} and {}", min, max)
                    .into(),
            )),
        }
    };

    let msg = format!("Introduce dusk amount for {}:", action);

    let amount_prompt: CustomType<f64> = CustomType {
        message: &msg,
        starting_input: None,
        formatter: &|i| format!("{} DUSK", i),
        default_value_formatter: &|i| format!("{} DUSK", i),
        default,
        validators: vec![Box::new(validator)],
        placeholder: Some("123.45"),
        error_message: "Please type a valid number.".into(),
        help_message: "The number should use a dot as the decimal separator."
            .into(),
        parser: &|i| match i.parse::<f64>() {
            Ok(val) => Ok(val),
            Err(_) => Err(()),
        },
        render_config: RenderConfig::default(),
    };

    let amount: Dusk = amount_prompt.prompt()?.try_into()?;
    Ok(amount)
}

/// Request a positive amount of tokens
pub(crate) fn request_token_amt(
    action: &str,
    balance: Dusk,
) -> anyhow::Result<Dusk> {
    let min = MIN_CONVERTIBLE;

    request_token(action, min, balance, None)
}

/// Request positive amount of tokens with a default
pub(crate) fn request_token_amt_with_default(
    action: &str,
    balance: Dusk,
    default: Dusk,
) -> anyhow::Result<Dusk> {
    let min = MIN_CONVERTIBLE;

    request_token(action, min, balance, Some(default.into()))
}

/// Request amount of tokens that can be 0
pub(crate) fn request_optional_token_amt(
    action: &str,
    balance: Dusk,
) -> anyhow::Result<Dusk> {
    let min = Dusk::from(0);

    request_token(action, min, balance, None)
}

/// Request amount of tokens that can't be lower than the `min` argument and
/// higher than `balance`
pub(crate) fn request_stake_token_amt(
    balance: Dusk,
    min: Dusk,
) -> anyhow::Result<Dusk> {
    request_token("stake", min, balance, None)
}

/// Request gas limit
pub(crate) fn request_gas_limit(default_gas_limit: u64) -> anyhow::Result<u64> {
    Ok(
        CustomType::<u64>::new("Introduce the gas limit for this transaction:")
            .with_default(default_gas_limit)
            .with_validator(|n: &u64| {
                if *n < gas::MIN_LIMIT {
                    Ok(Validation::Invalid("Gas limit too low".into()))
                } else {
                    Ok(Validation::Valid)
                }
            })
            .prompt()?,
    )
}

/// Request gas price
pub(crate) fn request_gas_price(
    min_gas_price: Lux,
    mempool_gas_prices: MempoolGasPrices,
) -> anyhow::Result<Lux> {
    let default_gas_price = if mempool_gas_prices.average > min_gas_price {
        mempool_gas_prices.average
    } else {
        min_gas_price
    };

    Ok(
        CustomType::<u64>::new("Introduce the gas price for this transaction:")
            .with_default(default_gas_price)
            .with_formatter(&|val| format!("{} LUX", val))
            .prompt()?,
    )
}

pub(crate) fn request_init_args() -> anyhow::Result<Vec<u8>> {
    const MAX_INIT_SIZE: usize = 32 * 1024;
    let init = Text::new("Introduce init args:")
        .with_help_message("Hex encoded rkyv serialized data")
        .with_validator(move |input: &str| {
            let error = match hex::decode(input) {
                Ok(data) => data.len().gt(&MAX_INIT_SIZE).then_some(format!(
                    "Input exceeds the maximum size of {MAX_INIT_SIZE} bytes",
                )),
                Err(_) => Some("Data must be a valid hex".into()),
            };
            Ok(error.map_or(Validation::Valid, |error| {
                Validation::Invalid(error.into())
            }))
        })
        .prompt()?;
    let init = hex::decode(init).map_err(|e| {
        anyhow::anyhow!("Expecting hex, this should be a bug: {e}")
    })?;

    Ok(init)
}

pub(crate) fn request_str(
    name: &str,
    max_length: usize,
) -> anyhow::Result<String> {
    Ok(
        Text::new(format!("Introduce string for {}:", name).as_str())
            .with_validator(move |input: &str| {
                if input.len() > max_length {
                    Ok(Validation::Invalid(
                        format!(
                            "Input exceeds the maximum length of {} characters",
                            max_length
                        )
                        .into(),
                    ))
                } else {
                    Ok(Validation::Valid)
                }
            })
            .prompt()?,
    )
}

pub enum TransactionModel {
    Shielded,
    Public,
}

impl Display for TransactionModel {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            TransactionModel::Shielded => write!(f, "Shielded"),
            TransactionModel::Public => write!(f, "Public"),
        }
    }
}

/// Request transaction model to use
pub(crate) fn request_transaction_model() -> anyhow::Result<TransactionModel> {
    let choices = vec![TransactionModel::Shielded, TransactionModel::Public];

    Ok(
        Select::new("Please specify the transaction model to use", choices)
            .prompt()?,
    )
}

/// Request public key to use as stake owner
pub(crate) fn request_owner_key(
    current_idx: u8,
    choices: Vec<Address>,
) -> anyhow::Result<Address> {
    let display_choices = choices
        .iter()
        .enumerate()
        .map(|(idx, val)| (format!("Profile {}: {}", idx + 1, val), val))
        .collect::<Vec<(String, &Address)>>();

    let answer = Select::new(
        "Please select the moonlight address to use as stake owner",
        display_choices.iter().map(|(s, _)| s.clone()).collect(),
    )
    .with_starting_cursor(current_idx as usize)
    .prompt()?;

    let selected_address = display_choices
        .into_iter()
        .find(|(s, _)| s == &answer)
        .map(|(_, addr)| addr.clone())
        .expect("Address should be present");

    Ok(selected_address)
}

pub(crate) fn tx_history_list(
    history: &[TransactionHistory],
) -> anyhow::Result<()> {
    if history.is_empty() {
        println!("No transactions found");
        return Ok(());
    }
    let header = TransactionHistory::header();
    let history_str: Vec<String> =
        history.iter().map(|history| history.to_string()).collect();

    Select::new(header.as_str(), history_str)
        .with_help_message(
            &[MOVE_HELP, FILTER_HELP, GO_BACK_HELP, EXIT_HELP].join(", "),
        )
        .with_render_config(
            RenderConfig::default()
                .with_canceled_prompt_indicator(Styled::new(" ")),
        )
        .prompt()?;

    Ok(())
}

const WASM_PATH_VALIDATOR: fn(&str) -> Result<Validation, CustomUserError> =
    |path_str: &str| {
        let path = PathBuf::from(path_str);
        if path.extension().is_some_and(|ext| ext == "wasm") {
            Ok(Validation::Valid)
        } else {
            Ok(Validation::Invalid("Not a valid WASM path".into()))
        }
    };

/// Request contract WASM file location
pub(crate) fn request_contract_code() -> anyhow::Result<PathBuf> {
    let q = Text::new("Please Enter location of the WASM contract:")
        .with_validator(WASM_PATH_VALIDATOR)
        .prompt()?;

    let p = PathBuf::from(q);

    Ok(p)
}

/// Request contract's driver WASM file location
pub(crate) fn request_driver_code() -> anyhow::Result<PathBuf> {
    let q = Text::new("Please Enter location of the WASM driver:")
        .with_validator(WASM_PATH_VALIDATOR)
        .prompt()?;

    let p = PathBuf::from(q);

    Ok(p)
}

pub(crate) fn request_bytes(name: &str) -> anyhow::Result<Vec<u8>> {
    let byte_string =
        Text::new(format!("Introduce hex bytes for {}:", name).as_str())
            .with_validator(|f: &str| match hex::decode(f) {
                Ok(_) => Ok(Validation::Valid),
                Err(_) => Ok(Validation::Invalid("Invalid hex string".into())),
            })
            .prompt()?;

    let bytes = hex::decode(byte_string)?;

    Ok(bytes)
}

pub(crate) fn request_nonce() -> anyhow::Result<u64> {
    let nonce_string =
        Text::new("Introduce a number for Contract Deployment nonce:")
            .with_validator(|f: &str| match u64::from_str(f) {
                Ok(_) => Ok(Validation::Valid),
                Err(_) => Ok(Validation::Invalid("Invalid u64 nonce".into())),
            })
            .prompt()?;

    let bytes = u64::from_str(&nonce_string)?;

    Ok(bytes)
}

/// Request Dusk block explorer to be opened
pub(crate) fn launch_explorer(url: String) -> Result<()> {
    if Confirm::new("Launch block explorer?").prompt()? {
        open::that(url)?;
    }

    Ok(())
}

/// Shows the terminal cursor
pub(crate) fn show_cursor() -> anyhow::Result<()> {
    let mut stdout = stdout();
    stdout.execute(Show)?;
    Ok(())
}

/// Hides the terminal cursor
pub(crate) fn hide_cursor() -> anyhow::Result<()> {
    let mut stdout = stdout();
    stdout.execute(Hide)?;
    Ok(())
}