From b05b69b37552718d90b0e3a6f139bb8dd70f0bae Mon Sep 17 00:00:00 2001 From: Pablo Lamela Date: Tue, 26 Nov 2024 18:35:18 +0100 Subject: [PATCH] Check produced number of mnemonic words is as expected --- cardano-cli/src/Cardano/CLI/Run/Key.hs | 13 +++++++++++++ .../src/Cardano/CLI/Types/Errors/KeyCmdError.hs | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/cardano-cli/src/Cardano/CLI/Run/Key.hs b/cardano-cli/src/Cardano/CLI/Run/Key.hs index 79e363dde8..901efcb27f 100644 --- a/cardano-cli/src/Cardano/CLI/Run/Key.hs +++ b/cardano-cli/src/Cardano/CLI/Run/Key.hs @@ -53,6 +53,7 @@ import Cardano.Prelude (isSpace) import qualified Codec.Binary.Bech32 as Bech32 import qualified Control.Exception as Exception +import Control.Monad (when) import Data.Bifunctor (Bifunctor (..)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS @@ -219,11 +220,23 @@ runGenerateMnemonicCmd , mnemonicWords } = do mnemonic <- firstExceptT KeyCmdMnemonicError $ generateMnemonic mnemonicWords + let expectedNumOfMnemonicWords = mnemonicSizeToInt mnemonicWords + obtainedNumOfMnemonicWords = length mnemonic + when (obtainedNumOfMnemonicWords /= expectedNumOfMnemonicWords) $ + left $ + KeyCmdWrongNumOfMnemonics expectedNumOfMnemonicWords obtainedNumOfMnemonicWords case mnemonicOutputFormat of Just outFile -> firstExceptT KeyCmdWriteFileError . newExceptT $ writeTextFile outFile (T.unwords mnemonic) Nothing -> liftIO $ putStrLn $ T.unpack (T.unwords mnemonic) + where + mnemonicSizeToInt :: MnemonicSize -> Int + mnemonicSizeToInt MS12 = 12 + mnemonicSizeToInt MS15 = 15 + mnemonicSizeToInt MS18 = 18 + mnemonicSizeToInt MS21 = 21 + mnemonicSizeToInt MS24 = 24 readExtendedVerificationKeyFile :: VerificationKeyFile In diff --git a/cardano-cli/src/Cardano/CLI/Types/Errors/KeyCmdError.hs b/cardano-cli/src/Cardano/CLI/Types/Errors/KeyCmdError.hs index 6bc8f1e5cd..1a41af1356 100644 --- a/cardano-cli/src/Cardano/CLI/Types/Errors/KeyCmdError.hs +++ b/cardano-cli/src/Cardano/CLI/Types/Errors/KeyCmdError.hs @@ -24,6 +24,11 @@ data KeyCmdError | KeyCmdReadMnemonicFileError !(FileError ()) | KeyCmdWriteFileError !(FileError ()) | KeyCmdMnemonicError MnemonicToSigningKeyError + | KeyCmdWrongNumOfMnemonics + !Int + -- ^ Expected number of mnemonics + !Int + -- ^ Actual number of mnemonics | KeyCmdByronKeyFailure !Byron.ByronKeyFailure | -- | Text representation of the parse error. Unfortunately, the actual -- error type isn't exported. @@ -51,6 +56,8 @@ renderKeyCmdError err = prettyError fileErr KeyCmdMnemonicError mnemonicErr -> "Error converting the mnemonic into a key: " <> prettyError mnemonicErr + KeyCmdWrongNumOfMnemonics expected actual -> + "Internal error: expected " <> pretty expected <> " mnemonics, but got " <> pretty actual KeyCmdByronKeyFailure e -> Byron.renderByronKeyFailure e KeyCmdByronKeyParseError errTxt ->