2

There is an Crypto.Random API inside the crypto-api package that specifies what it means for something to be a "pseudorandom number generator".

I have implemented this API using an instance of System.Random's RandomGen class, namely, StdGen:

instance CryptoRandomGen StdGen where
  newGen bs = Right $ mkStdGen $ shift e1 24 + shift e2 16 + shift e3 8 + e4
    where (e1 : e2 : e3 : e4 : _) = Prelude.map fromIntegral $ unpack bs
  genSeedLength = Tagged 4
  genBytes n g = Right $ genBytesHelper n empty g
    where genBytesHelper 0 partial gen = (partial, gen)
          genBytesHelper n partial gen = genBytesHelper (n-1) (partial `snoc` nextitem) newgen
            where (nextitem, newgen) = randomR (0, 255) gen
  reseed bs _ = newGen bs

However, this implementation is only for the StdGen type, but it would really work for anything in System.Random's RandomGen typeclass.

Is there a way to say that everything in RandomGen is a member of CryptoRandomGen using the given shim functions? I'd like to be able to do this in my own code, without having to change the source of either of those two libraries. My instincts would be to change the first line to something like

instance (RandomGen a) => CryptoRandomGen a where

but that doesn't appear to be syntactically correct.

Litherum
  • 22,564
  • 3
  • 23
  • 27

2 Answers2

6

Crypto-API author here. Please don't do this - it's really a violation of the implicit properties of CryptoRandomGen.

That said, here's how I'd do it: Just make a newtype that wraps your RandomGen and make that newtype an instance of CryptoRandomGen.

newtype AsCRG g = ACRG { unACRG :: g}

instance RandomGen g => CryptoRandomGen (AsCRG g) where
    newGen = -- This is not possible to implement with only a 'RandomGen' constraint.  Perhaps you want a 'Default' instance too?
    genSeedLength = -- This is also not possible from just 'RandomGen'
    genBytes nr g =
        let (g1,g2) = split g
            randInts :: [Word32]
            randInts = B.concat . map Data.Serialize.encode
                     . take ((nr + 3) `div` 4)
                     $ (randoms g1 :: [Word32])
        in (B.take nr randInts, g2)
    reseed _ _ = -- not possible w/o more constraints
    newGenIO = -- not possible w/o more constraints

So you see, you can split the generator (or manage many intermediate generators), make the right number of Ints (or in my case, Word32s), encode them, and return the bytes.

Because RandomGen is limited to just generation (and splitting), there isn't any straight-forward way to support instatiation, reinstantiation, or querying properties such as the seed length.

Thomas M. DuBuisson
  • 64,245
  • 7
  • 109
  • 166
  • Thanks; I totally see what you're saying about System.Random not supporting the semantics that crypto-api requires. I'll probably try to implement the other way (make every CryptoRandomGen instances of the RandomGen class) just as an exercise for fun. However, if I'm reading your code right, the caller will still have to wrap up their RandomGen in this ugly ACRG function to make the types check out. Looks like I have to weigh that against the ugliness of turning on UndecidableInstances. – Litherum Dec 11 '11 at 03:00
  • Yes, you're reading things right. It's a common trick, making a newtype in order to select a particular instance of a class. – Thomas M. DuBuisson Dec 11 '11 at 04:23
3

As far as I know, this is impossible, unless you're willing to turn on UndecidableInstances (which, of course, can make the typechecker go in an infinite loop). Here's an example that makes every instance of Monad an instance of Functor:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

module Main
       where

import Control.Monad (liftM)

instance (Monad a) => Functor a where
    fmap = liftM


-- Test code
data MyState a = MyState { unM :: a }
               deriving Show

instance Monad MyState where
  return a = MyState a
  (>>=) m k = k (unM m)

main :: IO ()
main = print . fmap (+ 1) . MyState $ 1

Testing:

*Main> :main
MyState { unM = 2 }

In your case, this translates to:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

instance (RandomGen a) => CryptoRandomGen a where
  newGen = ...
  genSeedLength = ...
  genBytes = ...
  reseed = ...

As an aside, I once asked how to implement this without UndecidableInstances on haskell-cafe and got this answer (the same workaround that Thomas proposed; I consider it ugly).

Mikhail Glushenkov
  • 14,928
  • 3
  • 52
  • 65
  • In this case the type checker is unlikely to go into an infinite loop. However, because you have an "OverreachingInstance" of Functor for all instances of Monad the choice of which instance to use for a given Monad (when it has its own instance) is dependent on compilation order - not good either. – stephen tetley Dec 11 '11 at 07:41