-- |-- Module : Crypto.Random.EntropyPool-- License : BSD-style-- Maintainer : Vincent Hanquez <vincent@snarc.org>-- Stability : experimental-- Portability : Goodmodule Crypto.Random.EntropyPool ( EntropyPool, createEntropyPool, createEntropyPoolWith, getEntropyFrom,) whereimport Control.Concurrent.MVarimport Crypto.Internal.ByteArray (ByteArray, ScrubbedBytes)import qualified Crypto.Internal.ByteArray as Bimport Crypto.Random.Entropy.Unsafeimport Data.Maybe (catMaybes)import Data.Word (Word8)import Foreign.Marshal.Utils (copyBytes)import Foreign.Ptr (Ptr, plusPtr)-- | Pool of Entropy. Contains a self-mutating pool of entropy,-- that is always guaranteed to contain data.data EntropyPool = EntropyPool [EntropyBackend] (MVar Int) ScrubbedBytes-- size of entropy pool by defaultdefaultPoolSize :: IntdefaultPoolSize = 4096-- | Create a new entropy pool of a specific size---- While you can create as many entropy pools as you want,-- the pool can be shared between multiples RNGs.createEntropyPoolWith :: Int -> [EntropyBackend] -> IO EntropyPoolcreateEntropyPoolWith poolSize backends -- an empty pool can never hand out a byte; drawing from one looped forever | poolSize <= 0 = error "Crypto.Random.EntropyPool: the pool size must be positive" | otherwise = do m <- newMVar 0 sm <- B.alloc poolSize (replenish poolSize backends) return $ EntropyPool backends m sm-- | Create a new entropy pool with a default size.---- While you can create as many entropy pools as you want,-- the pool can be shared between multiples RNGs.createEntropyPool :: IO EntropyPoolcreateEntropyPool = do backends <- catMaybes `fmap` sequence supportedBackends createEntropyPoolWith defaultPoolSize backends-- | Put a chunk of the entropy pool into a buffergetEntropyPtr :: EntropyPool -> Int -> Ptr Word8 -> IO ()getEntropyPtr (EntropyPool backends posM sm) n outPtr = B.withByteArray sm $ \entropyPoolPtr -> modifyMVar_ posM $ \pos -> copyLoop outPtr entropyPoolPtr pos n where poolSize = B.length sm copyLoop d s pos left | left == 0 = return pos | otherwise = do wrappedPos <- if pos == poolSize then replenish poolSize backends s >> return 0 else return pos let m = min (poolSize - wrappedPos) left copyBytes d (s `plusPtr` wrappedPos) m copyLoop (d `plusPtr` m) s (wrappedPos + m) (left - m)-- | Grab a chunk of entropy from the entropy pool.---- A negative length is an error; it used to reach a copy of negative size.getEntropyFrom :: ByteArray byteArray => EntropyPool -> Int -> IO byteArraygetEntropyFrom pool n | n < 0 = error "Crypto.Random.EntropyPool: negative length" | otherwise = B.alloc n (getEntropyPtr pool n)