Skip to content

Commit

Permalink
Encode the minimum and maximum passphrase lengths just once, using na…
Browse files Browse the repository at this point in the history
…med constants.
  • Loading branch information
jonathanknowles committed Mar 27, 2019
1 parent 3c56a9c commit f418d29
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
20 changes: 16 additions & 4 deletions src/Cardano/Wallet/Api/Types.hs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ module Cardano.Wallet.Api.Types
, AddressPoolGap
, Passphrase(..)

-- * Limits
, passphraseMinLength
, passphraseMaxLength

-- * Polymorphic Types
, ApiT (..)
, ApiMnemonicT (..)
Expand Down Expand Up @@ -176,13 +180,21 @@ instance ToJSON WalletPostData where

instance FromJSON (ApiT (Passphrase "encryption")) where
parseJSON = parseJSON >=> \case
t | T.length t < 10 ->
fail "passphrase is too short: expected at least 10 chars"
t | T.length t > 255 ->
fail "passphrase is too long: expect at most 255 chars"
t | T.length t < passphraseMinLength ->
fail $ "passphrase is too short: expected at least "
<> show passphraseMinLength <> " chars"
t | T.length t > passphraseMaxLength ->
fail $ "passphrase is too long: expected at most "
<> show passphraseMaxLength <> " chars"
t ->
return $ ApiT $ Passphrase $ BA.convert $ T.encodeUtf8 t

passphraseMinLength :: Int
passphraseMinLength = 10

passphraseMaxLength :: Int
passphraseMaxLength = 255

instance ToJSON (ApiT (Passphrase "encryption")) where
toJSON (ApiT (Passphrase bytes)) = toJSON $ T.decodeUtf8 $ BA.convert bytes

Expand Down
12 changes: 9 additions & 3 deletions test/unit/Cardano/Wallet/Api/TypesSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import Cardano.Wallet.Api.Types
, WalletPassphraseInfo (..)
, WalletPostData (..)
, WalletState (..)
, passphraseMinLength
, passphraseMaxLength
)
import Cardano.Wallet.Primitive.Mnemonic
( CheckSumBits
Expand Down Expand Up @@ -229,12 +231,16 @@ instance Arbitrary WalletName where

instance Arbitrary (Passphrase "encryption") where
arbitrary = do
n <- choose (10, 255)
n <- choose (passphraseMinLength, passphraseMaxLength)
bytes <- T.encodeUtf8 . T.pack <$> replicateM n arbitraryPrintableChar
return $ Passphrase $ BA.convert bytes
shrink (Passphrase bytes)
| BA.length bytes <= 10 = []
| otherwise = [Passphrase $ BA.convert $ B8.take 10 $ BA.convert bytes]
| BA.length bytes <= passphraseMinLength = []
| otherwise =
[ Passphrase
$ BA.convert
$ B8.take passphraseMinLength
$ BA.convert bytes ]

instance Arbitrary WalletPassphraseInfo where
arbitrary = genericArbitrary
Expand Down

0 comments on commit f418d29

Please sign in to comment.