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 = forall passPhrase seed.
(ByteArrayAccess passPhrase, ByteArrayAccess seed) =>
seed -> passPhrase -> XPrv
CC.generate ByteString
seed ScrubbedBytes
pp in (HasCallStack => 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 :: forall (m :: * -> *).
MonadRandom m =>
PassPhrase -> m (VerificationKey, SigningKey)
safeKeyGen PassPhrase
pp = do
  ByteString
seed <- forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
32
  forall (f :: * -> *) a. Applicative f => a -> f a
pure 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 =
  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)