commit f49cc0c4d13d6b4a84a4f3bfd1a7bee2d1b14023
parent 09db46ee0fb3e5a98f06b5157ced94475548c386
Author: Jared Tobin <jared@jtobin.io>
Date: Wed, 4 Nov 2026 21:02:20 +0400
lib: compacted tree representation
A subtree holding a single leaf is now stored as that leaf, at the
subtree's height, along with the subtree's commitment there and the
leaf's own hash and key; a branch is stored only where two or more
leaves lie beneath it. Commitments, roots, and proofs are unchanged.
A 1024-leaf tree now holds ~198KB live, down from ~16MB (~190 bytes
per leaf, down from ~16KB). Lookups, proofs, and deletes walk only
the stored branches, and insert allocates only its new path. A fresh
key landing in a leaf's slot rehashes both leaves' paths beneath the
new branch, so costs about twice a fresh key landing in an empty slot.
Tests add a compactness property, and label how often exclusion
proofs end at another key's leaf.
Diffstat:
2 files changed, 172 insertions(+), 48 deletions(-)
diff --git a/lib/Data/MSSMT/Internal.hs b/lib/Data/MSSMT/Internal.hs
@@ -78,11 +78,14 @@ data Commitment = Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64
-- | A merkle-sum sparse merkle tree.
--
--- Leaves sit at depth 256, and empty subtrees are collapsed to
--- 'Empty', so a tree holding n leaves has at most 256 * n branches.
+-- 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.
data Tree =
Empty
- | Leaf {-# UNPACK #-} !Commitment !BS.ByteString
+ -- 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 !Key !BS.ByteString
| Node !Tree {-# UNPACK #-} !Commitment !Tree
deriving (Eq, Show)
@@ -109,21 +112,26 @@ empties_aggregate :: PA.PrimArray Word64
empties_aggregate = empties_with Aggregate
{-# NOINLINE empties_aggregate #-}
--- commitment of a subtree at the given depth
-commit :: Scheme -> Int -> Tree -> Commitment
-commit sc d Empty = Commitment (Hash (ix 0) (ix 1) (ix 2) (ix 3)) 0 where
+-- hash of the empty subtree at the given depth
+empty_hash :: Scheme -> Int -> Hash
+empty_hash sc d = Hash (ix 0) (ix 1) (ix 2) (ix 3) where
es = case sc of
Split -> empties
Aggregate -> empties_aggregate
ix i = PA.indexPrimArray es (4 * d + i)
-commit _ _ (Leaf p _) = p
-commit _ _ (Node _ p _) = p
+{-# INLINE empty_hash #-}
+
+-- commitment of a subtree at the given depth
+commit :: Scheme -> Int -> Tree -> Commitment
+commit sc d Empty = Commitment (empty_hash sc d) 0
+commit _ _ (Leaf c _ _ _) = c
+commit _ _ (Node _ c _) = c
{-# INLINE commit #-}
-- sum of a subtree
total :: Tree -> Word64
total Empty = 0
-total (Leaf (Commitment _ s) _) = s
+total (Leaf (Commitment _ s) _ _ _) = s
total (Node _ (Commitment _ s) _) = s
{-# INLINE total #-}
@@ -132,19 +140,48 @@ 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
-leaf v s
- | BS.null v && s == 0 = Empty
- | otherwise = Leaf (Commitment (hash_leaf v s) s) v
-
--- branch at the given depth, hashed over the given state and block
--- arrays; two empty children make an empty subtree, as hashing them
--- would. callers rule out sum overflow
+-- 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, pairing it with an empty sibling at each level between
+raise#
+ :: Scheme -> Buffer -> Buffer -> Key -> Int -> Int -> Commitment
+ -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Commitment #)
+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 #)
+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#
:: Scheme -> Buffer -> Buffer -> Int -> Tree -> Tree
-> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree #)
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
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
@@ -156,25 +193,49 @@ node# sc st bk d l r s0 =
in (# s1, n #)
{-# 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
-{-# INLINE children #-}
-
--- replace the subtree at the given key's leaf, rehashing the path to it
--- over one pair of state and block arrays
-update :: Scheme -> Key -> Tree -> Tree -> Tree
-update sc k new t0 = with_scratch $ \st bk ->
- let go !d t s0
- | d == _HEIGHT = (# s0, new #)
- | otherwise = case children t of
- (# l, r #)
- | bit k d -> case go (d + 1) r s0 of
- (# s1, r' #) -> node# sc st bk d l r' s1
- | otherwise -> case go (d + 1) l s0 of
- (# s1, l' #) -> node# sc st bk d l' r s1
+-- 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 #)
+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, given its hash, rehashing the path to it over one pair
+-- of state and block arrays
+insert_leaf
+ :: Scheme -> Key -> Hash -> Word64 -> BS.ByteString -> Tree -> Tree
+insert_leaf sc k lh s v t0 = with_scratch $ \st bk ->
+ let go !d t s0 = case t of
+ Empty -> leaf# sc st bk d k lh s v s0
+ Leaf (Commitment _ s') lh' k' v'
+ | k' == k -> 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 up d s0
+ Node l _ r
+ | bit k d -> case go (d + 1) r s0 of
+ (# s1, r' #) -> node# sc st bk d l r' s1
+ | otherwise -> case go (d + 1) l s0 of
+ (# s1, l' #) -> node# sc st bk d l' r s1
in go 0 t0
-- tree -----------------------------------------------------------------------
@@ -194,7 +255,9 @@ insert_with
:: Scheme -> Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree
insert_with sc k v s t
| s > maxBound - rest = Nothing
- | otherwise = Just (update sc k (leaf v s) t)
+ -- 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 (hash_leaf v s) s v t)
where
rest = total t - maybe 0 snd (lookup k t)
@@ -204,14 +267,28 @@ delete = delete_with Split
-- | 'delete', under a scheme.
delete_with :: Scheme -> Key -> Tree -> Tree
-delete_with sc k = update sc k Empty
+delete_with sc k t0 = case lookup k t0 of
+ Nothing -> t0
+ Just _ -> with_scratch $ \st bk ->
+ 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' #) -> node# sc st bk d l r' s1
+ | otherwise -> case go (d + 1) l s0 of
+ (# s1, l' #) -> node# sc st bk d l' r s1
+ in go 0 t0
-- | Look up the value and sum at a key.
lookup :: Key -> Tree -> Maybe (BS.ByteString, Word64)
lookup k = go 0 where
go !d t = case t of
Empty -> Nothing
- Leaf (Commitment _ s) v -> Just (v, s)
+ Leaf (Commitment _ s) _ k' v
+ | k' == k -> Just (v, s)
+ | otherwise -> Nothing
Node l _ r -> go (d + 1) (if bit k d then r else l)
-- | The tree's root commitment.
@@ -237,13 +314,27 @@ prove = prove_with Split
-- | 'prove', under a scheme.
prove_with :: Scheme -> Key -> Tree -> Proof
-prove_with sc k = Proof . go 0 [] where
- go !d acc t
- | d == _HEIGHT = acc
- | otherwise = case children t of
- (# l, r #)
- | bit k d -> go (d + 1) (commit sc (d + 1) l : acc) r
- | otherwise -> go (d + 1) (commit sc (d + 1) r : acc) l
+prove_with sc 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 (Commitment (empty_hash sc (j + 1)) 0 : acc)
+ go !d acc t s0 = case t of
+ Empty -> (# s0, Proof (pad d _HEIGHT acc) #)
+ Leaf (Commitment _ s') lh' k' _
+ | k' == k -> (# s0, Proof (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# sc st bk k' (p + 1) _HEIGHT c0 s0 of
+ (# s1, c #) ->
+ (# s1, Proof (pad (p + 1) _HEIGHT (c : pad d p acc)) #)
+ Node l _ r
+ | bit k d -> go (d + 1) (commit sc (d + 1) l : acc) r s0
+ | otherwise -> go (d + 1) (commit sc (d + 1) r : acc) l s0
+ in go 0 [] t0
-- | Verify that a value and sum sit at a key, under a root.
--
diff --git a/test/Main.hs b/test/Main.hs
@@ -4,6 +4,7 @@ module Main where
import Control.Monad (foldM)
import qualified Data.Aeson as A
+import Data.Bits (testBit)
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import Data.Maybe (isJust)
@@ -154,6 +155,32 @@ big = Q.oneof [
raw :: M.Map Key a -> M.Map BS.ByteString a
raw = M.mapKeysMonotonic (\(I.Key bs) -> bs)
+-- path bit at the given depth; LSB-first within each byte
+kbit :: Key -> Int -> Bool
+kbit (I.Key bs) d = testBit (BS.index bs (d `quot` 8)) (d `rem` 8)
+
+-- every branch holds two or more leaves, and every leaf's key follows
+-- its path
+compact :: Tree -> Bool
+compact = isJust . go 0 [] where
+ go :: Int -> [Bool] -> Tree -> Maybe Int
+ go _ _ I.Empty = Just 0
+ go d path (I.Leaf _ _ k _)
+ | reverse path == fmap (kbit k) [0 .. d - 1] = Just 1
+ | otherwise = Nothing
+ go d path (I.Node l _ r) = do
+ a <- go (d + 1) (False : path) l
+ b <- go (d + 1) (True : path) r
+ if a + b >= 2 then Just (a + b) else Nothing
+
+-- whether a key's path ends at another key's leaf
+at_leaf :: Key -> Tree -> Bool
+at_leaf k = go 0 where
+ go d t = case t of
+ I.Empty -> False
+ I.Leaf _ _ k' _ -> k' /= k
+ I.Node l _ r -> go (d + 1) (if kbit k d then r else l)
+
with_tree :: [E] -> (Tree -> Q.Property) -> Q.Property
with_tree es f = case build es of
Nothing -> Q.counterexample "overflow" False
@@ -184,6 +211,11 @@ properties = testGroup "properties" [
let Commitment h s = I.root_with I.Aggregate t
in (serialize_hash h, s) Q.=== R.root_aggregate (raw (model es))
+ , Q.testProperty "trees are compact" $ \(Es _ es) ->
+ Q.forAll (Q.sublistOf (M.keys (model es))) $ \ks ->
+ with_tree es $ \t ->
+ compact t Q..&&. compact (foldr delete t ks)
+
, Q.testProperty "trees are independent of insertion history" $
\(Es _ es) ->
build es Q.=== build [E k v s | (k, (v, s)) <- M.toList (model es)]
@@ -207,7 +239,8 @@ properties = testGroup "properties" [
Q.forAll (pick x) $ \k ->
M.notMember k (model es) Q.==>
with_tree es $ \t ->
- Q.property $ verify k mempty 0 (prove k t) (root t)
+ Q.classify (at_leaf k t) "ends at another leaf" $
+ verify k mempty 0 (prove k t) (root t)
, Q.testProperty "proofs reject a wrong value or sum" $ \(Es _ es) ->
with_tree es $ \t ->