packages feed

mssmt-0.1.0: lib/Data/MSSMT/Hash.hs

{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UnliftedFFITypes #-}

-- |
-- Module: Data.MSSMT.Hash
-- Copyright: (c) 2026 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@jtobin.io>
--
-- MS-SMT hashing.

module Data.MSSMT.Hash (
  -- * Hashes
    Hash(..)
  , parse_hash
  , serialize_hash
  , unsafe_hash

  -- * Leaf and branch hashes
  , native
  , hash_value
  , hash_leaf_split
  , hash_leaf_aggregate
  , hash_node_split
  , hash_node_split_native
  , hash_node_split_pure
  , hash_node_aggregate
  , hash_node_aggregate_native
  , hash_node_aggregate_pure

  -- * Schemes
  , Scheme(..)
  , hash_branch

  -- * Scratch arrays
  , Buffer
  , with_scratch
  , hash_branch#
  , hash_leaf_split#
  ) where

import qualified Crypto.Hash.SHA256 as SHA256
import qualified Crypto.Hash.SHA256.Internal as SHA256I
import Data.Bits (unsafeShiftL, unsafeShiftR, (.|.))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
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(..))

-- | 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

-- 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).
hash_value :: BS.ByteString -> Hash
hash_value = unsafe_hash . SHA256.hash

-- | sha256(key || value hash || sum), a split leaf's hash.
--
--   The 72-byte message has the same two-block layout as that of
--   'hash_node_aggregate'.
hash_leaf_split :: Hash -> Hash -> Word64 -> Hash
hash_leaf_split = hash_node_aggregate
{-# INLINE hash_leaf_split #-}

-- | sha256(value || sum), an aggregate leaf's hash.
hash_leaf_aggregate :: BS.ByteString -> Word64 -> Hash
hash_leaf_aggregate 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 || left sum || right || right sum).
--
--   The 80-byte message is exactly two blocks: left || left sum || the
--   first 24 bytes of right, then the last 8 bytes of right || right
--   sum || 0x80 || 0^39 || 640 (the message length in bits, as a
--   big-endian 64-bit word).
hash_node_split :: Hash -> Word64 -> Hash -> Word64 -> Hash
hash_node_split l sl r sr
  | native    = hash_node_split_native l sl r sr
  | otherwise = hash_node_split_pure l sl r sr
{-# INLINE hash_node_split #-}

-- | sha256(left || right || sum), the Taproot Assets branch hash.
--
--   The 72-byte message is exactly two blocks: left || right, then
--   sum || 0x80 || 0^47 || 576 (the message length in bits, as a
--   big-endian 64-bit word).
hash_node_aggregate :: Hash -> Hash -> Word64 -> Hash
hash_node_aggregate l r s
  | native    = hash_node_aggregate_native l r s
  | otherwise = hash_node_aggregate_pure l r s
{-# INLINE hash_node_aggregate #-}

-- 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

-- | Are hardware SHA-256 instructions available?
native :: Bool
native = unsafeDupablePerformIO c_sha256_native_available /= 0
{-# NOINLINE native #-}

-- initial SHA-256 state
iv :: Hash
iv = Hash
  0x6a09e667bb67ae85 0x3c6ef372a54ff53a
  0x510e527f9b05688c 0x1f83d9ab5be0cd19

-- the hardware block function's state and block arrays
type Buffer = MutableByteArray# Exts.RealWorld

-- run a computation over fresh state and block arrays
with_scratch
  :: (Buffer -> Buffer -> State# Exts.RealWorld
        -> (# State# Exts.RealWorld, a #))
  -> a
with_scratch f = case Exts.runRW# go of
    (# _, a #) -> a
  where
    go s0 =
      case Exts.newByteArray# 32# s0 of { (# s1, st #) ->
      case Exts.newByteArray# 64# s1 of { (# s2, bk #) ->
      f st bk s2 }}
{-# INLINE with_scratch #-}

-- | 'hash_node_split', via hardware SHA-256. Callers check 'native'.
hash_node_split_native :: Hash -> Word64 -> Hash -> Word64 -> Hash
hash_node_split_native l sl r sr =
  with_scratch (\st bk -> hash_node_split# st bk l sl r sr)

-- 'hash_node_split' via hardware SHA-256, over the given state and
-- block arrays, both of which it overwrites in full. callers check
-- 'native'
hash_node_split#
  :: Buffer -> Buffer -> Hash -> Word64 -> Hash -> Word64
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
hash_node_split# st bk l sl (Hash b0 b1 b2 b3) sr s0 =
  case put_hash st 0# iv s0 of { s1 ->
  case put_hash bk 0# l s1 of { s2 ->
  case put_w64 bk 4# sl s2 of { s3 ->
  case put_w64 bk 5# b0 s3 of { s4 ->
  case put_w64 bk 6# b1 s4 of { s5 ->
  case put_w64 bk 7# b2 s5 of { s6 ->
  case unIO (c_sha256_block st bk) s6 of { (# s7, () #) ->
  case put_w64 bk 0# b3 s7 of { s8 ->
  case put_w64 bk 1# sr s8 of { s9 ->
  case Exts.writeWord32Array# bk 4# (w32 0x80000000) s9 of { s10 ->
  case Exts.setByteArray# bk 20# 40# 0# s10 of { s11 ->
  case Exts.writeWord32Array# bk 15# (w32 640) s11 of { s12 ->
  case unIO (c_sha256_block st bk) s12 of { (# s13, () #) ->
  get_hash st s13 }}}}}}}}}}}}}
{-# INLINE hash_node_split# #-}

-- | 'hash_node_split', in pure Haskell.
hash_node_split_pure :: Hash -> Word64 -> Hash -> Word64 -> Hash
hash_node_split_pure (Hash a0 a1 a2 a3) sl (Hash b0 b1 b2 b3) sr =
  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 sl) (lo sl) (hi b0) (lo b0) (hi b1) (lo b1) (hi b2) (lo b2)
      !(SHA256I.R x0 x1 x2 x3 x4 x5 x6 x7) = SHA256I.update r1 $ SHA256I.B
        (hi b3) (lo b3) (hi sr) (lo sr) (w32 0x80000000)
        z z z z z z z z z z (w32 640)
  in  Hash (w64 x0 x1) (w64 x2 x3) (w64 x4 x5) (w64 x6 x7)
  where
    z = w32 0

-- | 'hash_node_aggregate', via hardware SHA-256. Callers check 'native'.
hash_node_aggregate_native :: Hash -> Hash -> Word64 -> Hash
hash_node_aggregate_native l r s =
  with_scratch (\st bk -> hash_node_aggregate# st bk l r s)

-- 'hash_node_aggregate' via hardware SHA-256, over the given state and
-- block arrays, both of which it overwrites in full. callers check
-- 'native'
hash_node_aggregate#
  :: Buffer -> Buffer -> Hash -> Hash -> Word64
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
hash_node_aggregate# st bk l r s s0 =
  case put_hash st 0# iv s0 of { s1 ->
  case put_hash bk 0# l s1 of { s2 ->
  case put_hash bk 4# r s2 of { s3 ->
  case unIO (c_sha256_block st bk) s3 of { (# s4, () #) ->
  case put_w64 bk 0# s s4 of { s5 ->
  case Exts.writeWord32Array# bk 2# (w32 0x80000000) s5 of { s6 ->
  case Exts.setByteArray# bk 12# 48# 0# s6 of { s7 ->
  case Exts.writeWord32Array# bk 15# (w32 576) s7 of { s8 ->
  case unIO (c_sha256_block st bk) s8 of { (# s9, () #) ->
  get_hash st s9 }}}}}}}}}
{-# INLINE hash_node_aggregate# #-}

-- | 'hash_node_aggregate', in pure Haskell.
hash_node_aggregate_pure :: Hash -> Hash -> Word64 -> Hash
hash_node_aggregate_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 #-}

-- schemes --------------------------------------------------------------------

-- | A branch hashing scheme.
data Scheme =
    -- | Branches commit to each child's hash and sum, via 'hash_node_split'.
    Split
    -- | Branches commit to their children's hashes and the sum of their
    --   sums, via 'hash_node_aggregate', as in Taproot Assets.
  | Aggregate
  deriving (Eq, Show)

-- branch hash under a scheme; callers rule out sum overflow
hash_branch :: Scheme -> Hash -> Word64 -> Hash -> Word64 -> Hash
hash_branch Split l sl r sr = hash_node_split l sl r sr
hash_branch Aggregate l sl r sr = hash_node_aggregate l r (sl + sr)
{-# INLINE hash_branch #-}

-- 'hash_branch', over the given state and block arrays where hardware
-- SHA-256 is available
hash_branch#
  :: Scheme -> Buffer -> Buffer -> Hash -> Word64 -> Hash -> Word64
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
hash_branch# sc st bk l sl r sr s0
  | native = case sc of
      Split     -> hash_node_split# st bk l sl r sr s0
      Aggregate -> hash_node_aggregate# st bk l r (sl + sr) s0
  | otherwise = (# s0, hash_branch sc l sl r sr #)
{-# INLINE hash_branch# #-}

-- | 'hash_leaf_split', over the given state and block arrays where
--   hardware SHA-256 is available.
hash_leaf_split#
  :: Buffer -> Buffer -> Hash -> Hash -> Word64
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
hash_leaf_split# st bk k vh s s0
  | native    = hash_node_aggregate# st bk k vh s s0
  | otherwise = (# s0, hash_leaf_split k vh s #)
{-# INLINE hash_leaf_split# #-}