mssmt-0.1.0: bench/Fixtures.hs
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE BangPatterns #-}
module Fixtures (
Fixtures(..)
, fixtures
, leaves
, build
) where
import Control.DeepSeq
import Control.Monad (foldM)
import qualified Crypto.Hash.SHA256 as SHA256
import Data.Bits (bit, testBit, xor)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Data.MSSMT
import qualified Data.MSSMT.Internal as I
import Data.Void (Void)
import Data.Word (Word64)
-- all fields are strict, so WHNF is NF
instance NFData Key where
rnf = rwhnf
instance NFData Commitment where
rnf = rwhnf
instance NFData Tree where
rnf = rwhnf
instance NFData Neighbor where
rnf = rwhnf
instance NFData Proof where
rnf (Proof nb ps) = rnf nb `seq` rnf ps
-- | A tree of 1024 leaves, its root, a leaf in it, a key not in it
-- whose slot is empty, their proofs, and a key not in it whose slot
-- the leaf occupies.
data Fixtures = Fixtures {
f_tree :: !Tree
, f_root :: !Commitment
, f_key :: !Key
, f_value :: !BS.ByteString
, f_sum :: !Word64
, f_proof :: !Proof
, f_out :: !Key
, f_xproof :: !Proof
, f_near :: !Key
}
instance NFData Fixtures where
rnf (Fixtures t r k v s p o x n) =
rnf t `seq` rnf r `seq` rnf k `seq` rnf v `seq` rnf s
`seq` rnf p `seq` rnf o `seq` rnf x `seq` rnf n
fixtures :: Fixtures
fixtures = Fixtures t (root t) k v s (prove k t) o (prove o t) n where
t = build (leaves 1024)
(k, v, s) = leaf_of 1
o = key_of 0
n = near k raw
raw = case foldM ins I.empty (leaves 1024) of
Just r -> r
Nothing -> error "bang"
ins r (k', v', s') = I.complete (I.insert_with I.Split k' v' s' r)
-- a key whose path ends at the given key's leaf, diverging from it just
-- beneath: the given key, with the bit beneath its leaf flipped
near :: Key -> I.Tree Void -> Key
near (I.Key h) = flip_at . go 0 where
bs = I.serialize_hash h
go :: Int -> I.Tree Void -> Int
go !d t = case t of
I.Node l _ r -> go (d + 1) (if kbit d then r else l)
I.Leaf {} -> d
I.Empty -> d
kbit d = testBit (BS.index bs (d `quot` 8)) (d `rem` 8)
flip_at d = case BS.splitAt (d `quot` 8) bs of
(a, b) | Just (w, c) <- BS.uncons b
, Just n <- key (a <> BS.cons (w `xor` bit (d `rem` 8)) c) -> n
_ -> error "bang"
-- | n distinct leaves.
leaves :: Int -> [(Key, BS.ByteString, Word64)]
leaves n = fmap leaf_of [1 .. n]
leaf_of :: Int -> (Key, BS.ByteString, Word64)
leaf_of i =
(key_of i, SHA256.hash (B8.pack ('v' : show i)), fromIntegral i)
key_of :: Int -> Key
key_of i = case key (SHA256.hash (B8.pack (show i))) of
Just k -> k
Nothing -> error "bang"
-- | Build a tree from leaves.
build :: [(Key, BS.ByteString, Word64)] -> Tree
build ls = case foldM (\t (k, v, s) -> insert k v s t) empty ls of
Just t -> t
Nothing -> error "bang"