packages feed

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

{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedSums #-}
{-# LANGUAGE UnboxedTuples #-}

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

module Data.MSSMT.Internal (
  -- * Keys, hashes, and commitments
    Key(..)
  , key
  , Hash(..)
  , parse_hash
  , serialize_hash
  , Commitment(..)

  -- * Hashing
  , 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(..)

  -- * Tree
  , Tree(..)
  , Kind(..)
  , Payload(..)
  , Missing(..)
  , complete
  , expand
  , empty
  , insert_with
  , insert_many_with
  , delete_with
  , lookup
  , root_with

  -- * Proofs
  , Neighbor(..)
  , prove_split
  , verify_split
  , prove_aggregate
  , verify_aggregate
  ) where

import Data.Bits (unsafeShiftR, xor, (.&.))
import qualified Data.ByteString as BS
import Data.MSSMT.Hash
import Data.List (sortBy)
import qualified Data.Primitive.PrimArray as PA
import Data.Ord (comparing)
import Data.Void (Void, absurd)
import Data.Word (Word64)
import qualified GHC.Exts as Exts
import GHC.Exts (State#)
import Prelude hiding (lookup)

-- | A 256-bit key, held as a hash's big-endian words, so that keys
--   are ordered as their bytes are.
newtype Key = Key Hash
  deriving (Eq, Ord, Show)

-- | Parse a 32-byte key.
key :: BS.ByteString -> Maybe Key
key = fmap Key . parse_hash

-- | A node's commitment: its hash, and its sum.
data Commitment = Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
  deriving (Eq, Show)

-- | A merkle-sum sparse merkle tree, whose subtrees held elsewhere, if
--   it has any, are stood for by stubs carrying an @s@.
--
--   A subtree holding a single leaf is stored as that leaf, at the
--   subtree's height, and a branch is stored only where two or more
--   leaves lie beneath it. A complete tree, held entirely in memory, is
--   a @Tree Void@, which can't have stubs; one held partly elsewhere,
--   as in a store, is a @Tree Kind@.
data Tree s =
    Empty
    -- a subtree holding exactly one leaf: the subtree's commitment at
    -- its height, the leaf's hash, and the leaf's key and value
  | Leaf
      {-# UNPACK #-} !Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Key
      !BS.ByteString
  | Node !(Tree s) {-# UNPACK #-} !Commitment !(Tree s)
    -- a subtree held elsewhere: what stands for it, and its commitment
  | Stub !s {-# UNPACK #-} !Commitment
  deriving (Eq, Show)

-- | What a subtree holds: a single leaf, or a branch over two or more.
data Kind = Single | Branch
  deriving (Eq, Show)

-- | What a stub can carry: something telling what kind of subtree it
--   stands for.
class Payload s where
  payload_kind :: s -> Kind

instance Payload Kind where
  payload_kind = id

instance Payload Void where
  payload_kind = absurd

-- | A subtree held elsewhere that an operation needed: what stands for
--   it, and its commitment.
data Missing s = Missing !s {-# UNPACK #-} !Commitment
  deriving (Eq, Show)

-- | The result of an operation on a complete tree, which can't have
--   needed a subtree held elsewhere.
complete :: Either (Missing Void) a -> a
complete = either (\m -> case m of {}) id
{-# INLINE complete #-}

-- structure ------------------------------------------------------------------

-- leaf depth
_HEIGHT :: Int
_HEIGHT = 256

-- hashes of empty subtrees in an aggregate tree, four words per depth:
-- an empty subtree is the full subtree of empty leaves, hashed as any
-- other subtree
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_aggregate h h 0) (hash_leaf_aggregate mempty 0)
{-# NOINLINE empties #-}

-- hash of the empty subtree at the given depth; in a split tree, it's
-- the zero hash at any depth
empty_hash :: Scheme -> Int -> Hash
empty_hash Split _ = Hash 0 0 0 0
empty_hash Aggregate d = Hash (ix 0) (ix 1) (ix 2) (ix 3) where
  ix i = PA.indexPrimArray empties (4 * d + i)
{-# INLINE empty_hash #-}

-- commitment of a subtree at the given depth
commit :: Scheme -> Int -> Tree s -> Commitment
commit sc d Empty = Commitment (empty_hash sc d) 0
commit _ _ (Leaf c _ _ _) = c
commit _ _ (Node _ c _) = c
commit _ _ (Stub _ c) = c
{-# INLINE commit #-}

-- sum of a subtree
total :: Tree s -> Word64
total Empty = 0
total (Leaf (Commitment _ s) _ _ _) = s
total (Node _ (Commitment _ s) _) = s
total (Stub _ (Commitment _ s)) = s
{-# INLINE total #-}

-- path bit at the given depth; LSB-first within each byte. a word
-- holds its bytes big-endian, so the bit at depth d is at 8 * (7 - j) +
-- i in word d / 64, for j = d / 8 mod 8 and i = d mod 8: d mod 64 with
-- j's bits flipped
bit :: Key -> Int -> Bool
bit (Key (Hash w0 w1 w2 w3)) d =
    w `unsafeShiftR` ((d .&. 63) `xor` 56) .&. 1 /= 0
  where
    w = case d `unsafeShiftR` 6 of
      0 -> w0
      1 -> w1
      2 -> w2
      _ -> w3
{-# INLINE bit #-}

-- whether two keys' paths agree above the given depth
agree :: Key -> Key -> Int -> Bool
agree k k' d = all (\j -> bit k j == bit k' j) [0 .. d - 1]

-- a key, as a hash's words
key_hash :: Key -> Hash
key_hash (Key h) = h

-- a leaf's hash under a scheme, over the given state and block arrays
hash_leaf#
  :: Scheme -> Buffer -> Buffer -> Key -> BS.ByteString -> Word64
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Hash #)
hash_leaf# Split st bk k v s =
  hash_leaf_split# st bk (key_hash k) (hash_value v) s
hash_leaf# Aggregate _ _ _ v s = \s0 -> (# s0, hash_leaf_aggregate v s #)
{-# INLINE hash_leaf# #-}

-- the leaf at a key, if there's one, passed its sum and value, or the
-- stub on the key's path, if there's one
with_leaf
  :: Key -> Tree s -> r -> (Word64 -> BS.ByteString -> r) -> (Missing s -> r)
  -> r
with_leaf k t0 none some stub = go 0 t0 where
  go !d t = case t of
    Empty -> none
    Leaf (Commitment _ s) _ k' v
      | k' == k   -> some s v
      | otherwise -> none
    Node l _ r -> go (d + 1) (if bit k d then r else l)
    Stub p c -> stub (Missing p c)
{-# INLINE with_leaf #-}

-- an operation's result in a tree, or what it needed but found held
-- elsewhere
done#
  :: (# State# Exts.RealWorld, Tree s #)
  -> (# State# Exts.RealWorld, (# Tree s | Missing s #) #)
done# (# s0, t #) = (# s0, (# t | #) #)
{-# INLINE done# #-}

-- the first depth, at or below the given one, at which two keys' paths
-- diverge; callers ensure the keys are distinct, and agree above it
diverge :: Key -> Key -> Int -> Int
diverge k k' = go where
  go !d
    | bit k d /= bit k' d = d
    | otherwise = go (d + 1)

-- raise a single-leaf subtree's commitment from one depth to a
-- shallower one: in a split tree, it's the same at any depth, and in an
-- aggregate tree, it's paired with an empty sibling at each level
-- between. strict in the key and depths under either scheme, so that
-- they're passed unboxed
raise#
  :: Scheme -> Buffer -> Buffer -> Key -> Int -> Int -> Commitment
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Commitment #)
raise# Split _ _ !_ !_ !_ c = \s0 -> (# s0, c #)
raise# sc st bk !k !to from (Commitment h0 s) = go (from - 1) h0 where
  go !d !h s0
    | d < to = let !c = Commitment h s in (# s0, c #)
    | otherwise =
        let !e = empty_hash sc (d + 1)
        in  case if   bit k d
                 then hash_branch# sc st bk e 0 h s s0
                 else hash_branch# sc st bk h s e 0 s0 of
              (# s1, h' #) -> go (d - 1) h' s1

-- a single-leaf subtree at the given depth, given the leaf's hash
leaf#
  :: Scheme -> Buffer -> Buffer -> Int -> Key -> Hash -> Word64
  -> BS.ByteString
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
leaf# sc st bk d k lh s v s0 =
  case raise# sc st bk k d _HEIGHT (Commitment lh s) s0 of
    (# s1, c #) -> let !t = Leaf c lh k v in (# s1, t #)

-- a subtree at the given depth with the given children, hashed over the
-- given state and block arrays. a lone leaf beside an empty subtree is
-- raised to this depth in their place, and two empty children make an
-- empty subtree. callers rule out sum overflow
node#
  :: Payload s
  => Scheme -> Buffer -> Buffer -> Int -> Tree s -> Tree s
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
node# _ _ _ _ Empty Empty s0 = (# s0, Empty #)
node# sc st bk d Empty (Leaf c lh k v) s0 = lift# sc st bk d c lh k v s0
node# sc st bk d (Leaf c lh k v) Empty s0 = lift# sc st bk d c lh k v s0
-- a split leaf's commitment is the same at any height, so a lone leaf
-- held elsewhere moves up as it is. an aggregate one stays beneath a
-- branch, whose commitment is that of the leaf moved up a level
node# Split _ _ _ Empty t@(Stub p _) s0
  | payload_kind p == Single = (# s0, t #)
node# Split _ _ _ t@(Stub p _) Empty s0
  | payload_kind p == Single = (# s0, t #)
node# sc st bk d l r s0 =
  let !(Commitment hl sl) = commit sc (d + 1) l
      !(Commitment hr sr) = commit sc (d + 1) r
  in  case hash_branch# sc st bk hl sl hr sr s0 of
        (# s1, h #) ->
          -- built strictly; a lazy tuple component would allocate a
          -- thunk for the node per level
          let !n = Node l (Commitment h (sl + sr)) r
          in  (# s1, n #)
{-# INLINE node# #-}

-- raise a single-leaf subtree one level, to the given depth
lift#
  :: Scheme -> Buffer -> Buffer -> Int -> Commitment -> Hash -> Key
  -> BS.ByteString
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #)
lift# sc st bk d c lh k v s0 = case raise# sc st bk k d (d + 1) c s0 of
  (# s1, c' #) -> let !t = Leaf c' lh k v in (# s1, t #)

-- insert a leaf, hashing it and rehashing the path to it over one pair
-- of state and block arrays
insert_leaf
  :: Payload s
  => Scheme -> Key -> BS.ByteString -> Word64 -> Tree s
  -> Either (Missing s) (Tree s)
insert_leaf sc k v s t0 = with_scratch $ \st bk s00 ->
  case hash_leaf# sc st bk k v s s00 of { (# s01, lh #) ->
  let go !d t s0 = case t of
        Empty -> done# (leaf# sc st bk d k lh s v s0)
        Leaf (Commitment _ s') lh' k' v'
          | k' == k   -> done# (leaf# sc st bk d k lh s v s0)
          | otherwise ->
              let p = diverge k k' d
                  -- the two leaves, beneath the branch where their paths
                  -- diverge
                  new = leaf# sc st bk (p + 1) k lh s v
                  old = leaf# sc st bk (p + 1) k' lh' s' v'
                  pair s1 =
                    case new s1 of { (# s2, a #) ->
                    case old s2 of { (# s3, b #) ->
                    if   bit k p
                    then node# sc st bk p b a s3
                    else node# sc st bk p a b s3 }}
                  -- the branches from there up to this depth, each with
                  -- an empty sibling
                  up j s1
                    | j == p = pair s1
                    | otherwise = case up (j + 1) s1 of
                        (# s2, c #)
                          | bit k j   -> node# sc st bk j Empty c s2
                          | otherwise -> node# sc st bk j c Empty s2
              in  done# (up d s0)
        Node l _ r
          | bit k d -> case go (d + 1) r s0 of
              (# s1, (# r' | #) #) -> done# (node# sc st bk d l r' s1)
              (# s1, (# | m #) #) -> (# s1, (# | m #) #)
          | otherwise -> case go (d + 1) l s0 of
              (# s1, (# l' | #) #) -> done# (node# sc st bk d l' r s1)
              (# s1, (# | m #) #) -> (# s1, (# | m #) #)
        Stub p c -> (# s0, (# | Missing p c #) #)
  in  case go 0 t0 s01 of
        (# s1, (# t | #) #) -> (# s1, Right t #)
        (# s1, (# | m #) #) -> (# s1, Left m #) }
{-# INLINABLE insert_leaf #-}

-- a leaf in a subtree being rebuilt in a batch: one being put, one
-- being deleted, or an existing one, kept with its hash
data Item =
    Put {-# UNPACK #-} !Key !BS.ByteString {-# UNPACK #-} !Word64
  | Del {-# UNPACK #-} !Key
  | Kept
      {-# UNPACK #-} !Key {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
      !BS.ByteString

item_key :: Item -> Key
item_key (Put k _ _) = k
item_key (Del k) = k
item_key (Kept k _ _ _) = k

-- items whose paths go left and right at a depth
split :: Int -> [Item] -> ([Item], [Item])
split d = go [] [] where
  go !ls !rs is = case is of
    [] -> (ls, rs)
    i : rest
      | bit (item_key i) d -> go ls (i : rs) rest
      | otherwise -> go (i : ls) rs rest

-- apply a batch of puts and deletions, at distinct keys, rehashing each
-- changed node once over one pair of state and block arrays. callers
-- rule out sum overflow
batch
  :: Payload s => Scheme -> [Item] -> Tree s -> Either (Missing s) (Tree s)
batch sc items0 t0 = with_scratch $ \st bk s00 ->
  let -- the subtree at a depth holding the given items, which agree on
      -- their paths above it
      go !d t items s0 = case t of
        Empty -> done# (build d items s0)
        Leaf (Commitment _ s') lh' k' v'
          | any ((== k') . item_key) items -> done# (build d items s0)
          | otherwise -> done# (build d (Kept k' lh' s' v' : items) s0)
        Node l _ r ->
          let (ls, rs) = split d items
              side u is s1
                | null is   = (# s1, (# u | #) #)
                | otherwise = go (d + 1) u is s1
          in  case side l ls s0 of
                (# s1, (# | m #) #) -> (# s1, (# | m #) #)
                (# s1, (# l' | #) #) -> case side r rs s1 of
                  (# s2, (# | m #) #) -> (# s2, (# | m #) #)
                  (# s2, (# r' | #) #) -> done# (node# sc st bk d l' r' s2)
        Stub p c -> (# s0, (# | Missing p c #) #)

      -- the subtree at a depth holding exactly the given items' leaves
      build !d items s0 = case filter live items of
        [] -> (# s0, Empty #)
        [Put k v s] -> case hash_leaf# sc st bk k v s s0 of
          (# s1, lh #) -> leaf# sc st bk d k lh s v s1
        [Kept k lh s v] -> leaf# sc st bk d k lh s v s0
        is ->
          let (ls, rs) = split d is
          in  case build (d + 1) ls s0 of
                (# s1, l #) -> case build (d + 1) rs s1 of
                  (# s2, r #) -> node# sc st bk d l r s2

      live (Del _) = False
      live _ = True
  in  case go 0 t0 items0 s00 of
        (# s1, (# t | #) #) -> (# s1, Right t #)
        (# s1, (# | m #) #) -> (# s1, Left m #)
{-# INLINABLE batch #-}

-- tree -----------------------------------------------------------------------

-- | The empty tree.
empty :: Tree s
empty = Empty

-- | Insert a value and sum at a key under a scheme, replacing any
--   existing leaf.
--
--   Returns 'Nothing' if the tree's sum would overflow, or what the
--   insertion needed, if it was held elsewhere.
insert_with
  :: Payload s
  => Scheme -> Key -> BS.ByteString -> Word64 -> Tree s
  -> Either (Missing s) (Maybe (Tree s))
insert_with sc k v s t = with_leaf k t (go 0) (\was _ -> go was) Left where
  go was
    | s > maxBound - (total t - was) = Right Nothing
    -- an empty value with zero sum is the empty leaf
    | BS.null v && s == 0 = Just <$> delete_with sc k t
    | otherwise = Just <$> insert_leaf sc k v s t
{-# INLINABLE insert_with #-}

-- | Insert many values and sums under a scheme, as if one at a time,
--   but rehashing each changed node once.
--
--   Where a key appears more than once, its last appearance wins, and
--   an empty value with zero sum deletes whatever is at its key.
--   Returns 'Nothing' if the resulting tree's sum would overflow, or
--   what the insertions needed, if it was held elsewhere.
insert_many_with
  :: Payload s
  => Scheme -> [(Key, BS.ByteString, Word64)] -> Tree s
  -> Either (Missing s) (Maybe (Tree s))
insert_many_with sc kvs t
    | null items = Right (Just t)
    | otherwise = do
        was <- traverse (\i -> with_leaf (item_key i) t
                 (Right 0) (\s _ -> Right s) Left) items
        let after = toInteger (total t) + sum (zipWith change items was)
        if   after > toInteger (maxBound :: Word64)
        then Right Nothing
        else Just <$> batch sc items t
  where
    -- the last item at each key
    items = last_each (sortBy (comparing (\(k, _, _) -> k)) kvs)
    last_each ((k, v, s) : rest@((k', _, _) : _))
      | k == k' = last_each rest
      | otherwise = item k v s : last_each rest
    last_each [(k, v, s)] = [item k v s]
    last_each [] = []

    item k v s
      | BS.null v && s == 0 = Del k
      | otherwise = Put k v s

    -- each item's change to the tree's sum, given what's at its key
    change i was = case i of
      Put _ _ s -> toInteger s - toInteger was
      Del _ -> negate (toInteger was)
      Kept {} -> 0
{-# INLINABLE insert_many_with #-}

-- | Delete the leaf at a key under a scheme.
--
--   Returns what the deletion needed, if it was held elsewhere.
delete_with
  :: Payload s => Scheme -> Key -> Tree s -> Either (Missing s) (Tree s)
delete_with sc k t0 = with_leaf k t0 (Right t0) (\_ _ -> deleted) Left where
  deleted = with_scratch $ \st bk s00 ->
    let go !d t s0 = case t of
          -- the key is present, so a leaf on its path is its own
          Empty -> (# s0, (# Empty | #) #)
          Leaf {} -> (# s0, (# Empty | #) #)
          Node l _ r
            | bit k d -> case go (d + 1) r s0 of
                (# s1, (# r' | #) #) -> done# (node# sc st bk d l r' s1)
                (# s1, (# | m #) #) -> (# s1, (# | m #) #)
            | otherwise -> case go (d + 1) l s0 of
                (# s1, (# l' | #) #) -> done# (node# sc st bk d l' r s1)
                (# s1, (# | m #) #) -> (# s1, (# | m #) #)
          Stub p c -> (# s0, (# | Missing p c #) #)
    in  case go 0 t0 s00 of
          (# s1, (# t | #) #) -> (# s1, Right t #)
          (# s1, (# | m #) #) -> (# s1, Left m #)
{-# INLINABLE delete_with #-}

-- | Look up the value and sum at a key.
--
--   Returns what the lookup needed, if it was held elsewhere.
lookup :: Key -> Tree s -> Either (Missing s) (Maybe (BS.ByteString, Word64))
lookup k t = with_leaf k t (Right Nothing) (\s v -> Right (Just (v, s))) Left
{-# INLINE lookup #-}

-- | Load the subtrees held elsewhere along a key's path, down to the
--   key's slot, via a loader given what stands for each one and its
--   commitment, which returns its contents with its own subtrees held
--   elsewhere.
--
--   Operations at a key need only its path loaded.
expand
  :: Monad m => (s -> Commitment -> m (Tree s)) -> Key -> Tree s
  -> m (Tree s)
expand load k = go 0 where
  go !d t = case t of
    Stub p c -> load p c >>= go d
    Node l c r
      | bit k d   -> (\r' -> Node l c r') <$> go (d + 1) r
      | otherwise -> (\l' -> Node l' c r) <$> go (d + 1) l
    Empty -> pure t
    Leaf {} -> pure t

-- | The tree's root commitment under a scheme.
root_with :: Scheme -> Tree s -> Commitment
root_with sc = commit sc 0

-- proofs ---------------------------------------------------------------------

-- | Another key's leaf, at which a key's path ends: its key, the hash
--   of its value, and its sum.
data Neighbor =
  Neighbor {-# UNPACK #-} !Key {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
  deriving (Eq, Show)

-- whether climbing from a commitment at the given depth on a key's
-- path, over that many siblings from the deepest up, reaches a root,
-- hashing over the given state and block arrays; a branch's sum mustn't
-- overflow. callers ensure the depth is at most 256
climb#
  :: Scheme -> Buffer -> Buffer -> Key -> Int -> Commitment
  -> [Commitment] -> Commitment
  -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Bool #)
climb# sc st bk k d0 (Commitment h0 n0) sibs r = go (d0 - 1) h0 n0 sibs where
  go !d !h !hs ps s0 = case ps of
    [] -> (# s0, d == -1 && Commitment h hs == r #)
    Commitment g gs : rest
      | d < 0 || gs > maxBound - hs -> (# s0, False #)
      | otherwise ->
          case if   bit k d
               then hash_branch# sc st bk g gs h hs s0
               else hash_branch# sc st bk h hs g gs s0 of
            (# s1, p #) -> go (d - 1) p (hs + gs) rest s1

-- | The siblings along a key's path in a split tree, from the deepest up
--   to the root's, and the leaf the path ends at, where that's another
--   key's.
--
--   Returns what the proof needed, if it was held elsewhere.
prove_split
  :: Key -> Tree s -> Either (Missing s) (Maybe Neighbor, [Commitment])
prove_split k = go 0 [] where
  go !d acc t = case t of
    Empty -> Right (Nothing, acc)
    Leaf (Commitment _ s) _ k' v
      | k' == k   -> Right (Nothing, acc)
      | otherwise -> Right (Just (Neighbor k' (hash_value v) s), acc)
    Node l _ r
      | bit k d   -> go (d + 1) (commit Split (d + 1) l : acc) r
      | otherwise -> go (d + 1) (commit Split (d + 1) r : acc) l
    Stub p c -> Left (Missing p c)

-- | Verify that a value and sum sit at a key in a split tree, under a
--   root, given the siblings along the key's path, and the leaf the path
--   ends at, where that's another key's.
--
--   An empty value with zero sum verifies the key's exclusion, for which
--   the path must end at an empty subtree or at another key's leaf.
--   Proofs with more than 256 siblings, or whose branch sums overflow,
--   are rejected.
verify_split
  :: Key -> BS.ByteString -> Word64 -> Maybe Neighbor -> [Commitment]
  -> Commitment -> Bool
verify_split k v s nb sibs r = d <= _HEIGHT && with_scratch go where
  d = length sibs
  vacant = BS.null v && s == 0
  up st bk c = climb# Split st bk k d c sibs r
  go st bk s0 = case nb of
    Nothing
      | vacant    -> up st bk (commit Split d Empty) s0
      | otherwise -> case hash_leaf# Split st bk k v s s0 of
          (# s1, h #) -> up st bk (Commitment h s) s1
    Just (Neighbor k' h s')
      | vacant && k' /= k && agree k k' d ->
          case hash_leaf_split# st bk (key_hash k') h s' s0 of
            (# s1, h' #) -> up st bk (Commitment h' s') s1
      | otherwise -> (# s0, False #)

-- | The siblings along a key's path in an aggregate tree: all 256 of
--   them, from the leaf up to the root's.
--
--   Returns what the proof needed, if it was held elsewhere.
prove_aggregate :: Key -> Tree s -> Either (Missing s) [Commitment]
prove_aggregate k t0 = with_scratch $ \st bk ->
  let -- empty siblings at depths j through j1 - 1
      pad j j1 acc
        | j == j1 = acc
        | otherwise =
            pad (j + 1) j1 (commit Aggregate (j + 1) Empty : acc)
      go !d acc t s0 = case t of
        Empty -> (# s0, Right (pad d _HEIGHT acc) #)
        Leaf (Commitment _ s') lh' k' _
          | k' == k   -> (# s0, Right (pad d _HEIGHT acc) #)
          | otherwise ->
              -- the leaf's subtree is the sibling where the paths diverge
              let p  = diverge k k' d
                  c0 = Commitment lh' s'
              in  case raise# Aggregate st bk k' (p + 1) _HEIGHT c0 s0 of
                    (# s1, c #) ->
                      (# s1, Right (pad (p + 1) _HEIGHT (c : pad d p acc)) #)
        Node l _ r
          | bit k d   -> go (d + 1) (commit Aggregate (d + 1) l : acc) r s0
          | otherwise -> go (d + 1) (commit Aggregate (d + 1) r : acc) l s0
        Stub q c -> (# s0, Left (Missing q c) #)
  in  go 0 [] t0

-- | Verify that a value and sum sit at a key in an aggregate tree, under
--   a root, given the 256 siblings along the key's path.
--
--   An empty value with zero sum verifies the key's exclusion. Proofs
--   whose branch sums overflow are rejected.
verify_aggregate
  :: Key -> BS.ByteString -> Word64 -> [Commitment] -> Commitment -> Bool
verify_aggregate k v s sibs r =
     length sibs == _HEIGHT
  && with_scratch (\st bk -> climb# Aggregate st bk k _HEIGHT leaf sibs r)
  where
    leaf = Commitment (hash_leaf_aggregate v s) s