mssmt

A high-performance Merkle-Sum Sparse Merkle Tree.
git clone git://git.jtobin.io/mssmt.git
Log | Files | Refs | README | LICENSE | git.jtobin.io

Hash.hs (13155B)


      1 {-# OPTIONS_HADDOCK hide #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 {-# LANGUAGE MagicHash #-}
      4 {-# LANGUAGE UnboxedTuples #-}
      5 {-# LANGUAGE UnliftedFFITypes #-}
      6 
      7 -- |
      8 -- Module: Data.MSSMT.Hash
      9 -- Copyright: (c) 2026 Jared Tobin
     10 -- License: MIT
     11 -- Maintainer: Jared Tobin <jared@jtobin.io>
     12 --
     13 -- MS-SMT hashing.
     14 
     15 module Data.MSSMT.Hash (
     16   -- * Hashes
     17     Hash(..)
     18   , parse_hash
     19   , serialize_hash
     20   , unsafe_hash
     21 
     22   -- * Leaf and branch hashes
     23   , native
     24   , hash_value
     25   , hash_leaf_split
     26   , hash_leaf_aggregate
     27   , hash_node_split
     28   , hash_node_split_native
     29   , hash_node_split_pure
     30   , hash_node_aggregate
     31   , hash_node_aggregate_native
     32   , hash_node_aggregate_pure
     33 
     34   -- * Schemes
     35   , Scheme(..)
     36   , hash_branch
     37 
     38   -- * Scratch arrays
     39   , Buffer
     40   , with_scratch
     41   , hash_branch#
     42   , hash_leaf_split#
     43   ) where
     44 
     45 import qualified Crypto.Hash.SHA256 as SHA256
     46 import qualified Crypto.Hash.SHA256.Internal as SHA256I
     47 import Data.Bits (unsafeShiftL, unsafeShiftR, (.|.))
     48 import qualified Data.ByteString as BS
     49 import qualified Data.ByteString.Internal as BI
     50 import qualified Data.ByteString.Unsafe as BU
     51 import Data.Word (Word8, Word64)
     52 import Foreign.C.Types (CInt(..))
     53 import Foreign.Marshal.Utils (copyBytes)
     54 import Foreign.Ptr (Ptr, castPtr)
     55 import Foreign.Storable (pokeByteOff)
     56 import qualified GHC.Exts as Exts
     57 import GHC.Exts (Int#, MutableByteArray#, State#, (+#), (*#))
     58 import GHC.IO (unIO, unsafeDupablePerformIO)
     59 import GHC.Word (Word32(..))
     60 
     61 -- | A 256-bit hash.
     62 data Hash = Hash
     63   {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
     64   {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
     65   deriving (Eq, Ord, Show)
     66 
     67 -- | Parse a 32-byte hash.
     68 parse_hash :: BS.ByteString -> Maybe Hash
     69 parse_hash bs
     70   | BS.length bs == 32 = Just (unsafe_hash bs)
     71   | otherwise = Nothing
     72 
     73 -- | Serialize a hash to 32 bytes.
     74 serialize_hash :: Hash -> BS.ByteString
     75 serialize_hash (Hash a b c d) = BI.unsafeCreate 32 $ \p -> do
     76   poke_be64 p 00 a
     77   poke_be64 p 08 b
     78   poke_be64 p 16 c
     79   poke_be64 p 24 d
     80 
     81 -- bytes ----------------------------------------------------------------------
     82 
     83 -- | Read a hash from 32 bytes. Callers check the length.
     84 unsafe_hash :: BS.ByteString -> Hash
     85 unsafe_hash bs = Hash (be64 00) (be64 08) (be64 16) (be64 24) where
     86   be64 i =
     87         byte i       `unsafeShiftL` 56 .|. byte (i + 1) `unsafeShiftL` 48
     88     .|. byte (i + 2) `unsafeShiftL` 40 .|. byte (i + 3) `unsafeShiftL` 32
     89     .|. byte (i + 4) `unsafeShiftL` 24 .|. byte (i + 5) `unsafeShiftL` 16
     90     .|. byte (i + 6) `unsafeShiftL` 08 .|. byte (i + 7)
     91   byte i = fromIntegral (BU.unsafeIndex bs i) :: Word64
     92 {-# INLINE unsafe_hash #-}
     93 
     94 poke_be64 :: Ptr Word8 -> Int -> Word64 -> IO ()
     95 poke_be64 p i w = do
     96   pokeByteOff p (i + 0) (fromIntegral (w `unsafeShiftR` 56) :: Word8)
     97   pokeByteOff p (i + 1) (fromIntegral (w `unsafeShiftR` 48) :: Word8)
     98   pokeByteOff p (i + 2) (fromIntegral (w `unsafeShiftR` 40) :: Word8)
     99   pokeByteOff p (i + 3) (fromIntegral (w `unsafeShiftR` 32) :: Word8)
    100   pokeByteOff p (i + 4) (fromIntegral (w `unsafeShiftR` 24) :: Word8)
    101   pokeByteOff p (i + 5) (fromIntegral (w `unsafeShiftR` 16) :: Word8)
    102   pokeByteOff p (i + 6) (fromIntegral (w `unsafeShiftR` 08) :: Word8)
    103   pokeByteOff p (i + 7) (fromIntegral w :: Word8)
    104 {-# INLINE poke_be64 #-}
    105 
    106 -- hashing --------------------------------------------------------------------
    107 
    108 -- | sha256(value).
    109 hash_value :: BS.ByteString -> Hash
    110 hash_value = unsafe_hash . SHA256.hash
    111 
    112 -- | sha256(key || value hash || sum), a split leaf's hash.
    113 --
    114 --   The 72-byte message has the same two-block layout as that of
    115 --   'hash_node_aggregate'.
    116 hash_leaf_split :: Hash -> Hash -> Word64 -> Hash
    117 hash_leaf_split = hash_node_aggregate
    118 {-# INLINE hash_leaf_split #-}
    119 
    120 -- | sha256(value || sum), an aggregate leaf's hash.
    121 hash_leaf_aggregate :: BS.ByteString -> Word64 -> Hash
    122 hash_leaf_aggregate v s = unsafe_hash . SHA256.hash $
    123     BI.unsafeCreate (l + 8) $ \p -> do
    124       BU.unsafeUseAsCString v $ \q -> copyBytes p (castPtr q) l
    125       poke_be64 p l s
    126   where
    127     l = BS.length v
    128 
    129 -- | sha256(left || left sum || right || right sum).
    130 --
    131 --   The 80-byte message is exactly two blocks: left || left sum || the
    132 --   first 24 bytes of right, then the last 8 bytes of right || right
    133 --   sum || 0x80 || 0^39 || 640 (the message length in bits, as a
    134 --   big-endian 64-bit word).
    135 hash_node_split :: Hash -> Word64 -> Hash -> Word64 -> Hash
    136 hash_node_split l sl r sr
    137   | native    = hash_node_split_native l sl r sr
    138   | otherwise = hash_node_split_pure l sl r sr
    139 {-# INLINE hash_node_split #-}
    140 
    141 -- | sha256(left || right || sum), the Taproot Assets branch hash.
    142 --
    143 --   The 72-byte message is exactly two blocks: left || right, then
    144 --   sum || 0x80 || 0^47 || 576 (the message length in bits, as a
    145 --   big-endian 64-bit word).
    146 hash_node_aggregate :: Hash -> Hash -> Word64 -> Hash
    147 hash_node_aggregate l r s
    148   | native    = hash_node_aggregate_native l r s
    149   | otherwise = hash_node_aggregate_pure l r s
    150 {-# INLINE hash_node_aggregate #-}
    151 
    152 -- ppad-sha256's hardware block function, and its availability check;
    153 -- the block function updates eight native-endian state words in
    154 -- place, given sixteen native-endian message words
    155 foreign import ccall unsafe "sha256_block_native"
    156   c_sha256_block
    157     :: MutableByteArray# Exts.RealWorld
    158     -> MutableByteArray# Exts.RealWorld
    159     -> IO ()
    160 
    161 foreign import ccall unsafe "sha256_native_available"
    162   c_sha256_native_available :: IO CInt
    163 
    164 -- | Are hardware SHA-256 instructions available?
    165 native :: Bool
    166 native = unsafeDupablePerformIO c_sha256_native_available /= 0
    167 {-# NOINLINE native #-}
    168 
    169 -- initial SHA-256 state
    170 iv :: Hash
    171 iv = Hash
    172   0x6a09e667bb67ae85 0x3c6ef372a54ff53a
    173   0x510e527f9b05688c 0x1f83d9ab5be0cd19
    174 
    175 -- the hardware block function's state and block arrays
    176 type Buffer = MutableByteArray# Exts.RealWorld
    177 
    178 -- run a computation over fresh state and block arrays
    179 with_scratch
    180   :: (Buffer -> Buffer -> State# Exts.RealWorld
    181         -> (# State# Exts.RealWorld, a #))
    182   -> a
    183 with_scratch f = case Exts.runRW# go of
    184     (# _, a #) -> a
    185   where
    186     go s0 =
    187       case Exts.newByteArray# 32# s0 of { (# s1, st #) ->
    188       case Exts.newByteArray# 64# s1 of { (# s2, bk #) ->
    189       f st bk s2 }}
    190 {-# INLINE with_scratch #-}
    191 
    192 -- | 'hash_node_split', via hardware SHA-256. Callers check 'native'.
    193 hash_node_split_native :: Hash -> Word64 -> Hash -> Word64 -> Hash
    194 hash_node_split_native l sl r sr =
    195   with_scratch (\st bk -> hash_node_split# st bk l sl r sr)
    196 
    197 -- 'hash_node_split' via hardware SHA-256, over the given state and
    198 -- block arrays, both of which it overwrites in full. callers check
    199 -- 'native'
    200 hash_node_split#
    201   :: Buffer -> Buffer -> Hash -> Word64 -> Hash -> Word64
    202   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
    203 hash_node_split# st bk l sl (Hash b0 b1 b2 b3) sr s0 =
    204   case put_hash st 0# iv s0 of { s1 ->
    205   case put_hash bk 0# l s1 of { s2 ->
    206   case put_w64 bk 4# sl s2 of { s3 ->
    207   case put_w64 bk 5# b0 s3 of { s4 ->
    208   case put_w64 bk 6# b1 s4 of { s5 ->
    209   case put_w64 bk 7# b2 s5 of { s6 ->
    210   case unIO (c_sha256_block st bk) s6 of { (# s7, () #) ->
    211   case put_w64 bk 0# b3 s7 of { s8 ->
    212   case put_w64 bk 1# sr s8 of { s9 ->
    213   case Exts.writeWord32Array# bk 4# (w32 0x80000000) s9 of { s10 ->
    214   case Exts.setByteArray# bk 20# 40# 0# s10 of { s11 ->
    215   case Exts.writeWord32Array# bk 15# (w32 640) s11 of { s12 ->
    216   case unIO (c_sha256_block st bk) s12 of { (# s13, () #) ->
    217   get_hash st s13 }}}}}}}}}}}}}
    218 {-# INLINE hash_node_split# #-}
    219 
    220 -- | 'hash_node_split', in pure Haskell.
    221 hash_node_split_pure :: Hash -> Word64 -> Hash -> Word64 -> Hash
    222 hash_node_split_pure (Hash a0 a1 a2 a3) sl (Hash b0 b1 b2 b3) sr =
    223   let !r0 = SHA256I.iv ()
    224       !r1 = SHA256I.update r0 $ SHA256I.B
    225         (hi a0) (lo a0) (hi a1) (lo a1) (hi a2) (lo a2) (hi a3) (lo a3)
    226         (hi sl) (lo sl) (hi b0) (lo b0) (hi b1) (lo b1) (hi b2) (lo b2)
    227       !(SHA256I.R x0 x1 x2 x3 x4 x5 x6 x7) = SHA256I.update r1 $ SHA256I.B
    228         (hi b3) (lo b3) (hi sr) (lo sr) (w32 0x80000000)
    229         z z z z z z z z z z (w32 640)
    230   in  Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7)
    231   where
    232     z = w32 0
    233 
    234 -- | 'hash_node_aggregate', via hardware SHA-256. Callers check 'native'.
    235 hash_node_aggregate_native :: Hash -> Hash -> Word64 -> Hash
    236 hash_node_aggregate_native l r s =
    237   with_scratch (\st bk -> hash_node_aggregate# st bk l r s)
    238 
    239 -- 'hash_node_aggregate' via hardware SHA-256, over the given state and
    240 -- block arrays, both of which it overwrites in full. callers check
    241 -- 'native'
    242 hash_node_aggregate#
    243   :: Buffer -> Buffer -> Hash -> Hash -> Word64
    244   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
    245 hash_node_aggregate# st bk l r s s0 =
    246   case put_hash st 0# iv s0 of { s1 ->
    247   case put_hash bk 0# l s1 of { s2 ->
    248   case put_hash bk 4# r s2 of { s3 ->
    249   case unIO (c_sha256_block st bk) s3 of { (# s4, () #) ->
    250   case put_w64 bk 0# s s4 of { s5 ->
    251   case Exts.writeWord32Array# bk 2# (w32 0x80000000) s5 of { s6 ->
    252   case Exts.setByteArray# bk 12# 48# 0# s6 of { s7 ->
    253   case Exts.writeWord32Array# bk 15# (w32 576) s7 of { s8 ->
    254   case unIO (c_sha256_block st bk) s8 of { (# s9, () #) ->
    255   get_hash st s9 }}}}}}}}}
    256 {-# INLINE hash_node_aggregate# #-}
    257 
    258 -- | 'hash_node_aggregate', in pure Haskell.
    259 hash_node_aggregate_pure :: Hash -> Hash -> Word64 -> Hash
    260 hash_node_aggregate_pure (Hash a0 a1 a2 a3) (Hash b0 b1 b2 b3) s =
    261   let !r0 = SHA256I.iv ()
    262       !r1 = SHA256I.update r0 $ SHA256I.B
    263         (hi a0) (lo a0) (hi a1) (lo a1) (hi a2) (lo a2) (hi a3) (lo a3)
    264         (hi b0) (lo b0) (hi b1) (lo b1) (hi b2) (lo b2) (hi b3) (lo b3)
    265       !(SHA256I.R x0 x1 x2 x3 x4 x5 x6 x7) = SHA256I.update r1 $ SHA256I.B
    266         (hi s) (lo s) (w32 0x80000000) z z z z z z z z z z z z (w32 576)
    267   in  Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7)
    268   where
    269     z = w32 0
    270 
    271 -- words ----------------------------------------------------------------------
    272 
    273 w32 :: Word -> Exts.Word32#
    274 w32 (Exts.W# w) = Exts.wordToWord32# w
    275 {-# INLINE w32 #-}
    276 
    277 hi :: Word64 -> Exts.Word32#
    278 hi w = case fromIntegral (w `unsafeShiftR` 32) of W32# x -> x
    279 {-# INLINE hi #-}
    280 
    281 lo :: Word64 -> Exts.Word32#
    282 lo w = case fromIntegral w of W32# x -> x
    283 {-# INLINE lo #-}
    284 
    285 w64 :: Exts.Word32# -> Exts.Word32# -> Word64
    286 w64 h l = fromIntegral (W32# h) `unsafeShiftL` 32 .|. fromIntegral (W32# l)
    287 {-# INLINE w64 #-}
    288 
    289 -- write a word as two 32-bit words, high first, at a 64-bit offset
    290 put_w64
    291   :: MutableByteArray# s -> Int# -> Word64 -> State# s -> State# s
    292 put_w64 a i w s0 =
    293   case Exts.writeWord32Array# a (2# *# i) (hi w) s0 of
    294     s1 -> Exts.writeWord32Array# a (2# *# i +# 1#) (lo w) s1
    295 {-# INLINE put_w64 #-}
    296 
    297 -- write a hash at a 64-bit offset
    298 put_hash
    299   :: MutableByteArray# s -> Int# -> Hash -> State# s -> State# s
    300 put_hash a i (Hash w0 w1 w2 w3) s0 =
    301   case put_w64 a i w0 s0 of { s1 ->
    302   case put_w64 a (i +# 1#) w1 s1 of { s2 ->
    303   case put_w64 a (i +# 2#) w2 s2 of { s3 ->
    304   put_w64 a (i +# 3#) w3 s3 }}}
    305 {-# INLINE put_hash #-}
    306 
    307 -- read a hash from eight 32-bit words
    308 get_hash :: MutableByteArray# s -> State# s -> (# State# s, Hash #)
    309 get_hash a s0 =
    310   case Exts.readWord32Array# a 0# s0 of { (# s1, x0 #) ->
    311   case Exts.readWord32Array# a 1# s1 of { (# s2, x1 #) ->
    312   case Exts.readWord32Array# a 2# s2 of { (# s3, x2 #) ->
    313   case Exts.readWord32Array# a 3# s3 of { (# s4, x3 #) ->
    314   case Exts.readWord32Array# a 4# s4 of { (# s5, x4 #) ->
    315   case Exts.readWord32Array# a 5# s5 of { (# s6, x5 #) ->
    316   case Exts.readWord32Array# a 6# s6 of { (# s7, x6 #) ->
    317   case Exts.readWord32Array# a 7# s7 of { (# s8, x7 #) ->
    318   (# s8, Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7) #)
    319   }}}}}}}}
    320 {-# INLINE get_hash #-}
    321 
    322 -- schemes --------------------------------------------------------------------
    323 
    324 -- | A branch hashing scheme.
    325 data Scheme =
    326     -- | Branches commit to each child's hash and sum, via 'hash_node_split'.
    327     Split
    328     -- | Branches commit to their children's hashes and the sum of their
    329     --   sums, via 'hash_node_aggregate', as in Taproot Assets.
    330   | Aggregate
    331   deriving (Eq, Show)
    332 
    333 -- branch hash under a scheme; callers rule out sum overflow
    334 hash_branch :: Scheme -> Hash -> Word64 -> Hash -> Word64 -> Hash
    335 hash_branch Split l sl r sr = hash_node_split l sl r sr
    336 hash_branch Aggregate l sl r sr = hash_node_aggregate l r (sl + sr)
    337 {-# INLINE hash_branch #-}
    338 
    339 -- 'hash_branch', over the given state and block arrays where hardware
    340 -- SHA-256 is available
    341 hash_branch#
    342   :: Scheme -> Buffer -> Buffer -> Hash -> Word64 -> Hash -> Word64
    343   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
    344 hash_branch# sc st bk l sl r sr s0
    345   | native = case sc of
    346       Split     -> hash_node_split# st bk l sl r sr s0
    347       Aggregate -> hash_node_aggregate# st bk l r (sl + sr) s0
    348   | otherwise = (# s0, hash_branch sc l sl r sr #)
    349 {-# INLINE hash_branch# #-}
    350 
    351 -- | 'hash_leaf_split', over the given state and block arrays where
    352 --   hardware SHA-256 is available.
    353 hash_leaf_split#
    354   :: Buffer -> Buffer -> Hash -> Hash -> Word64
    355   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
    356 hash_leaf_split# st bk k vh s s0
    357   | native    = hash_node_aggregate# st bk k vh s s0
    358   | otherwise = (# s0, hash_leaf_split k vh s #)
    359 {-# INLINE hash_leaf_split# #-}