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

Internal.hs (23881B)


      1 {-# OPTIONS_HADDOCK hide #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 {-# LANGUAGE EmptyCase #-}
      4 {-# LANGUAGE MagicHash #-}
      5 {-# LANGUAGE UnboxedSums #-}
      6 {-# LANGUAGE UnboxedTuples #-}
      7 
      8 -- |
      9 -- Module: Data.MSSMT.Internal
     10 -- Copyright: (c) 2026 Jared Tobin
     11 -- License: MIT
     12 -- Maintainer: Jared Tobin <jared@jtobin.io>
     13 --
     14 -- MS-SMT internals.
     15 
     16 module Data.MSSMT.Internal (
     17   -- * Keys, hashes, and commitments
     18     Key(..)
     19   , key
     20   , Hash(..)
     21   , parse_hash
     22   , serialize_hash
     23   , Commitment(..)
     24 
     25   -- * Hashing
     26   , native
     27   , hash_value
     28   , hash_leaf_split
     29   , hash_leaf_aggregate
     30   , hash_node_split
     31   , hash_node_split_native
     32   , hash_node_split_pure
     33   , hash_node_aggregate
     34   , hash_node_aggregate_native
     35   , hash_node_aggregate_pure
     36 
     37   -- * Schemes
     38   , Scheme(..)
     39 
     40   -- * Tree
     41   , Tree(..)
     42   , Kind(..)
     43   , Payload(..)
     44   , Missing(..)
     45   , complete
     46   , expand
     47   , empty
     48   , insert_with
     49   , insert_many_with
     50   , delete_with
     51   , lookup
     52   , root_with
     53 
     54   -- * Proofs
     55   , Neighbor(..)
     56   , prove_split
     57   , verify_split
     58   , prove_aggregate
     59   , verify_aggregate
     60   ) where
     61 
     62 import Data.Bits (unsafeShiftR, xor, (.&.))
     63 import qualified Data.ByteString as BS
     64 import Data.MSSMT.Hash
     65 import Data.List (sortBy)
     66 import qualified Data.Primitive.PrimArray as PA
     67 import Data.Ord (comparing)
     68 import Data.Void (Void, absurd)
     69 import Data.Word (Word64)
     70 import qualified GHC.Exts as Exts
     71 import GHC.Exts (State#)
     72 import Prelude hiding (lookup)
     73 
     74 -- | A 256-bit key, held as a hash's big-endian words, so that keys
     75 --   are ordered as their bytes are.
     76 newtype Key = Key Hash
     77   deriving (Eq, Ord, Show)
     78 
     79 -- | Parse a 32-byte key.
     80 key :: BS.ByteString -> Maybe Key
     81 key = fmap Key . parse_hash
     82 
     83 -- | A node's commitment: its hash, and its sum.
     84 data Commitment = Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
     85   deriving (Eq, Show)
     86 
     87 -- | A merkle-sum sparse merkle tree, whose subtrees held elsewhere, if
     88 --   it has any, are stood for by stubs carrying an @s@.
     89 --
     90 --   A subtree holding a single leaf is stored as that leaf, at the
     91 --   subtree's height, and a branch is stored only where two or more
     92 --   leaves lie beneath it. A complete tree, held entirely in memory, is
     93 --   a @Tree Void@, which can't have stubs; one held partly elsewhere,
     94 --   as in a store, is a @Tree Kind@.
     95 data Tree s =
     96     Empty
     97     -- a subtree holding exactly one leaf: the subtree's commitment at
     98     -- its height, the leaf's hash, and the leaf's key and value
     99   | Leaf
    100       {-# UNPACK #-} !Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Key
    101       !BS.ByteString
    102   | Node !(Tree s) {-# UNPACK #-} !Commitment !(Tree s)
    103     -- a subtree held elsewhere: what stands for it, and its commitment
    104   | Stub !s {-# UNPACK #-} !Commitment
    105   deriving (Eq, Show)
    106 
    107 -- | What a subtree holds: a single leaf, or a branch over two or more.
    108 data Kind = Single | Branch
    109   deriving (Eq, Show)
    110 
    111 -- | What a stub can carry: something telling what kind of subtree it
    112 --   stands for.
    113 class Payload s where
    114   payload_kind :: s -> Kind
    115 
    116 instance Payload Kind where
    117   payload_kind = id
    118 
    119 instance Payload Void where
    120   payload_kind = absurd
    121 
    122 -- | A subtree held elsewhere that an operation needed: what stands for
    123 --   it, and its commitment.
    124 data Missing s = Missing !s {-# UNPACK #-} !Commitment
    125   deriving (Eq, Show)
    126 
    127 -- | The result of an operation on a complete tree, which can't have
    128 --   needed a subtree held elsewhere.
    129 complete :: Either (Missing Void) a -> a
    130 complete = either (\m -> case m of {}) id
    131 {-# INLINE complete #-}
    132 
    133 -- structure ------------------------------------------------------------------
    134 
    135 -- leaf depth
    136 _HEIGHT :: Int
    137 _HEIGHT = 256
    138 
    139 -- hashes of empty subtrees in an aggregate tree, four words per depth:
    140 -- an empty subtree is the full subtree of empty leaves, hashed as any
    141 -- other subtree
    142 empties :: PA.PrimArray Word64
    143 empties = PA.primArrayFromListN (4 * (_HEIGHT + 1))
    144   . concatMap (\(Hash a b c d) -> [a, b, c, d])
    145   . reverse . take (_HEIGHT + 1) $
    146     iterate (\h -> hash_node_aggregate h h 0) (hash_leaf_aggregate mempty 0)
    147 {-# NOINLINE empties #-}
    148 
    149 -- hash of the empty subtree at the given depth; in a split tree, it's
    150 -- the zero hash at any depth
    151 empty_hash :: Scheme -> Int -> Hash
    152 empty_hash Split _ = Hash 0 0 0 0
    153 empty_hash Aggregate d = Hash (ix 0) (ix 1) (ix 2) (ix 3) where
    154   ix i = PA.indexPrimArray empties (4 * d + i)
    155 {-# INLINE empty_hash #-}
    156 
    157 -- commitment of a subtree at the given depth
    158 commit :: Scheme -> Int -> Tree s -> Commitment
    159 commit sc d Empty = Commitment (empty_hash sc d) 0
    160 commit _ _ (Leaf c _ _ _) = c
    161 commit _ _ (Node _ c _) = c
    162 commit _ _ (Stub _ c) = c
    163 {-# INLINE commit #-}
    164 
    165 -- sum of a subtree
    166 total :: Tree s -> Word64
    167 total Empty = 0
    168 total (Leaf (Commitment _ s) _ _ _) = s
    169 total (Node _ (Commitment _ s) _) = s
    170 total (Stub _ (Commitment _ s)) = s
    171 {-# INLINE total #-}
    172 
    173 -- path bit at the given depth; LSB-first within each byte. a word
    174 -- holds its bytes big-endian, so the bit at depth d is at 8 * (7 - j) +
    175 -- i in word d / 64, for j = d / 8 mod 8 and i = d mod 8: d mod 64 with
    176 -- j's bits flipped
    177 bit :: Key -> Int -> Bool
    178 bit (Key (Hash w0 w1 w2 w3)) d =
    179     w `unsafeShiftR` ((d .&. 63) `xor` 56) .&. 1 /= 0
    180   where
    181     w = case d `unsafeShiftR` 6 of
    182       0 -> w0
    183       1 -> w1
    184       2 -> w2
    185       _ -> w3
    186 {-# INLINE bit #-}
    187 
    188 -- whether two keys' paths agree above the given depth
    189 agree :: Key -> Key -> Int -> Bool
    190 agree k k' d = all (\j -> bit k j == bit k' j) [0 .. d - 1]
    191 
    192 -- a key, as a hash's words
    193 key_hash :: Key -> Hash
    194 key_hash (Key h) = h
    195 
    196 -- a leaf's hash under a scheme, over the given state and block arrays
    197 hash_leaf#
    198   :: Scheme -> Buffer -> Buffer -> Key -> BS.ByteString -> Word64
    199   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
    200 hash_leaf# Split st bk k v s =
    201   hash_leaf_split# st bk (key_hash k) (hash_value v) s
    202 hash_leaf# Aggregate _ _ _ v s = \s0 -> (# s0, hash_leaf_aggregate v s #)
    203 {-# INLINE hash_leaf# #-}
    204 
    205 -- the leaf at a key, if there's one, passed its sum and value, or the
    206 -- stub on the key's path, if there's one
    207 with_leaf
    208   :: Key -> Tree s -> r -> (Word64 -> BS.ByteString -> r) -> (Missing s -> r)
    209   -> r
    210 with_leaf k t0 none some stub = go 0 t0 where
    211   go !d t = case t of
    212     Empty -> none
    213     Leaf (Commitment _ s) _ k' v
    214       | k' == k   -> some s v
    215       | otherwise -> none
    216     Node l _ r -> go (d + 1) (if bit k d then r else l)
    217     Stub p c -> stub (Missing p c)
    218 {-# INLINE with_leaf #-}
    219 
    220 -- an operation's result in a tree, or what it needed but found held
    221 -- elsewhere
    222 done#
    223   :: (# State# Exts.RealWorld, Tree s #)
    224   -> (# State# Exts.RealWorld, (# Tree s | Missing s #) #)
    225 done# (# s0, t #) = (# s0, (# t | #) #)
    226 {-# INLINE done# #-}
    227 
    228 -- the first depth, at or below the given one, at which two keys' paths
    229 -- diverge; callers ensure the keys are distinct, and agree above it
    230 diverge :: Key -> Key -> Int -> Int
    231 diverge k k' = go where
    232   go !d
    233     | bit k d /= bit k' d = d
    234     | otherwise = go (d + 1)
    235 
    236 -- raise a single-leaf subtree's commitment from one depth to a
    237 -- shallower one: in a split tree, it's the same at any depth, and in an
    238 -- aggregate tree, it's paired with an empty sibling at each level
    239 -- between. strict in the key and depths under either scheme, so that
    240 -- they're passed unboxed
    241 raise#
    242   :: Scheme -> Buffer -> Buffer -> Key -> Int -> Int -> Commitment
    243   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Commitment #)
    244 raise# Split _ _ !_ !_ !_ c = \s0 -> (# s0, c #)
    245 raise# sc st bk !k !to from (Commitment h0 s) = go (from - 1) h0 where
    246   go !d !h s0
    247     | d < to = let !c = Commitment h s in (# s0, c #)
    248     | otherwise =
    249         let !e = empty_hash sc (d + 1)
    250         in  case if   bit k d
    251                  then hash_branch# sc st bk e 0 h s s0
    252                  else hash_branch# sc st bk h s e 0 s0 of
    253               (# s1, h' #) -> go (d - 1) h' s1
    254 
    255 -- a single-leaf subtree at the given depth, given the leaf's hash
    256 leaf#
    257   :: Scheme -> Buffer -> Buffer -> Int -> Key -> Hash -> Word64
    258   -> BS.ByteString
    259   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
    260 leaf# sc st bk d k lh s v s0 =
    261   case raise# sc st bk k d _HEIGHT (Commitment lh s) s0 of
    262     (# s1, c #) -> let !t = Leaf c lh k v in (# s1, t #)
    263 
    264 -- a subtree at the given depth with the given children, hashed over the
    265 -- given state and block arrays. a lone leaf beside an empty subtree is
    266 -- raised to this depth in their place, and two empty children make an
    267 -- empty subtree. callers rule out sum overflow
    268 node#
    269   :: Payload s
    270   => Scheme -> Buffer -> Buffer -> Int -> Tree s -> Tree s
    271   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
    272 node# _ _ _ _ Empty Empty s0 = (# s0, Empty #)
    273 node# sc st bk d Empty (Leaf c lh k v) s0 = lift# sc st bk d c lh k v s0
    274 node# sc st bk d (Leaf c lh k v) Empty s0 = lift# sc st bk d c lh k v s0
    275 -- a split leaf's commitment is the same at any height, so a lone leaf
    276 -- held elsewhere moves up as it is. an aggregate one stays beneath a
    277 -- branch, whose commitment is that of the leaf moved up a level
    278 node# Split _ _ _ Empty t@(Stub p _) s0
    279   | payload_kind p == Single = (# s0, t #)
    280 node# Split _ _ _ t@(Stub p _) Empty s0
    281   | payload_kind p == Single = (# s0, t #)
    282 node# sc st bk d l r s0 =
    283   let !(Commitment hl sl) = commit sc (d + 1) l
    284       !(Commitment hr sr) = commit sc (d + 1) r
    285   in  case hash_branch# sc st bk hl sl hr sr s0 of
    286         (# s1, h #) ->
    287           -- built strictly; a lazy tuple component would allocate a
    288           -- thunk for the node per level
    289           let !n = Node l (Commitment h (sl + sr)) r
    290           in  (# s1, n #)
    291 {-# INLINE node# #-}
    292 
    293 -- raise a single-leaf subtree one level, to the given depth
    294 lift#
    295   :: Scheme -> Buffer -> Buffer -> Int -> Commitment -> Hash -> Key
    296   -> BS.ByteString
    297   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
    298 lift# sc st bk d c lh k v s0 = case raise# sc st bk k d (d + 1) c s0 of
    299   (# s1, c' #) -> let !t = Leaf c' lh k v in (# s1, t #)
    300 
    301 -- insert a leaf, hashing it and rehashing the path to it over one pair
    302 -- of state and block arrays
    303 insert_leaf
    304   :: Payload s
    305   => Scheme -> Key -> BS.ByteString -> Word64 -> Tree s
    306   -> Either (Missing s) (Tree s)
    307 insert_leaf sc k v s t0 = with_scratch $ \st bk s00 ->
    308   case hash_leaf# sc st bk k v s s00 of { (# s01, lh #) ->
    309   let go !d t s0 = case t of
    310         Empty -> done# (leaf# sc st bk d k lh s v s0)
    311         Leaf (Commitment _ s') lh' k' v'
    312           | k' == k   -> done# (leaf# sc st bk d k lh s v s0)
    313           | otherwise ->
    314               let p = diverge k k' d
    315                   -- the two leaves, beneath the branch where their paths
    316                   -- diverge
    317                   new = leaf# sc st bk (p + 1) k lh s v
    318                   old = leaf# sc st bk (p + 1) k' lh' s' v'
    319                   pair s1 =
    320                     case new s1 of { (# s2, a #) ->
    321                     case old s2 of { (# s3, b #) ->
    322                     if   bit k p
    323                     then node# sc st bk p b a s3
    324                     else node# sc st bk p a b s3 }}
    325                   -- the branches from there up to this depth, each with
    326                   -- an empty sibling
    327                   up j s1
    328                     | j == p = pair s1
    329                     | otherwise = case up (j + 1) s1 of
    330                         (# s2, c #)
    331                           | bit k j   -> node# sc st bk j Empty c s2
    332                           | otherwise -> node# sc st bk j c Empty s2
    333               in  done# (up d s0)
    334         Node l _ r
    335           | bit k d -> case go (d + 1) r s0 of
    336               (# s1, (# r' | #) #) -> done# (node# sc st bk d l r' s1)
    337               (# s1, (# | m #) #) -> (# s1, (# | m #) #)
    338           | otherwise -> case go (d + 1) l s0 of
    339               (# s1, (# l' | #) #) -> done# (node# sc st bk d l' r s1)
    340               (# s1, (# | m #) #) -> (# s1, (# | m #) #)
    341         Stub p c -> (# s0, (# | Missing p c #) #)
    342   in  case go 0 t0 s01 of
    343         (# s1, (# t | #) #) -> (# s1, Right t #)
    344         (# s1, (# | m #) #) -> (# s1, Left m #) }
    345 {-# INLINABLE insert_leaf #-}
    346 
    347 -- a leaf in a subtree being rebuilt in a batch: one being put, one
    348 -- being deleted, or an existing one, kept with its hash
    349 data Item =
    350     Put {-# UNPACK #-} !Key !BS.ByteString {-# UNPACK #-} !Word64
    351   | Del {-# UNPACK #-} !Key
    352   | Kept
    353       {-# UNPACK #-} !Key {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
    354       !BS.ByteString
    355 
    356 item_key :: Item -> Key
    357 item_key (Put k _ _) = k
    358 item_key (Del k) = k
    359 item_key (Kept k _ _ _) = k
    360 
    361 -- items whose paths go left and right at a depth
    362 split :: Int -> [Item] -> ([Item], [Item])
    363 split d = go [] [] where
    364   go !ls !rs is = case is of
    365     [] -> (ls, rs)
    366     i : rest
    367       | bit (item_key i) d -> go ls (i : rs) rest
    368       | otherwise -> go (i : ls) rs rest
    369 
    370 -- apply a batch of puts and deletions, at distinct keys, rehashing each
    371 -- changed node once over one pair of state and block arrays. callers
    372 -- rule out sum overflow
    373 batch
    374   :: Payload s => Scheme -> [Item] -> Tree s -> Either (Missing s) (Tree s)
    375 batch sc items0 t0 = with_scratch $ \st bk s00 ->
    376   let -- the subtree at a depth holding the given items, which agree on
    377       -- their paths above it
    378       go !d t items s0 = case t of
    379         Empty -> done# (build d items s0)
    380         Leaf (Commitment _ s') lh' k' v'
    381           | any ((== k') . item_key) items -> done# (build d items s0)
    382           | otherwise -> done# (build d (Kept k' lh' s' v' : items) s0)
    383         Node l _ r ->
    384           let (ls, rs) = split d items
    385               side u is s1
    386                 | null is   = (# s1, (# u | #) #)
    387                 | otherwise = go (d + 1) u is s1
    388           in  case side l ls s0 of
    389                 (# s1, (# | m #) #) -> (# s1, (# | m #) #)
    390                 (# s1, (# l' | #) #) -> case side r rs s1 of
    391                   (# s2, (# | m #) #) -> (# s2, (# | m #) #)
    392                   (# s2, (# r' | #) #) -> done# (node# sc st bk d l' r' s2)
    393         Stub p c -> (# s0, (# | Missing p c #) #)
    394 
    395       -- the subtree at a depth holding exactly the given items' leaves
    396       build !d items s0 = case filter live items of
    397         [] -> (# s0, Empty #)
    398         [Put k v s] -> case hash_leaf# sc st bk k v s s0 of
    399           (# s1, lh #) -> leaf# sc st bk d k lh s v s1
    400         [Kept k lh s v] -> leaf# sc st bk d k lh s v s0
    401         is ->
    402           let (ls, rs) = split d is
    403           in  case build (d + 1) ls s0 of
    404                 (# s1, l #) -> case build (d + 1) rs s1 of
    405                   (# s2, r #) -> node# sc st bk d l r s2
    406 
    407       live (Del _) = False
    408       live _ = True
    409   in  case go 0 t0 items0 s00 of
    410         (# s1, (# t | #) #) -> (# s1, Right t #)
    411         (# s1, (# | m #) #) -> (# s1, Left m #)
    412 {-# INLINABLE batch #-}
    413 
    414 -- tree -----------------------------------------------------------------------
    415 
    416 -- | The empty tree.
    417 empty :: Tree s
    418 empty = Empty
    419 
    420 -- | Insert a value and sum at a key under a scheme, replacing any
    421 --   existing leaf.
    422 --
    423 --   Returns 'Nothing' if the tree's sum would overflow, or what the
    424 --   insertion needed, if it was held elsewhere.
    425 insert_with
    426   :: Payload s
    427   => Scheme -> Key -> BS.ByteString -> Word64 -> Tree s
    428   -> Either (Missing s) (Maybe (Tree s))
    429 insert_with sc k v s t = with_leaf k t (go 0) (\was _ -> go was) Left where
    430   go was
    431     | s > maxBound - (total t - was) = Right Nothing
    432     -- an empty value with zero sum is the empty leaf
    433     | BS.null v && s == 0 = Just <$> delete_with sc k t
    434     | otherwise = Just <$> insert_leaf sc k v s t
    435 {-# INLINABLE insert_with #-}
    436 
    437 -- | Insert many values and sums under a scheme, as if one at a time,
    438 --   but rehashing each changed node once.
    439 --
    440 --   Where a key appears more than once, its last appearance wins, and
    441 --   an empty value with zero sum deletes whatever is at its key.
    442 --   Returns 'Nothing' if the resulting tree's sum would overflow, or
    443 --   what the insertions needed, if it was held elsewhere.
    444 insert_many_with
    445   :: Payload s
    446   => Scheme -> [(Key, BS.ByteString, Word64)] -> Tree s
    447   -> Either (Missing s) (Maybe (Tree s))
    448 insert_many_with sc kvs t
    449     | null items = Right (Just t)
    450     | otherwise = do
    451         was <- traverse (\i -> with_leaf (item_key i) t
    452                  (Right 0) (\s _ -> Right s) Left) items
    453         let after = toInteger (total t) + sum (zipWith change items was)
    454         if   after > toInteger (maxBound :: Word64)
    455         then Right Nothing
    456         else Just <$> batch sc items t
    457   where
    458     -- the last item at each key
    459     items = last_each (sortBy (comparing (\(k, _, _) -> k)) kvs)
    460     last_each ((k, v, s) : rest@((k', _, _) : _))
    461       | k == k' = last_each rest
    462       | otherwise = item k v s : last_each rest
    463     last_each [(k, v, s)] = [item k v s]
    464     last_each [] = []
    465 
    466     item k v s
    467       | BS.null v && s == 0 = Del k
    468       | otherwise = Put k v s
    469 
    470     -- each item's change to the tree's sum, given what's at its key
    471     change i was = case i of
    472       Put _ _ s -> toInteger s - toInteger was
    473       Del _ -> negate (toInteger was)
    474       Kept {} -> 0
    475 {-# INLINABLE insert_many_with #-}
    476 
    477 -- | Delete the leaf at a key under a scheme.
    478 --
    479 --   Returns what the deletion needed, if it was held elsewhere.
    480 delete_with
    481   :: Payload s => Scheme -> Key -> Tree s -> Either (Missing s) (Tree s)
    482 delete_with sc k t0 = with_leaf k t0 (Right t0) (\_ _ -> deleted) Left where
    483   deleted = with_scratch $ \st bk s00 ->
    484     let go !d t s0 = case t of
    485           -- the key is present, so a leaf on its path is its own
    486           Empty -> (# s0, (# Empty | #) #)
    487           Leaf {} -> (# s0, (# Empty | #) #)
    488           Node l _ r
    489             | bit k d -> case go (d + 1) r s0 of
    490                 (# s1, (# r' | #) #) -> done# (node# sc st bk d l r' s1)
    491                 (# s1, (# | m #) #) -> (# s1, (# | m #) #)
    492             | otherwise -> case go (d + 1) l s0 of
    493                 (# s1, (# l' | #) #) -> done# (node# sc st bk d l' r s1)
    494                 (# s1, (# | m #) #) -> (# s1, (# | m #) #)
    495           Stub p c -> (# s0, (# | Missing p c #) #)
    496     in  case go 0 t0 s00 of
    497           (# s1, (# t | #) #) -> (# s1, Right t #)
    498           (# s1, (# | m #) #) -> (# s1, Left m #)
    499 {-# INLINABLE delete_with #-}
    500 
    501 -- | Look up the value and sum at a key.
    502 --
    503 --   Returns what the lookup needed, if it was held elsewhere.
    504 lookup :: Key -> Tree s -> Either (Missing s) (Maybe (BS.ByteString, Word64))
    505 lookup k t = with_leaf k t (Right Nothing) (\s v -> Right (Just (v, s))) Left
    506 {-# INLINE lookup #-}
    507 
    508 -- | Load the subtrees held elsewhere along a key's path, down to the
    509 --   key's slot, via a loader given what stands for each one and its
    510 --   commitment, which returns its contents with its own subtrees held
    511 --   elsewhere.
    512 --
    513 --   Operations at a key need only its path loaded.
    514 expand
    515   :: Monad m => (s -> Commitment -> m (Tree s)) -> Key -> Tree s
    516   -> m (Tree s)
    517 expand load k = go 0 where
    518   go !d t = case t of
    519     Stub p c -> load p c >>= go d
    520     Node l c r
    521       | bit k d   -> (\r' -> Node l c r') <$> go (d + 1) r
    522       | otherwise -> (\l' -> Node l' c r) <$> go (d + 1) l
    523     Empty -> pure t
    524     Leaf {} -> pure t
    525 
    526 -- | The tree's root commitment under a scheme.
    527 root_with :: Scheme -> Tree s -> Commitment
    528 root_with sc = commit sc 0
    529 
    530 -- proofs ---------------------------------------------------------------------
    531 
    532 -- | Another key's leaf, at which a key's path ends: its key, the hash
    533 --   of its value, and its sum.
    534 data Neighbor =
    535   Neighbor {-# UNPACK #-} !Key {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
    536   deriving (Eq, Show)
    537 
    538 -- whether climbing from a commitment at the given depth on a key's
    539 -- path, over that many siblings from the deepest up, reaches a root,
    540 -- hashing over the given state and block arrays; a branch's sum mustn't
    541 -- overflow. callers ensure the depth is at most 256
    542 climb#
    543   :: Scheme -> Buffer -> Buffer -> Key -> Int -> Commitment
    544   -> [Commitment] -> Commitment
    545   -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Bool #)
    546 climb# sc st bk k d0 (Commitment h0 n0) sibs r = go (d0 - 1) h0 n0 sibs where
    547   go !d !h !hs ps s0 = case ps of
    548     [] -> (# s0, d == -1 && Commitment h hs == r #)
    549     Commitment g gs : rest
    550       | d < 0 || gs > maxBound - hs -> (# s0, False #)
    551       | otherwise ->
    552           case if   bit k d
    553                then hash_branch# sc st bk g gs h hs s0
    554                else hash_branch# sc st bk h hs g gs s0 of
    555             (# s1, p #) -> go (d - 1) p (hs + gs) rest s1
    556 
    557 -- | The siblings along a key's path in a split tree, from the deepest up
    558 --   to the root's, and the leaf the path ends at, where that's another
    559 --   key's.
    560 --
    561 --   Returns what the proof needed, if it was held elsewhere.
    562 prove_split
    563   :: Key -> Tree s -> Either (Missing s) (Maybe Neighbor, [Commitment])
    564 prove_split k = go 0 [] where
    565   go !d acc t = case t of
    566     Empty -> Right (Nothing, acc)
    567     Leaf (Commitment _ s) _ k' v
    568       | k' == k   -> Right (Nothing, acc)
    569       | otherwise -> Right (Just (Neighbor k' (hash_value v) s), acc)
    570     Node l _ r
    571       | bit k d   -> go (d + 1) (commit Split (d + 1) l : acc) r
    572       | otherwise -> go (d + 1) (commit Split (d + 1) r : acc) l
    573     Stub p c -> Left (Missing p c)
    574 
    575 -- | Verify that a value and sum sit at a key in a split tree, under a
    576 --   root, given the siblings along the key's path, and the leaf the path
    577 --   ends at, where that's another key's.
    578 --
    579 --   An empty value with zero sum verifies the key's exclusion, for which
    580 --   the path must end at an empty subtree or at another key's leaf.
    581 --   Proofs with more than 256 siblings, or whose branch sums overflow,
    582 --   are rejected.
    583 verify_split
    584   :: Key -> BS.ByteString -> Word64 -> Maybe Neighbor -> [Commitment]
    585   -> Commitment -> Bool
    586 verify_split k v s nb sibs r = d <= _HEIGHT && with_scratch go where
    587   d = length sibs
    588   vacant = BS.null v && s == 0
    589   up st bk c = climb# Split st bk k d c sibs r
    590   go st bk s0 = case nb of
    591     Nothing
    592       | vacant    -> up st bk (commit Split d Empty) s0
    593       | otherwise -> case hash_leaf# Split st bk k v s s0 of
    594           (# s1, h #) -> up st bk (Commitment h s) s1
    595     Just (Neighbor k' h s')
    596       | vacant && k' /= k && agree k k' d ->
    597           case hash_leaf_split# st bk (key_hash k') h s' s0 of
    598             (# s1, h' #) -> up st bk (Commitment h' s') s1
    599       | otherwise -> (# s0, False #)
    600 
    601 -- | The siblings along a key's path in an aggregate tree: all 256 of
    602 --   them, from the leaf up to the root's.
    603 --
    604 --   Returns what the proof needed, if it was held elsewhere.
    605 prove_aggregate :: Key -> Tree s -> Either (Missing s) [Commitment]
    606 prove_aggregate k t0 = with_scratch $ \st bk ->
    607   let -- empty siblings at depths j through j1 - 1
    608       pad j j1 acc
    609         | j == j1 = acc
    610         | otherwise =
    611             pad (j + 1) j1 (commit Aggregate (j + 1) Empty : acc)
    612       go !d acc t s0 = case t of
    613         Empty -> (# s0, Right (pad d _HEIGHT acc) #)
    614         Leaf (Commitment _ s') lh' k' _
    615           | k' == k   -> (# s0, Right (pad d _HEIGHT acc) #)
    616           | otherwise ->
    617               -- the leaf's subtree is the sibling where the paths diverge
    618               let p  = diverge k k' d
    619                   c0 = Commitment lh' s'
    620               in  case raise# Aggregate st bk k' (p + 1) _HEIGHT c0 s0 of
    621                     (# s1, c #) ->
    622                       (# s1, Right (pad (p + 1) _HEIGHT (c : pad d p acc)) #)
    623         Node l _ r
    624           | bit k d   -> go (d + 1) (commit Aggregate (d + 1) l : acc) r s0
    625           | otherwise -> go (d + 1) (commit Aggregate (d + 1) r : acc) l s0
    626         Stub q c -> (# s0, Left (Missing q c) #)
    627   in  go 0 [] t0
    628 
    629 -- | Verify that a value and sum sit at a key in an aggregate tree, under
    630 --   a root, given the 256 siblings along the key's path.
    631 --
    632 --   An empty value with zero sum verifies the key's exclusion. Proofs
    633 --   whose branch sums overflow are rejected.
    634 verify_aggregate
    635   :: Key -> BS.ByteString -> Word64 -> [Commitment] -> Commitment -> Bool
    636 verify_aggregate k v s sibs r =
    637      length sibs == _HEIGHT
    638   && with_scratch (\st bk -> climb# Aggregate st bk k _HEIGHT leaf sibs r)
    639   where
    640     leaf = Commitment (hash_leaf_aggregate v s) s