module Cardano.Crypto.Signing.Safe.KeyGen
  ( safeDeterministicKeyGen,
    safeKeyGen,
  )
where

import Cardano.Crypto.Signing.Safe.PassPhrase (PassPhrase (..))
import Cardano.Crypto.Signing.SigningKey (SigningKey (..))
import Cardano.Crypto.Signing.VerificationKey (VerificationKey (..))
import qualified Cardano.Crypto.Wallet as CC
import Cardano.Prelude
import Crypto.Random (MonadRandom, getRandomBytes)
import qualified Data.ByteString as BS

safeCreateKeypairFromSeed :: BS.ByteString -> PassPhrase -> (CC.XPub, CC.XPrv)
safeCreateKeypairFromSeed :: ByteString -> PassPhrase -> (XPub, XPrv)
safeCreateKeypairFromSeed ByteString
seed (PassPhrase ScrubbedBytes
pp) =
  let prv :: XPrv
prv = ByteString -> ScrubbedBytes -> XPrv
forall passPhrase seed.
(ByteArrayAccess passPhrase, ByteArrayAccess seed) =>
seed -> passPhrase -> XPrv
CC.generate ByteString
seed ScrubbedBytes
pp in (HasCallStack => XPrv -> XPub
XPrv -> XPub
CC.toXPub XPrv
prv, XPrv
prv)

-- NB. It's recommended to run it with 'runSecureRandom' from
-- "Cardano.Crypto.Random" because the OpenSSL generator is probably safer than
-- the default IO generator.
safeKeyGen :: (MonadRandom m) => PassPhrase -> m (VerificationKey, SigningKey)
safeKeyGen :: PassPhrase -> m (VerificationKey, SigningKey)
safeKeyGen PassPhrase
pp = do
  ByteString
seed <- Int -> m ByteString
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
32
  (VerificationKey, SigningKey) -> m (VerificationKey, SigningKey)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((VerificationKey, SigningKey) -> m (VerificationKey, SigningKey))
-> (VerificationKey, SigningKey) -> m (VerificationKey, SigningKey)
forall a b. (a -> b) -> a -> b
$ ByteString -> PassPhrase -> (VerificationKey, SigningKey)
safeDeterministicKeyGen ByteString
seed PassPhrase
pp

safeDeterministicKeyGen ::
  BS.ByteString -> PassPhrase -> (VerificationKey, SigningKey)
safeDeterministicKeyGen :: ByteString -> PassPhrase -> (VerificationKey, SigningKey)
safeDeterministicKeyGen ByteString
seed PassPhrase
pp =
  (XPub -> VerificationKey)
-> (XPrv -> SigningKey)
-> (XPub, XPrv)
-> (VerificationKey, SigningKey)
forall (p :: * -> * -> *) a b c d.
Bifunctor p =>
(a -> b) -> (c -> d) -> p a c -> p b d
bimap XPub -> VerificationKey
VerificationKey XPrv -> SigningKey
SigningKey (ByteString -> PassPhrase -> (XPub, XPrv)
safeCreateKeypairFromSeed ByteString
seed PassPhrase
pp)