From dfcf4b1740b268d8fc167887d610b5949c59733e Mon Sep 17 00:00:00 2001 From: ryan Date: Mon, 19 Feb 2024 05:32:24 -0500 Subject: [PATCH] keyfork-mnemonic-util: reduce amount of generics for validated functions --- crates/keyfork-shard/src/lib.rs | 2 +- crates/keyfork-shard/src/openpgp.rs | 2 +- crates/keyfork/src/cli/recover.rs | 2 +- .../examples/test-basic-prompt.rs | 4 +-- crates/util/keyfork-prompt/src/lib.rs | 15 +++----- crates/util/keyfork-prompt/src/terminal.rs | 34 +++++++++---------- crates/util/keyfork-prompt/src/validators.rs | 30 ++++++++-------- 7 files changed, 43 insertions(+), 46 deletions(-) diff --git a/crates/keyfork-shard/src/lib.rs b/crates/keyfork-shard/src/lib.rs index b98de30..01e01d1 100644 --- a/crates/keyfork-shard/src/lib.rs +++ b/crates/keyfork-shard/src/lib.rs @@ -130,7 +130,7 @@ pub fn remote_decrypt(w: &mut impl Write) -> Result<(), Box( + .prompt_validated_wordlist::( QRCODE_COULDNT_READ, 3, validator.to_fn(), diff --git a/crates/keyfork-shard/src/openpgp.rs b/crates/keyfork-shard/src/openpgp.rs index c364d50..1135265 100644 --- a/crates/keyfork-shard/src/openpgp.rs +++ b/crates/keyfork-shard/src/openpgp.rs @@ -495,7 +495,7 @@ pub fn decrypt( let validator = MnemonicSetValidator { word_lengths: [9, 24], }; - let [nonce_mnemonic, pubkey_mnemonic] = pm.prompt_validated_wordlist::( + let [nonce_mnemonic, pubkey_mnemonic] = pm.prompt_validated_wordlist::( QRCODE_COULDNT_READ, 3, validator.to_fn(), diff --git a/crates/keyfork/src/cli/recover.rs b/crates/keyfork/src/cli/recover.rs index 41184ee..d68a193 100644 --- a/crates/keyfork/src/cli/recover.rs +++ b/crates/keyfork/src/cli/recover.rs @@ -69,7 +69,7 @@ impl RecoverSubcommands { let validator = MnemonicChoiceValidator { word_lengths: [WordLength::Count(12), WordLength::Count(24)], }; - let mnemonic = term.prompt_validated_wordlist::( + let mnemonic = term.prompt_validated_wordlist::( "Mnemonic: ", 3, validator.to_fn(), diff --git a/crates/util/keyfork-prompt/examples/test-basic-prompt.rs b/crates/util/keyfork-prompt/examples/test-basic-prompt.rs index c1f4302..04c7391 100644 --- a/crates/util/keyfork-prompt/examples/test-basic-prompt.rs +++ b/crates/util/keyfork-prompt/examples/test-basic-prompt.rs @@ -18,7 +18,7 @@ fn main() -> Result<(), Box> { word_lengths: [24, 48], }; - let mnemonics = mgr.prompt_validated_wordlist::( + let mnemonics = mgr.prompt_validated_wordlist::( "Enter a 9-word and 24-word mnemonic: ", 3, transport_validator.to_fn(), @@ -26,7 +26,7 @@ fn main() -> Result<(), Box> { assert_eq!(mnemonics[0].as_bytes().len(), 12); assert_eq!(mnemonics[1].as_bytes().len(), 32); - let mnemonics = mgr.prompt_validated_wordlist::( + let mnemonics = mgr.prompt_validated_wordlist::( "Enter a 24 and 48-word mnemonic: ", 3, combine_validator.to_fn(), diff --git a/crates/util/keyfork-prompt/src/lib.rs b/crates/util/keyfork-prompt/src/lib.rs index 9c73e8a..e12597b 100644 --- a/crates/util/keyfork-prompt/src/lib.rs +++ b/crates/util/keyfork-prompt/src/lib.rs @@ -68,15 +68,13 @@ pub trait PromptHandler { /// The method may return an error if the message was not able to be displayed, if the input /// could not be read, or if the parser returned an error. #[cfg(feature = "mnemonic")] - fn prompt_validated_wordlist( + fn prompt_validated_wordlist( &mut self, prompt: &str, retries: u8, - validator_fn: F, + validator_fn: impl Fn(String) -> Result>, ) -> Result where - F: Fn(String) -> Result, - E: std::error::Error, X: Wordlist; /// Prompt the user for a passphrase, which is hidden while typing. @@ -92,15 +90,12 @@ pub trait PromptHandler { /// # Errors /// The method may return an error if the message was not able to be displayed, if the input /// could not be read, or if the parser returned an error. - fn prompt_validated_passphrase( + fn prompt_validated_passphrase( &mut self, prompt: &str, retries: u8, - validator_fn: F, - ) -> Result - where - F: Fn(String) -> Result, - E: std::error::Error; + validator_fn: impl Fn(String) -> Result>, + ) -> Result; /// Prompt the user with a [`Message`]. /// diff --git a/crates/util/keyfork-prompt/src/terminal.rs b/crates/util/keyfork-prompt/src/terminal.rs index 64eb8be..0b5e6bd 100644 --- a/crates/util/keyfork-prompt/src/terminal.rs +++ b/crates/util/keyfork-prompt/src/terminal.rs @@ -1,6 +1,7 @@ use std::{ + borrow::Borrow, io::{stderr, stdin, BufRead, BufReader, Read, Stderr, Stdin, Write}, - os::fd::AsRawFd, borrow::Borrow, + os::fd::AsRawFd, }; use keyfork_crossterm::{ @@ -12,7 +13,7 @@ use keyfork_crossterm::{ ExecutableCommand, QueueableCommand, }; -use crate::{PromptHandler, Message, Wordlist, Error}; +use crate::{Error, Message, PromptHandler, Wordlist}; #[allow(missing_docs)] pub type Result = std::result::Result; @@ -155,11 +156,13 @@ where fn lock(&mut self) -> TerminalGuard<'_, R, W> { TerminalGuard::new(&mut self.read, &mut self.write, &mut self.terminal) } - } -impl PromptHandler for Terminal where R: Read + Sized, W: Write + AsRawFd + Sized { - +impl PromptHandler for Terminal +where + R: Read + Sized, + W: Write + AsRawFd + Sized, +{ fn prompt_input(&mut self, prompt: &str) -> Result { let mut terminal = self.lock().alternate_screen()?; terminal @@ -182,15 +185,13 @@ impl PromptHandler for Terminal where R: Read + Sized, W: Write + As } #[cfg(feature = "mnemonic")] - fn prompt_validated_wordlist( + fn prompt_validated_wordlist( &mut self, prompt: &str, retries: u8, - validator_fn: F, + validator_fn: impl Fn(String) -> Result>, ) -> Result where - F: Fn(String) -> Result, - E: std::error::Error, X: Wordlist, { let mut last_error = None; @@ -214,7 +215,10 @@ impl PromptHandler for Terminal where R: Read + Sized, W: Write + As #[cfg(feature = "mnemonic")] #[allow(clippy::too_many_lines)] - fn prompt_wordlist(&mut self, prompt: &str) -> Result where X: Wordlist { + fn prompt_wordlist(&mut self, prompt: &str) -> Result + where + X: Wordlist, + { let wordlist = X::get_singleton(); let words = wordlist.to_str_array(); @@ -340,16 +344,12 @@ impl PromptHandler for Terminal where R: Read + Sized, W: Write + As Ok(input) } - fn prompt_validated_passphrase( + fn prompt_validated_passphrase( &mut self, prompt: &str, retries: u8, - validator_fn: F, - ) -> Result - where - F: Fn(String) -> Result, - E: std::error::Error, - { + validator_fn: impl Fn(String) -> Result>, + ) -> Result { let mut last_error = None; for _ in 0..retries { let s = self.prompt_passphrase(prompt)?; diff --git a/crates/util/keyfork-prompt/src/validators.rs b/crates/util/keyfork-prompt/src/validators.rs index e05e21f..8d10dcf 100644 --- a/crates/util/keyfork-prompt/src/validators.rs +++ b/crates/util/keyfork-prompt/src/validators.rs @@ -12,7 +12,7 @@ pub trait Validator { type Error; /// Create a validator function from the given parameters. - fn to_fn(&self) -> Box Result>; + fn to_fn(&self) -> Box Result>>; } /// A PIN could not be validated from the given input. @@ -48,7 +48,7 @@ impl Validator for PinValidator { type Output = String; type Error = PinError; - fn to_fn(&self) -> Box Result> { + fn to_fn(&self) -> Box Result>> { let min_len = self.min_length.unwrap_or(usize::MIN); let max_len = self.max_length.unwrap_or(usize::MAX); let range = self.range.clone().unwrap_or('0'..='9'); @@ -56,14 +56,14 @@ impl Validator for PinValidator { s.truncate(s.trim_end().len()); let len = s.len(); if len < min_len { - return Err(PinError::TooShort(len, min_len)); + return Err(Box::new(PinError::TooShort(len, min_len))); } if len > max_len { - return Err(PinError::TooLong(len, max_len)); + return Err(Box::new(PinError::TooLong(len, max_len))); } for (index, ch) in s.chars().enumerate() { if !range.contains(&ch) { - return Err(PinError::InvalidCharacters(ch, index)); + return Err(Box::new(PinError::InvalidCharacters(ch, index))); } } Ok(s) @@ -123,13 +123,13 @@ pub mod mnemonic { type Output = Mnemonic; type Error = MnemonicValidationError; - fn to_fn(&self) -> Box Result> { + fn to_fn(&self) -> Box Result>> { let word_length = self.word_length.clone(); Box::new(move |s: String| match word_length.as_ref() { Some(wl) => { let count = s.split_whitespace().count(); if !wl.matches(count) { - return Err(Self::Error::InvalidLength(count, wl.clone())); + return Err(Box::new(Self::Error::InvalidLength(count, wl.clone()))); } let m = Mnemonic::from_str(&s)?; Ok(m) @@ -165,7 +165,7 @@ pub mod mnemonic { type Output = Mnemonic; type Error = MnemonicChoiceValidationError; - fn to_fn(&self) -> Box Result> { + fn to_fn(&self) -> Box Result>> { let word_lengths = self.word_lengths.clone(); Box::new(move |s: String| { let count = s.split_whitespace().count(); @@ -175,10 +175,10 @@ pub mod mnemonic { return Ok(m); } } - Err(MnemonicChoiceValidationError::InvalidLength( + Err(Box::new(MnemonicChoiceValidationError::InvalidLength( count, word_lengths.to_vec(), - )) + ))) }) } } @@ -207,7 +207,7 @@ pub mod mnemonic { type Output = [Mnemonic; N]; type Error = MnemonicSetValidationError; - fn to_fn(&self) -> Box Result> { + fn to_fn(&self) -> Box Result>> { let word_lengths = self.word_lengths; Box::new(move |s: String| { let mut counter: usize = 0; @@ -219,15 +219,17 @@ pub mod mnemonic { .take(word_length) .collect::>(); if words.len() != word_length { - return Err(MnemonicSetValidationError::InvalidSetLength( + return Err(Box::new(MnemonicSetValidationError::InvalidSetLength( word_set, words.len(), word_length, - )); + ))); } let mnemonic = match Mnemonic::from_str(&words.join(" ")) { Ok(m) => m, - Err(e) => return Err(Self::Error::MnemonicFromStrError(word_set, e)), + Err(e) => { + return Err(Box::new(Self::Error::MnemonicFromStrError(word_set, e))) + } }; output.push(mnemonic); counter += word_length;