{-# OPTIONS_HADDOCK prune #-}
{-# LANGUAGE BangPatterns #-}

-- |
-- Module: Crypto.CSPRNG
-- Copyright: (c) 2026 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- A fast cryptographically-secure pseudorandom number generator:
-- [ChaCha8Rand](https://c2sp.org/chacha8rand), as used by Go's
-- @math/rand/v2@ and runtime.
--
-- The generator draws 992 bytes of output at a time from ChaCha8, and
-- rekeys itself from the next 32 bytes. Its key and output buffer are
-- erased as they are used, and the native ChaCha8 kernels (on aarch64
-- and x86_64) zero the stack they use, so that a later disclosure of
-- the process's memory reveals nothing about prior output. This
-- covers the generator's own state only: copies of seeds passed to it
-- and of output it returns are the caller's to manage, and on other
-- platforms the pure Haskell ChaCha8 fallback makes copies of keys and
-- keystream that the garbage collector manages and can't erase.
--
-- The generator is mutable, living in any 'PrimMonad' (e.g. 'IO' or
-- 'ST s'), and is not thread-safe. Use one generator per thread,
-- deriving more via 'split'.
--
-- A forked process (e.g. via @forkProcess@), or a restored virtual
-- machine snapshot, inherits a copy of the generator's state, and
-- then produces the same output as the original. Create a new
-- generator in such a child, e.g. via 'new_system', rather than using
-- an inherited one.

module Crypto.CSPRNG (
    -- * Generator
    Gen
  , new
  , new_system

    -- * Output
  , word64
  , word64_range
  , int_range
  , bytes

    -- * Splitting
  , split

    -- * Wiping
  , wipe
  ) where

import Control.Monad.Primitive (PrimMonad, PrimState, unsafeIOToPrim)
import Control.Monad.ST (ST)
import qualified Crypto.Cipher.ChaCha as ChaCha
import qualified Crypto.Entropy as Entropy
import qualified Crypto.Range as Range
import Data.Bits ((.&.), complement)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
import qualified Data.Primitive.ByteArray as BA
import Data.Word (Word8, Word64, byteSwap64)
import Foreign.ForeignPtr (touchForeignPtr)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import Foreign.Marshal.Utils (copyBytes)
import Foreign.Ptr (Ptr, castPtr, plusPtr)
import GHC.ByteOrder (ByteOrder(..), targetByteOrder)
import GHC.Exts (RealWorld)

-- utils ----------------------------------------------------------------------

fi :: (Integral a, Num b) => a -> b
fi :: forall a b. (Integral a, Num b) => a -> b
fi = a -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral
{-# INLINE fi #-}

-- convert between host and little-endian byte order
le64 :: Word64 -> Word64
le64 :: Word64 -> Word64
le64 Word64
w = case ByteOrder
targetByteOrder of
  ByteOrder
LittleEndian -> Word64
w
  ByteOrder
BigEndian    -> Word64 -> Word64
byteSwap64 Word64
w
{-# INLINE le64 #-}

-- state ----------------------------------------------------------------------

-- a generator's state is a pinned byte array, laid out as:
--
--   offset  size  contents
--   0       32    key for the next refill
--   32      16    zero nonce (12 bytes used)
--   48      8     position of the next unread byte of output
--   64      1024  output (992 bytes) and next key (32 bytes)
--
-- all bytes of output, and all keys, are little-endian.

-- | A ChaCha8Rand generator.
newtype Gen s = Gen (BA.MutableByteArray s)

_KEY, _NONCE, _POS, _OUT, _SIZE, _AVAIL :: Int
_KEY :: Int
_KEY   = Int
0
_NONCE :: Int
_NONCE = Int
32
_POS :: Int
_POS   = Int
48
_OUT :: Int
_OUT   = Int
64
_SIZE :: Int
_SIZE  = Int
1088
_AVAIL :: Int
_AVAIL = Int
992

alloc :: PrimMonad m => m (BA.MutableByteArray (PrimState m))
alloc :: forall (m :: * -> *).
PrimMonad m =>
m (MutableByteArray (PrimState m))
alloc = do
  st <- Int -> m (MutableByteArray (PrimState m))
forall (m :: * -> *).
PrimMonad m =>
Int -> m (MutableByteArray (PrimState m))
BA.newPinnedByteArray Int
_SIZE
  BA.setByteArray st 0 _SIZE (0 :: Word8)
  pure st
{-# INLINE alloc #-}

read_pos :: PrimMonad m => BA.MutableByteArray (PrimState m) -> m Int
read_pos :: forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> m Int
read_pos MutableByteArray (PrimState m)
st = do
  !p <- MutableByteArray (PrimState m) -> Int -> m Word64
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
BA.readByteArray MutableByteArray (PrimState m)
st (Int
_POS Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` Int
8)
  pure $! fi (p :: Word64)
{-# INLINE read_pos #-}

write_pos :: PrimMonad m => BA.MutableByteArray (PrimState m) -> Int -> m ()
write_pos :: forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> Int -> m ()
write_pos MutableByteArray (PrimState m)
st Int
p = MutableByteArray (PrimState m) -> Int -> Word64 -> m ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
BA.writeByteArray MutableByteArray (PrimState m)
st (Int
_POS Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` Int
8) (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fi Int
p :: Word64)
{-# INLINE write_pos #-}

ptr :: BA.MutableByteArray s -> Int -> Ptr Word8
ptr :: forall s. MutableByteArray s -> Int -> Ptr Word8
ptr MutableByteArray s
st Int
off = MutableByteArray s -> Ptr Word8
forall s. MutableByteArray s -> Ptr Word8
BA.mutableByteArrayContents MutableByteArray s
st Ptr Word8 -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
off
{-# INLINE ptr #-}

-- ChaCha8Rand iteration: replace the output buffer with 992 fresh
-- bytes of output, and rekey.
refill :: PrimMonad m => BA.MutableByteArray (PrimState m) -> m ()
refill :: forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> m ()
refill MutableByteArray (PrimState m)
st = do
  -- sixteen ChaCha8 blocks, with counters 0 to 15, interleaved four
  -- at a time and with the final addition covering only the key
  IO () -> m ()
forall (m :: * -> *) a. PrimMonad m => IO a -> m a
unsafeIOToPrim (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$
    Rounds
-> FeedForward
-> Ptr Word8
-> Word32
-> Ptr Word8
-> Ptr Word8
-> Int
-> IO ()
ChaCha._interleaved_into Rounds
ChaCha.ChaCha8 FeedForward
ChaCha.FeedForwardKey
      (MutableByteArray (PrimState m) -> Int -> Ptr Word8
forall s. MutableByteArray s -> Int -> Ptr Word8
ptr MutableByteArray (PrimState m)
st Int
_KEY) Word32
0 (MutableByteArray (PrimState m) -> Int -> Ptr Word8
forall s. MutableByteArray s -> Int -> Ptr Word8
ptr MutableByteArray (PrimState m)
st Int
_NONCE) (MutableByteArray (PrimState m) -> Int -> Ptr Word8
forall s. MutableByteArray s -> Int -> Ptr Word8
ptr MutableByteArray (PrimState m)
st Int
_OUT) Int
4
  -- the last 32 bytes of output are the next key
  MutableByteArray (PrimState m)
-> Int -> MutableByteArray (PrimState m) -> Int -> Int -> m ()
forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m)
-> Int -> MutableByteArray (PrimState m) -> Int -> Int -> m ()
BA.copyMutableByteArray MutableByteArray (PrimState m)
st Int
_KEY MutableByteArray (PrimState m)
st (Int
_OUT Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
_AVAIL) Int
32
  MutableByteArray (PrimState m) -> Int -> Int -> Word8 -> m ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> Int -> a -> m ()
BA.setByteArray MutableByteArray (PrimState m)
st (Int
_OUT Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
_AVAIL) Int
32 (Word8
0 :: Word8)
  MutableByteArray (PrimState m) -> Int -> m ()
forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> Int -> m ()
write_pos MutableByteArray (PrimState m)
st Int
0
{-# INLINABLE refill #-}
{-# SPECIALIZE refill :: BA.MutableByteArray RealWorld -> IO () #-}
{-# SPECIALIZE refill :: BA.MutableByteArray s -> ST s () #-}

-- copy the next bytes of output to the destination, erasing them
fill
  :: PrimMonad m
  => BA.MutableByteArray (PrimState m)
  -> Ptr Word8
  -> Int
  -> m ()
fill :: forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> Ptr Word8 -> Int -> m ()
fill MutableByteArray (PrimState m)
st Ptr Word8
dst Int
n = Int -> m ()
forall {f :: * -> *}.
(PrimState f ~ PrimState m, PrimMonad f) =>
Int -> f ()
loop Int
0 where
  loop :: Int -> f ()
loop !Int
off
    | Int
off Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
n  = () -> f ()
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    | Bool
otherwise = do
        !pos <- MutableByteArray (PrimState f) -> f Int
forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> m Int
read_pos MutableByteArray (PrimState m)
MutableByteArray (PrimState f)
st
        if   pos == _AVAIL
        then do
          refill st
          loop off
        else do
          let !k = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
off) (Int
_AVAIL Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
pos)
              !d = Ptr Word8
dst Ptr Word8 -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
off :: Ptr Word8
          BA.copyMutableByteArrayToPtr d st (_OUT + pos) k
          BA.setByteArray st (_OUT + pos) k (0 :: Word8)
          write_pos st (pos + k)
          loop (off + k)
{-# INLINABLE fill #-}

-- generator ------------------------------------------------------------------

-- | Create a generator from a 256-bit seed, returning 'Nothing' if the
--   seed is not exactly 32 bytes.
--
--   The seed must be secret and uniformly random; prefer 'new_system'
--   unless a reproducible stream is required.
--
--   >>> Just gen <- new "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
--   >>> word64 gen
--   13219109469176600229
new
  :: PrimMonad m
  => BS.ByteString
  -> m (Maybe (Gen (PrimState m)))
new :: forall (m :: * -> *).
PrimMonad m =>
ByteString -> m (Maybe (Gen (PrimState m)))
new seed :: ByteString
seed@(BI.PS ForeignPtr Word8
_ Int
_ Int
l)
  | Int
l Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32   = Maybe (Gen (PrimState m)) -> m (Maybe (Gen (PrimState m)))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (Gen (PrimState m))
forall a. Maybe a
Nothing
  | Bool
otherwise = do
      st <- m (MutableByteArray (PrimState m))
forall (m :: * -> *).
PrimMonad m =>
m (MutableByteArray (PrimState m))
alloc
      unsafeIOToPrim $ BU.unsafeUseAsCString seed $ \CString
sp ->
        Ptr Word8 -> Ptr Word8 -> Int -> IO ()
forall a. Ptr a -> Ptr a -> Int -> IO ()
copyBytes (MutableByteArray (PrimState m) -> Int -> Ptr Word8
forall s. MutableByteArray s -> Int -> Ptr Word8
ptr MutableByteArray (PrimState m)
st Int
_KEY) (CString -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr CString
sp) Int
32
      refill st
      pure $! Just (Gen st)
{-# INLINABLE new #-}
{-# SPECIALIZE new :: BS.ByteString -> IO (Maybe (Gen RealWorld)) #-}
{-# SPECIALIZE new :: BS.ByteString -> ST s (Maybe (Gen s)) #-}

-- | Create a generator seeded from the operating system's entropy
--   source, returning 'Nothing' if that fails.
--
--   >>> Just gen <- new_system
new_system :: IO (Maybe (Gen RealWorld))
new_system :: IO (Maybe (Gen RealWorld))
new_system = do
  st <- IO (MutableByteArray RealWorld)
IO (MutableByteArray (PrimState IO))
forall (m :: * -> *).
PrimMonad m =>
m (MutableByteArray (PrimState m))
alloc
  ok <- Entropy.fill (ptr st _KEY) 32
  if   not ok
  then pure Nothing
  else do
    refill st
    pure $! Just (Gen st)

-- output ---------------------------------------------------------------------

-- | Generate a uniformly-distributed 'Word64' from the next eight
--   bytes of output, read in little-endian order. If a call to 'bytes'
--   has left the output out of eight-byte alignment, the bytes up to
--   the next boundary are discarded.
--
--   >>> Just gen <- new "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
--   >>> word64 gen
--   13219109469176600229
word64 :: PrimMonad m => Gen (PrimState m) -> m Word64
word64 :: forall (m :: * -> *). PrimMonad m => Gen (PrimState m) -> m Word64
word64 (Gen MutableByteArray (PrimState m)
st) = do
  !pos <- MutableByteArray (PrimState m) -> m Int
forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> m Int
read_pos MutableByteArray (PrimState m)
st
  let !aligned = (Int
pos Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7) Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int -> Int
forall a. Bits a => a -> a
complement Int
7
  !p <- if   aligned + 8 > _AVAIL
        then do
          refill st
          pure 0
        else pure aligned
  let !ix = (Int
_OUT Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
p) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` Int
8
  !w <- BA.readByteArray st ix
  BA.writeByteArray st ix (0 :: Word64)
  write_pos st (p + 8)
  pure $! le64 w
{-# INLINE word64 #-}

-- | Generate a uniformly-distributed 'Word64' in the given inclusive
--   range, whose bounds may be given in either order.
--
--   The result is unbiased; see 'int_range'.
--
--   >>> Just gen <- new "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
--   >>> word64_range 1 6 gen
--   5
word64_range
  :: PrimMonad m => Word64 -> Word64 -> Gen (PrimState m) -> m Word64
word64_range :: forall (m :: * -> *).
PrimMonad m =>
Word64 -> Word64 -> Gen (PrimState m) -> m Word64
word64_range Word64
a Word64
b Gen (PrimState m)
gen = do
  let !lo :: Word64
lo = Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
min Word64
a Word64
b
      !hi :: Word64
hi = Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
max Word64
a Word64
b
  !r <- m Word64 -> Word64 -> m Word64
forall (m :: * -> *). Monad m => m Word64 -> Word64 -> m Word64
Range.upto (Gen (PrimState m) -> m Word64
forall (m :: * -> *). PrimMonad m => Gen (PrimState m) -> m Word64
word64 Gen (PrimState m)
gen) (Word64
hi Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
lo)
  pure $! lo + r
{-# INLINE word64_range #-}

-- | Generate a uniformly-distributed 'Int' in the given inclusive
--   range, whose bounds may be given in either order.
--
--   The result is unbiased, via Lemire's method: an occasional draw is
--   rejected and replaced, so the number of words consumed, and the
--   running time, depend on the (discarded) rejected words.
--
--   >>> Just gen <- new "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
--   >>> int_range (-10) 10 gen
--   5
int_range :: PrimMonad m => Int -> Int -> Gen (PrimState m) -> m Int
int_range :: forall (m :: * -> *).
PrimMonad m =>
Int -> Int -> Gen (PrimState m) -> m Int
int_range Int
a Int
b Gen (PrimState m)
gen = do
  let !lo :: Int
lo = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min Int
a Int
b
      !hi :: Int
hi = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
a Int
b
  !r <- m Word64 -> Word64 -> m Word64
forall (m :: * -> *). Monad m => m Word64 -> Word64 -> m Word64
Range.upto (Gen (PrimState m) -> m Word64
forall (m :: * -> *). PrimMonad m => Gen (PrimState m) -> m Word64
word64 Gen (PrimState m)
gen) (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fi Int
hi Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fi Int
lo)
  pure $! lo + fi r
{-# INLINE int_range #-}

-- | Generate the given number of bytes. Non-positive counts yield the
--   empty string.
--
--   >>> import qualified Data.ByteString.Base16 as B16
--   >>> Just gen <- new "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
--   >>> fmap B16.encode (bytes 8 gen)
--   "a516463d06b673b7"
bytes :: PrimMonad m => Int -> Gen (PrimState m) -> m BS.ByteString
bytes :: forall (m :: * -> *).
PrimMonad m =>
Int -> Gen (PrimState m) -> m ByteString
bytes Int
n (Gen MutableByteArray (PrimState m)
st)
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0    = ByteString -> m ByteString
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
  | Bool
otherwise = do
      fp <- IO (ForeignPtr Word8) -> m (ForeignPtr Word8)
forall (m :: * -> *) a. PrimMonad m => IO a -> m a
unsafeIOToPrim (Int -> IO (ForeignPtr Word8)
forall a. Int -> IO (ForeignPtr a)
BI.mallocByteString Int
n)
      fill st (unsafeForeignPtrToPtr fp) n
      unsafeIOToPrim (touchForeignPtr fp)
      pure $! BI.BS fp n
{-# INLINABLE bytes #-}
{-# SPECIALIZE bytes :: Int -> Gen RealWorld -> IO BS.ByteString #-}
{-# SPECIALIZE bytes :: Int -> Gen s -> ST s BS.ByteString #-}

-- splitting ------------------------------------------------------------------

-- | Derive a new generator, seeded from the next 32 bytes of output.
--
--   The two generators' outputs are independent; use 'split' to give
--   each thread its own generator.
--
--   >>> Just gen <- new_system
--   >>> child <- split gen
split :: PrimMonad m => Gen (PrimState m) -> m (Gen (PrimState m))
split :: forall (m :: * -> *).
PrimMonad m =>
Gen (PrimState m) -> m (Gen (PrimState m))
split (Gen MutableByteArray (PrimState m)
st) = do
  child <- m (MutableByteArray (PrimState m))
forall (m :: * -> *).
PrimMonad m =>
m (MutableByteArray (PrimState m))
alloc
  fill st (ptr child _KEY) 32
  refill child
  pure $! Gen child
{-# INLINABLE split #-}

-- wiping ---------------------------------------------------------------------

-- | Erase a generator's state.
--
--   Call this when finished with a generator, to wipe its key and any
--   unused output from memory. The generator must not be used
--   afterwards: it would then produce output from an all-zero key,
--   which is predictable.
--
--   >>> Just gen <- new_system
--   >>> out <- bytes 32 gen
--   >>> wipe gen
wipe :: PrimMonad m => Gen (PrimState m) -> m ()
wipe :: forall (m :: * -> *). PrimMonad m => Gen (PrimState m) -> m ()
wipe (Gen MutableByteArray (PrimState m)
st) = do
  MutableByteArray (PrimState m) -> Int -> Int -> Word8 -> m ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> Int -> a -> m ()
BA.setByteArray MutableByteArray (PrimState m)
st Int
0 Int
_SIZE (Word8
0 :: Word8)
  MutableByteArray (PrimState m) -> Int -> m ()
forall (m :: * -> *).
PrimMonad m =>
MutableByteArray (PrimState m) -> Int -> m ()
write_pos MutableByteArray (PrimState m)
st Int
_AVAIL
{-# INLINE wipe #-}