commit db4a04829328b623b0a7c7adcf7e20352ea292f1
parent b354968bd4103177e675f864d3ff47417fafb0a7
Author: Jared Tobin <jared@jtobin.io>
Date: Wed, 4 Nov 2026 19:17:27 +0400
lib: unboxed hashes, native SHA-256 compression
Represents hashes as four unpacked Word64s, so that tree nodes are
flat heap objects, and stores empty-subtree hashes in a PrimArray.
A branch's 72-byte hash input is exactly two SHA-256 blocks, so
branch hashes are now computed by running the compression function
twice from the IV directly on hash words: via ppad-sha256's native
block function (sha256_block_native) over FFI where hardware SHA-256
is available, and its pure Internal.update otherwise. Leaf hashes
use the strict SHA256.hash over an unsafeCreate'd buffer.
Pair now holds a Hash, with parse_hash and serialize_hash at the
boundary. insert and verify are ~20x faster and allocate ~50-80x
less.
Diffstat:
3 files changed, 234 insertions(+), 51 deletions(-)
diff --git a/lib/Data/MSSMT.hs b/lib/Data/MSSMT.hs
@@ -1,5 +1,8 @@
{-# OPTIONS_HADDOCK prune #-}
{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE MagicHash #-}
+{-# LANGUAGE UnboxedTuples #-}
+{-# LANGUAGE UnliftedFFITypes #-}
-- |
-- Module: Data.MSSMT
@@ -16,9 +19,12 @@
-- empty, and have fixed hashes at each depth.
module Data.MSSMT (
- -- * Keys and commitments
+ -- * Keys, hashes, and commitments
Key
, key
+ , Hash
+ , parse_hash
+ , serialize_hash
, Pair(..)
-- * Tree
@@ -35,14 +41,22 @@ module Data.MSSMT (
, verify
) where
-import Control.Monad (foldM)
import qualified Crypto.Hash.SHA256 as SHA256
-import Data.Bits (testBit)
+import qualified Crypto.Hash.SHA256.Internal as SHA256I
+import Data.Bits (testBit, unsafeShiftL, unsafeShiftR, (.|.))
import qualified Data.ByteString as BS
-import qualified Data.ByteString.Builder as BSB
+import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
-import qualified Data.Primitive.Array as PA
-import Data.Word (Word64)
+import qualified Data.Primitive.PrimArray as PA
+import Data.Word (Word8, Word64)
+import Foreign.C.Types (CInt(..))
+import Foreign.Marshal.Utils (copyBytes)
+import Foreign.Ptr (Ptr, castPtr)
+import Foreign.Storable (pokeByteOff)
+import qualified GHC.Exts as Exts
+import GHC.Exts (Int#, MutableByteArray#, State#, (+#), (*#))
+import GHC.IO (unIO, unsafeDupablePerformIO)
+import GHC.Word (Word32(..))
import Prelude hiding (lookup)
-- | A 256-bit key.
@@ -55,8 +69,28 @@ key bs
| BS.length bs == 32 = Just (Key bs)
| otherwise = Nothing
--- | A node's commitment: its 32-byte hash, and its sum.
-data Pair = Pair !BS.ByteString {-# UNPACK #-} !Word64
+-- | A 256-bit hash.
+data Hash = Hash
+ {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
+ {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
+ deriving (Eq, Ord, Show)
+
+-- | Parse a 32-byte hash.
+parse_hash :: BS.ByteString -> Maybe Hash
+parse_hash bs
+ | BS.length bs == 32 = Just (unsafe_hash bs)
+ | otherwise = Nothing
+
+-- | Serialize a hash to 32 bytes.
+serialize_hash :: Hash -> BS.ByteString
+serialize_hash (Hash a b c d) = BI.unsafeCreate 32 $ \p -> do
+ poke_be64 p 00 a
+ poke_be64 p 08 b
+ poke_be64 p 16 c
+ poke_be64 p 24 d
+
+-- | A node's commitment: its hash, and its sum.
+data Pair = Pair {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
deriving (Eq, Show)
-- | A merkle-sum sparse merkle tree.
@@ -65,21 +99,158 @@ data Pair = Pair !BS.ByteString {-# UNPACK #-} !Word64
-- 'Empty', so a tree holding n leaves has at most 256 * n branches.
data Tree =
Empty
- | Leaf !Pair !BS.ByteString
- | Node !Tree !Pair !Tree
+ | Leaf {-# UNPACK #-} !Pair !BS.ByteString
+ | Node !Tree {-# UNPACK #-} !Pair !Tree
deriving (Eq, Show)
+-- bytes ----------------------------------------------------------------------
+
+-- read a hash from 32 bytes; callers check the length
+unsafe_hash :: BS.ByteString -> Hash
+unsafe_hash bs = Hash (be64 00) (be64 08) (be64 16) (be64 24) where
+ be64 i =
+ byte i `unsafeShiftL` 56 .|. byte (i + 1) `unsafeShiftL` 48
+ .|. byte (i + 2) `unsafeShiftL` 40 .|. byte (i + 3) `unsafeShiftL` 32
+ .|. byte (i + 4) `unsafeShiftL` 24 .|. byte (i + 5) `unsafeShiftL` 16
+ .|. byte (i + 6) `unsafeShiftL` 08 .|. byte (i + 7)
+ byte i = fromIntegral (BU.unsafeIndex bs i) :: Word64
+{-# INLINE unsafe_hash #-}
+
+poke_be64 :: Ptr Word8 -> Int -> Word64 -> IO ()
+poke_be64 p i w = do
+ pokeByteOff p (i + 0) (fromIntegral (w `unsafeShiftR` 56) :: Word8)
+ pokeByteOff p (i + 1) (fromIntegral (w `unsafeShiftR` 48) :: Word8)
+ pokeByteOff p (i + 2) (fromIntegral (w `unsafeShiftR` 40) :: Word8)
+ pokeByteOff p (i + 3) (fromIntegral (w `unsafeShiftR` 32) :: Word8)
+ pokeByteOff p (i + 4) (fromIntegral (w `unsafeShiftR` 24) :: Word8)
+ pokeByteOff p (i + 5) (fromIntegral (w `unsafeShiftR` 16) :: Word8)
+ pokeByteOff p (i + 6) (fromIntegral (w `unsafeShiftR` 08) :: Word8)
+ pokeByteOff p (i + 7) (fromIntegral w :: Word8)
+{-# INLINE poke_be64 #-}
+
-- hashing --------------------------------------------------------------------
-- sha256(value || sum)
-hash_leaf :: BS.ByteString -> Word64 -> BS.ByteString
-hash_leaf v s = SHA256.hash_lazy . BSB.toLazyByteString $
- BSB.byteString v <> BSB.word64BE s
+hash_leaf :: BS.ByteString -> Word64 -> Hash
+hash_leaf v s = unsafe_hash . SHA256.hash $
+ BI.unsafeCreate (l + 8) $ \p -> do
+ BU.unsafeUseAsCString v $ \q -> copyBytes p (castPtr q) l
+ poke_be64 p l s
+ where
+ l = BS.length v
-- sha256(left || right || sum)
-hash_node :: BS.ByteString -> BS.ByteString -> Word64 -> BS.ByteString
-hash_node l r s = SHA256.hash_lazy . BSB.toLazyByteString $
- BSB.byteString l <> BSB.byteString r <> BSB.word64BE s
+--
+-- the 72-byte message is exactly two blocks: left || right, then
+-- sum || 0x80 || 0^44 || 576 (the message length in bits, big-endian)
+hash_node :: Hash -> Hash -> Word64 -> Hash
+hash_node l r s
+ | native = hash_node_native l r s
+ | otherwise = hash_node_pure l r s
+{-# INLINE hash_node #-}
+
+-- ppad-sha256's hardware block function, and its availability check;
+-- the block function updates eight native-endian state words in
+-- place, given sixteen native-endian message words
+foreign import ccall unsafe "sha256_block_native"
+ c_sha256_block
+ :: MutableByteArray# Exts.RealWorld
+ -> MutableByteArray# Exts.RealWorld
+ -> IO ()
+
+foreign import ccall unsafe "sha256_native_available"
+ c_sha256_native_available :: IO CInt
+
+native :: Bool
+native = unsafeDupablePerformIO c_sha256_native_available /= 0
+{-# NOINLINE native #-}
+
+-- initial SHA-256 state
+iv :: Hash
+iv = Hash
+ 0x6a09e667bb67ae85 0x3c6ef372a54ff53a
+ 0x510e527f9b05688c 0x1f83d9ab5be0cd19
+
+hash_node_native :: Hash -> Hash -> Word64 -> Hash
+hash_node_native l r s = case Exts.runRW# go of
+ (# _, h #) -> h
+ where
+ go s0 =
+ case Exts.newByteArray# 32# s0 of { (# s1, st #) ->
+ case Exts.newByteArray# 64# s1 of { (# s2, bk #) ->
+ case put_hash st 0# iv s2 of { s3 ->
+ case put_hash bk 0# l s3 of { s4 ->
+ case put_hash bk 4# r s4 of { s5 ->
+ case unIO (c_sha256_block st bk) s5 of { (# s6, () #) ->
+ case put_w64 bk 0# s s6 of { s7 ->
+ case Exts.writeWord32Array# bk 2# (w32 0x80000000) s7 of { s8 ->
+ case Exts.setByteArray# bk 12# 48# 0# s8 of { s9 ->
+ case Exts.writeWord32Array# bk 15# (w32 576) s9 of { s10 ->
+ case unIO (c_sha256_block st bk) s10 of { (# s11, () #) ->
+ get_hash st s11 }}}}}}}}}}}
+
+hash_node_pure :: Hash -> Hash -> Word64 -> Hash
+hash_node_pure (Hash a0 a1 a2 a3) (Hash b0 b1 b2 b3) s =
+ let !r0 = SHA256I.iv ()
+ !r1 = SHA256I.update r0 $ SHA256I.B
+ (hi a0) (lo a0) (hi a1) (lo a1) (hi a2) (lo a2) (hi a3) (lo a3)
+ (hi b0) (lo b0) (hi b1) (lo b1) (hi b2) (lo b2) (hi b3) (lo b3)
+ !(SHA256I.R x0 x1 x2 x3 x4 x5 x6 x7) = SHA256I.update r1 $ SHA256I.B
+ (hi s) (lo s) (w32 0x80000000) z z z z z z z z z z z z (w32 576)
+ in Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7)
+ where
+ z = w32 0
+
+-- words ----------------------------------------------------------------------
+
+w32 :: Word -> Exts.Word32#
+w32 (Exts.W# w) = Exts.wordToWord32# w
+{-# INLINE w32 #-}
+
+hi :: Word64 -> Exts.Word32#
+hi w = case fromIntegral (w `unsafeShiftR` 32) of W32# x -> x
+{-# INLINE hi #-}
+
+lo :: Word64 -> Exts.Word32#
+lo w = case fromIntegral w of W32# x -> x
+{-# INLINE lo #-}
+
+w64 :: Exts.Word32# -> Exts.Word32# -> Word64
+w64 h l = fromIntegral (W32# h) `unsafeShiftL` 32 .|. fromIntegral (W32# l)
+{-# INLINE w64 #-}
+
+-- write a word as two 32-bit words, high first, at a 64-bit offset
+put_w64
+ :: MutableByteArray# s -> Int# -> Word64 -> State# s -> State# s
+put_w64 a i w s0 =
+ case Exts.writeWord32Array# a (2# *# i) (hi w) s0 of
+ s1 -> Exts.writeWord32Array# a (2# *# i +# 1#) (lo w) s1
+{-# INLINE put_w64 #-}
+
+-- write a hash at a 64-bit offset
+put_hash
+ :: MutableByteArray# s -> Int# -> Hash -> State# s -> State# s
+put_hash a i (Hash w0 w1 w2 w3) s0 =
+ case put_w64 a i w0 s0 of { s1 ->
+ case put_w64 a (i +# 1#) w1 s1 of { s2 ->
+ case put_w64 a (i +# 2#) w2 s2 of { s3 ->
+ put_w64 a (i +# 3#) w3 s3 }}}
+{-# INLINE put_hash #-}
+
+-- read a hash from eight 32-bit words
+get_hash :: MutableByteArray# s -> State# s -> (# State# s, Hash #)
+get_hash a s0 =
+ case Exts.readWord32Array# a 0# s0 of { (# s1, x0 #) ->
+ case Exts.readWord32Array# a 1# s1 of { (# s2, x1 #) ->
+ case Exts.readWord32Array# a 2# s2 of { (# s3, x2 #) ->
+ case Exts.readWord32Array# a 3# s3 of { (# s4, x3 #) ->
+ case Exts.readWord32Array# a 4# s4 of { (# s5, x4 #) ->
+ case Exts.readWord32Array# a 5# s5 of { (# s6, x5 #) ->
+ case Exts.readWord32Array# a 6# s6 of { (# s7, x6 #) ->
+ case Exts.readWord32Array# a 7# s7 of { (# s8, x7 #) ->
+ (# s8, Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7) #)
+ }}}}}}}}
+{-# INLINE get_hash #-}
-- structure ------------------------------------------------------------------
@@ -87,22 +258,26 @@ hash_node l r s = SHA256.hash_lazy . BSB.toLazyByteString $
height :: Int
height = 256
--- commitments of empty subtrees, indexed by depth
-empties :: PA.Array Pair
-empties = PA.arrayFromListN (height + 1) . reverse . take (height + 1) $
- iterate up (Pair (hash_leaf mempty 0) 0)
- where
- up (Pair h _) = Pair (hash_node h h 0) 0
+-- hashes of empty subtrees, four words per depth
+empties :: PA.PrimArray Word64
+empties = PA.primArrayFromListN (4 * (height + 1))
+ . concatMap (\(Hash a b c d) -> [a, b, c, d])
+ . reverse . take (height + 1) $
+ iterate (\h -> hash_node h h 0) (hash_leaf mempty 0)
+{-# NOINLINE empties #-}
-- commitment of a subtree at the given depth
commit :: Int -> Tree -> Pair
-commit d Empty = PA.indexArray empties d
+commit d Empty = Pair (Hash (ix 0) (ix 1) (ix 2) (ix 3)) 0 where
+ ix i = PA.indexPrimArray empties (4 * d + i)
commit _ (Leaf p _) = p
commit _ (Node _ p _) = p
+{-# INLINE commit #-}
-- path bit at the given depth; LSB-first within each byte
bit :: Key -> Int -> Bool
bit (Key k) d = testBit (BU.unsafeIndex k (d `quot` 8)) (d `rem` 8)
+{-# INLINE bit #-}
-- an empty value with zero sum is the empty leaf
leaf :: BS.ByteString -> Word64 -> Tree
@@ -118,23 +293,24 @@ node d l r =
!(Pair hr sr) = commit (d + 1) r
!s = sl + sr
in Node l (Pair (hash_node hl hr s) s) r
+{-# INLINE node #-}
-- children of a subtree above leaf depth
-children :: Tree -> (Tree, Tree)
-children (Node l _ r) = (l, r)
-children Empty = (Empty, Empty)
-children (Leaf _ _) = (Empty, Empty) -- unreachable above leaf depth
+children :: Tree -> (# Tree, Tree #)
+children (Node l _ r) = (# l, r #)
+children Empty = (# Empty, Empty #)
+children (Leaf _ _) = (# Empty, Empty #) -- unreachable above leaf depth
+{-# INLINE children #-}
-- replace the subtree at the given key's leaf
update :: Key -> Tree -> Tree -> Tree
update k new = go 0 where
go !d t
| d == height = new
- | otherwise =
- let (l, r) = children t
- in if bit k d
- then node d l (go (d + 1) r)
- else node d (go (d + 1) l) r
+ | otherwise = case children t of
+ (# l, r #)
+ | bit k d -> node d l (go (d + 1) r)
+ | otherwise -> node d (go (d + 1) l) r
-- tree -----------------------------------------------------------------------
@@ -183,26 +359,23 @@ prove :: Key -> Tree -> Proof
prove k = Proof . go 0 [] where
go !d acc t
| d == height = acc
- | otherwise =
- let (l, r) = children t
- (next, sib) = if bit k d then (r, l) else (l, r)
- in go (d + 1) (commit (d + 1) sib : acc) next
+ | otherwise = case children t of
+ (# l, r #)
+ | bit k d -> go (d + 1) (commit (d + 1) l : acc) r
+ | otherwise -> go (d + 1) (commit (d + 1) r : acc) l
-- | Verify that a value and sum sit at a key, under a root.
--
-- An empty value with zero sum verifies the key's exclusion. Proofs
-- whose branch sums overflow are rejected.
verify :: Key -> BS.ByteString -> Word64 -> Proof -> Pair -> Bool
-verify k v s (Proof sibs) r
- | length sibs /= height = False
- | otherwise = foldM step (Pair (hash_leaf v s) s) levels == Just r
- where
- levels = zip [height - 1, height - 2 .. 0] sibs
-
- step (Pair h hs) (d, Pair g gs)
- | bit k d = parent g gs h hs
- | otherwise = parent h hs g gs
-
- parent hl sl hr sr
- | sr > maxBound - sl = Nothing
- | otherwise = let !t = sl + sr in Just (Pair (hash_node hl hr t) t)
+verify k v s (Proof sibs) r = go (height - 1) (hash_leaf v s) s sibs where
+ go !d !h !hs ps = case ps of
+ [] -> d == -1 && Pair h hs == r
+ Pair g gs : rest
+ | d < 0 || gs > maxBound - hs -> False
+ | otherwise ->
+ let !t = hs + gs
+ !p | bit k d = hash_node g h t
+ | otherwise = hash_node h g t
+ in go (d - 1) p t rest
diff --git a/test/Main.hs b/test/Main.hs
@@ -42,6 +42,12 @@ units = testGroup "units" [
assertBool "31" (not (isJust (key (BS.replicate 31 0))))
assertBool "32" (isJust (key (BS.replicate 32 0)))
assertBool "33" (not (isJust (key (BS.replicate 33 0))))
+ , testCase "hashes are 32 bytes" $ do
+ assertBool "31" (not (isJust (parse_hash (BS.replicate 31 0))))
+ assertBool "33" (not (isJust (parse_hash (BS.replicate 33 0))))
+ , Q.testProperty "serialize_hash . parse_hash ~ id" $
+ Q.forAll (BS.pack <$> Q.vector 32) $ \bs ->
+ fmap serialize_hash (parse_hash bs) Q.=== Just bs
, testCase "an empty value with zero sum is the empty leaf" $
case key (BS.replicate 32 0) of
Nothing -> assertFailure "key"
diff --git a/test/Vectors.hs b/test/Vectors.hs
@@ -119,7 +119,7 @@ instance A.FromJSON Leaf where
instance A.FromJSON Valid where
parseJSON = A.withObject "Valid" $ \o -> do
- h <- o .: "root_hash" >>= parse_hex
+ h <- o .: "root_hash" >>= parse_hex >>= parse_digest
s <- o .: "root_sum" >>= parse_sum
Valid (Pair h s)
<$> (list o "inserted_leaves" >>= traverse parse_key)
@@ -146,6 +146,9 @@ parse_case = A.withObject "ProofCase" $ \o -> (,)
parse_hex :: String -> AT.Parser BS.ByteString
parse_hex s = maybe (fail ("bad hex: " <> s)) pure (B16.decode (B8.pack s))
+parse_digest :: BS.ByteString -> AT.Parser Hash
+parse_digest bs = maybe (fail "bad hash") pure (parse_hash bs)
+
parse_key :: String -> AT.Parser Key
parse_key s = parse_hex s >>= maybe (fail ("bad key: " <> s)) pure . key
@@ -187,8 +190,9 @@ decompress bs0 = do
| otherwise = do
let (h, rest0) = BS.splitAt 32 bs
(s, rest1) = BS.splitAt 8 rest0
+ d <- parse_hash h
(ps, rest) <- siblings (n - 1) rest1
- pure (Pair h (be s) : ps, rest)
+ pure (Pair d (be s) : ps, rest)
fill (b:bs) ns (e:es)
| b = (e :) <$> fill bs ns es