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

commit 2cd79d2aeea095a10ddd11de572309ee2b3f377a
parent 729efb7649715237653d5153b45c604fd5654cbf
Author: Jared Tobin <jared@jtobin.io>
Date:   Wed,  4 Nov 2026 23:11:26 +0400

lib: complete and partial trees as Tree s

A tree is now a Tree s, whose stubs carry an s: a complete tree is a
Tree Void, which can't have stubs, and one held partly elsewhere a
Tree Kind. Operations return Either (Missing s), the stub they needed,
where they meet one on their path, rather than calling error; for
complete trees, complete eliminates the impossible case, and the
public modules wrap Tree Void.

A lone stubbed leaf left beside an empty subtree by a deletion now
moves up as it is in a split tree, and stays beneath its branch in an
aggregate one, whose commitment is that of the leaf moved up a level.
So operations need only their own paths loaded, and expand_deleting
is gone.

Tests check that operations on unloaded paths report the stubs they
need. Inserts, deletes, and proofs cost 3-5% more for the checks.

Diffstat:
Mbench/Fixtures.hs | 7++++---
Mlib/Data/MSSMT/Aggregate.hs | 14++++++++------
Mlib/Data/MSSMT/Internal.hs | 301+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mlib/Data/MSSMT/Split.hs | 14++++++++------
Mtest/Main.hs | 85+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
5 files changed, 252 insertions(+), 169 deletions(-)

diff --git a/bench/Fixtures.hs b/bench/Fixtures.hs @@ -16,6 +16,7 @@ import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B8 import Data.MSSMT import qualified Data.MSSMT.Internal as I +import Data.Void (Void) import Data.Word (Word64) -- all fields are strict, so WHNF is NF @@ -63,17 +64,17 @@ fixtures = Fixtures t (root t) k v s (prove k t) o (prove o t) n where raw = case foldM ins I.empty (leaves 1024) of Just r -> r Nothing -> error "bang" - ins r (k', v', s') = I.insert_with I.Split k' v' s' r + ins r (k', v', s') = I.complete (I.insert_with I.Split k' v' s' r) -- a key whose path ends at the given key's leaf, diverging from it just -- beneath: the given key, with the bit beneath its leaf flipped -near :: Key -> I.Tree -> Key +near :: Key -> I.Tree Void -> Key near (I.Key bs) = flip_at . go 0 where + go :: Int -> I.Tree Void -> Int go !d t = case t of I.Node l _ r -> go (d + 1) (if kbit d then r else l) I.Leaf {} -> d I.Empty -> d - I.Stub {} -> d kbit d = testBit (BS.index bs (d `quot` 8)) (d `rem` 8) flip_at d = case BS.splitAt (d `quot` 8) bs of (a, b) | Just (w, c) <- BS.uncons b diff --git a/lib/Data/MSSMT/Aggregate.hs b/lib/Data/MSSMT/Aggregate.hs @@ -50,12 +50,13 @@ import Data.MSSMT.Internal ( , serialize_hash ) import qualified Data.MSSMT.Internal as I +import Data.Void (Void) import Data.Word (Word64) import Prelude hiding (lookup) -- | A merkle-sum sparse merkle tree whose branches commit to their -- children's hashes and the sum of their sums. -newtype Tree = Tree I.Tree +newtype Tree = Tree (I.Tree Void) deriving (Eq, Show) -- | The empty tree. @@ -66,7 +67,7 @@ empty = Tree I.empty -- -- Returns 'Nothing' if the tree's sum would overflow. insert :: Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree -insert k v s (Tree t) = coerce (I.insert_with Aggregate k v s t) +insert k v s (Tree t) = coerce (I.complete (I.insert_with Aggregate k v s t)) -- | Insert many values and sums, as if one at a time, but rehashing -- each changed node once. @@ -75,15 +76,16 @@ insert k v s (Tree t) = coerce (I.insert_with Aggregate k v s t) -- an empty value with zero sum deletes whatever is at its key. -- Returns 'Nothing' if the resulting tree's sum would overflow. insert_many :: [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree -insert_many kvs (Tree t) = coerce (I.insert_many_with Aggregate kvs t) +insert_many kvs (Tree t) = + coerce (I.complete (I.insert_many_with Aggregate kvs t)) -- | Delete the leaf at a key. delete :: Key -> Tree -> Tree -delete k (Tree t) = Tree (I.delete_with Aggregate k t) +delete k (Tree t) = Tree (I.complete (I.delete_with Aggregate k t)) -- | Look up the value and sum at a key. lookup :: Key -> Tree -> Maybe (BS.ByteString, Word64) -lookup k (Tree t) = I.lookup k t +lookup k (Tree t) = I.complete (I.lookup k t) -- | The tree's root commitment. root :: Tree -> Commitment @@ -98,7 +100,7 @@ newtype Proof = Proof [Commitment] -- -- If no leaf exists at the key, this proves its exclusion. prove :: Key -> Tree -> Proof -prove k (Tree t) = Proof (I.prove_aggregate k t) +prove k (Tree t) = Proof (I.complete (I.prove_aggregate k t)) -- | Verify that a value and sum sit at a key, under a root. -- diff --git a/lib/Data/MSSMT/Internal.hs b/lib/Data/MSSMT/Internal.hs @@ -1,6 +1,8 @@ {-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE BangPatterns #-} +{-# LANGUAGE EmptyCase #-} {-# LANGUAGE MagicHash #-} +{-# LANGUAGE UnboxedSums #-} {-# LANGUAGE UnboxedTuples #-} -- | @@ -38,8 +40,10 @@ module Data.MSSMT.Internal ( -- * Tree , Tree(..) , Kind(..) + , Payload(..) + , Missing(..) + , complete , expand - , expand_deleting , empty , insert_with , insert_many_with @@ -62,6 +66,7 @@ import Data.MSSMT.Hash import Data.List (partition, 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#) @@ -81,26 +86,50 @@ key bs data Commitment = Commitment {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64 deriving (Eq, Show) --- | A merkle-sum sparse merkle tree. +-- | 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. -data Tree = +-- 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 !Key !BS.ByteString - | Node !Tree {-# UNPACK #-} !Commitment !Tree - -- a subtree held elsewhere, as in a store: what it holds, and its - -- commitment - | Stub !Kind {-# UNPACK #-} !Commitment + | 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 @@ -126,7 +155,7 @@ empty_hash Aggregate d = Hash (ix 0) (ix 1) (ix 2) (ix 3) where {-# INLINE empty_hash #-} -- commitment of a subtree at the given depth -commit :: Scheme -> Int -> Tree -> Commitment +commit :: Scheme -> Int -> Tree s -> Commitment commit sc d Empty = Commitment (empty_hash sc d) 0 commit _ _ (Leaf c _ _ _) = c commit _ _ (Node _ c _) = c @@ -134,7 +163,7 @@ commit _ _ (Stub _ c) = c {-# INLINE commit #-} -- sum of a subtree -total :: Tree -> Word64 +total :: Tree s -> Word64 total Empty = 0 total (Leaf (Commitment _ s) _ _ _) = s total (Node _ (Commitment _ s) _) = s @@ -163,21 +192,28 @@ hash_leaf# Split st bk k 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 -with_leaf :: Key -> Tree -> r -> (Word64 -> BS.ByteString -> r) -> r -with_leaf k t0 none some = go 0 t0 where +-- 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 {} -> error unloaded + Stub p c -> stub (Missing p c) {-# INLINE with_leaf #-} --- operations at a key require its path to be loaded -unloaded :: String -unloaded = "mssmt: unloaded subtree on an operation's path" +-- 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 @@ -209,7 +245,7 @@ raise# sc st bk k to from (Commitment h0 s) = go (from - 1) h0 where leaf# :: Scheme -> Buffer -> Buffer -> Int -> Key -> Hash -> Word64 -> BS.ByteString - -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree #) + -> 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 #) @@ -219,17 +255,19 @@ leaf# sc st bk d k lh s v s0 = -- 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 #) + :: Payload s + => Scheme -> Buffer -> Buffer -> Int -> Tree s -> Tree s + -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree s #) node# _ _ _ _ Empty Empty s0 = (# s0, Empty #) --- 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 must be loaded -node# Split _ _ _ Empty t@(Stub Single _) s0 = (# s0, t #) -node# Split _ _ _ t@(Stub Single _) Empty s0 = (# s0, t #) -node# Aggregate _ _ _ Empty (Stub Single _) _ = error unloaded -node# Aggregate _ _ _ (Stub Single _) Empty _ = error unloaded 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 @@ -245,19 +283,22 @@ node# sc st bk d l r s0 = lift# :: Scheme -> Buffer -> Buffer -> Int -> Commitment -> Hash -> Key -> BS.ByteString - -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree #) + -> 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 :: Scheme -> Key -> BS.ByteString -> Word64 -> Tree -> Tree +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 -> leaf# sc st bk d k lh s v s0 + Empty -> done# (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 + | 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 @@ -278,14 +319,19 @@ insert_leaf sc k v s t0 = with_scratch $ \st bk s00 -> (# 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 + in done# (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 + (# 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' #) -> node# sc st bk d l' r s1 - Stub {} -> error unloaded - in go 0 t0 s01 } + (# 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 @@ -302,22 +348,27 @@ item_key (Kept k _ _ _) = k -- 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 :: Scheme -> [Item] -> Tree -> Tree -batch sc items0 t0 = with_scratch $ \st bk -> +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 -> build d items s0 + Empty -> done# (build d items s0) Leaf (Commitment _ s') lh' k' v' - | any ((== k') . item_key) items -> build d items s0 - | otherwise -> build d (Kept k' lh' s' v' : items) s0 + | 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) = partition (\i -> not (bit (item_key i) d)) items - in case if null ls then (# s0, l #) else go (d + 1) l ls s0 of - (# s1, l' #) -> - case if null rs then (# s1, r #) else go (d + 1) r rs s1 of - (# s2, r' #) -> node# sc st bk d l' r' s2 - Stub {} -> error unloaded + 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 @@ -333,40 +384,54 @@ batch sc items0 t0 = with_scratch $ \st bk -> live (Del _) = False live _ = True - in go 0 t0 items0 + 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 +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. +-- Returns 'Nothing' if the tree's sum would overflow, or what the +-- insertion needed, if it was held elsewhere. insert_with - :: Scheme -> Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree -insert_with sc k v s t - | s > maxBound - rest = Nothing + :: 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) - where - rest = total t - with_leaf k t 0 const + | 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. +-- Returns 'Nothing' if the resulting tree's sum would overflow, or +-- what the insertions needed, if it was held elsewhere. insert_many_with - :: Scheme -> [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree + :: Payload s + => Scheme -> [(Key, BS.ByteString, Word64)] -> Tree s + -> Either (Missing s) (Maybe (Tree s)) insert_many_with sc kvs t - | null items = Just t - | after > toInteger (maxBound :: Word64) = Nothing - | otherwise = Just (batch sc items 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) @@ -380,77 +445,64 @@ insert_many_with sc kvs t | BS.null v && s == 0 = Del k | otherwise = Put k v s - -- the resulting tree's sum - after = toInteger (total t) + sum (fmap change items) - change i = - let k = item_key i - was = toInteger (with_leaf k t 0 const) - in case i of - Put _ _ s -> toInteger s - was - Del _ -> negate was - Kept {} -> 0 + -- 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. -delete_with :: Scheme -> Key -> Tree -> Tree -delete_with sc k t0 = with_leaf k t0 t0 $ \_ _ -> with_scratch $ \st bk -> +-- +-- 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 #) + 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 + (# 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' #) -> node# sc st bk d l' r s1 - Stub {} -> error unloaded - in go 0 t0 + (# 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. -lookup :: Key -> Tree -> Maybe (BS.ByteString, Word64) -lookup k t = with_leaf k t Nothing (\s v -> Just (v, s)) +-- +-- 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 each one's kind and commitment, which --- returns its contents with its own subtrees held elsewhere. +-- 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 require its path to be loaded. +-- Operations at a key need only its path loaded. expand - :: Monad m => (Kind -> Commitment -> m Tree) -> Key -> Tree -> m Tree -expand = expand_with False - --- | 'expand', loading too each single leaf held elsewhere beside the --- key's path. --- --- Deleting at a key in an aggregate tree requires these to be loaded, --- since a deletion can move them. -expand_deleting - :: Monad m => (Kind -> Commitment -> m Tree) -> Key -> Tree -> m Tree -expand_deleting = expand_with True - -expand_with - :: Monad m - => Bool -> (Kind -> Commitment -> m Tree) -> Key -> Tree -> m Tree -expand_with singles load k = go 0 where + :: 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 kd c -> load kd c >>= go d + Stub p c -> load p c >>= go d Node l c r - | bit k d -> do - r' <- go (d + 1) r - l' <- beside l - pure (Node l' c r') - | otherwise -> do - l' <- go (d + 1) l - r' <- beside r - pure (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 - beside t = case t of - Stub Single c | singles -> load Single c - _ -> pure t - -- | The tree's root commitment under a scheme. -root_with :: Scheme -> Tree -> Commitment +root_with :: Scheme -> Tree s -> Commitment root_with sc = commit sc 0 -- proofs --------------------------------------------------------------------- @@ -482,17 +534,20 @@ climb# sc st bk k d0 (Commitment h0 n0) sibs r = go (d0 - 1) h0 n0 sibs where -- | 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. -prove_split :: Key -> Tree -> (Maybe Neighbor, [Commitment]) +-- +-- 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 -> (Nothing, acc) + Empty -> Right (Nothing, acc) Leaf (Commitment _ s) _ k' v - | k' == k -> (Nothing, acc) - | otherwise -> (Just (Neighbor k' (hash_value v) s), acc) + | 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 {} -> error unloaded + 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 @@ -522,7 +577,9 @@ verify_split k v s nb sibs r = d <= _HEIGHT && with_scratch go where -- | The siblings along a key's path in an aggregate tree: all 256 of -- them, from the leaf up to the root's. -prove_aggregate :: Key -> Tree -> [Commitment] +-- +-- 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 @@ -530,20 +587,20 @@ prove_aggregate k t0 = with_scratch $ \st bk -> | otherwise = pad (j + 1) j1 (commit Aggregate (j + 1) Empty : acc) go !d acc t s0 = case t of - Empty -> (# s0, pad d _HEIGHT acc #) + Empty -> (# s0, Right (pad d _HEIGHT acc) #) Leaf (Commitment _ s') lh' k' _ - | k' == k -> (# s0, pad d _HEIGHT acc #) + | 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, pad (p + 1) _HEIGHT (c : pad d p acc) #) + (# 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 {} -> error unloaded + 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 diff --git a/lib/Data/MSSMT/Split.hs b/lib/Data/MSSMT/Split.hs @@ -53,12 +53,13 @@ import Data.MSSMT.Internal ( , serialize_hash ) import qualified Data.MSSMT.Internal as I +import Data.Void (Void) import Data.Word (Word64) import Prelude hiding (lookup) -- | A merkle-sum sparse merkle tree whose branches commit to the -- hash and sum of each of their children. -newtype Tree = Tree I.Tree +newtype Tree = Tree (I.Tree Void) deriving (Eq, Show) -- | The empty tree. @@ -69,7 +70,7 @@ empty = Tree I.empty -- -- Returns 'Nothing' if the tree's sum would overflow. insert :: Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree -insert k v s (Tree t) = coerce (I.insert_with Split k v s t) +insert k v s (Tree t) = coerce (I.complete (I.insert_with Split k v s t)) -- | Insert many values and sums, as if one at a time, but rehashing -- each changed node once. @@ -78,15 +79,16 @@ insert k v s (Tree t) = coerce (I.insert_with Split k v s t) -- an empty value with zero sum deletes whatever is at its key. -- Returns 'Nothing' if the resulting tree's sum would overflow. insert_many :: [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree -insert_many kvs (Tree t) = coerce (I.insert_many_with Split kvs t) +insert_many kvs (Tree t) = + coerce (I.complete (I.insert_many_with Split kvs t)) -- | Delete the leaf at a key. delete :: Key -> Tree -> Tree -delete k (Tree t) = Tree (I.delete_with Split k t) +delete k (Tree t) = Tree (I.complete (I.delete_with Split k t)) -- | Look up the value and sum at a key. lookup :: Key -> Tree -> Maybe (BS.ByteString, Word64) -lookup k (Tree t) = I.lookup k t +lookup k (Tree t) = I.complete (I.lookup k t) -- | The tree's root commitment. root :: Tree -> Commitment @@ -104,7 +106,7 @@ data Proof = Proof !(Maybe Neighbor) [Commitment] -- -- If no leaf exists at the key, this proves its exclusion. prove :: Key -> Tree -> Proof -prove k (Tree t) = case I.prove_split k t of +prove k (Tree t) = case I.complete (I.prove_split k t) of (nb, ps) -> Proof nb ps -- | Verify that a value and sum sit at a key, under a root. diff --git a/test/Main.hs b/test/Main.hs @@ -13,6 +13,7 @@ import Data.MSSMT import qualified Data.MSSMT.Aggregate as Agg import qualified Data.MSSMT.Hash as H import qualified Data.MSSMT.Internal as I +import Data.Void (Void) import Data.Word (Word32, Word64) import Prelude hiding (lookup) import Test.Tasty @@ -30,8 +31,10 @@ main = do , properties "split" split_ops , properties "aggregate" aggregate_ops , split_proofs - , partial "split" I.Split I.prove_split I.expand - , partial "aggregate" I.Aggregate I.prove_aggregate I.expand_deleting + , partial "split" I.Split I.prove_split + (\k t -> I.complete (I.prove_split k t)) + , partial "aggregate" I.Aggregate I.prove_aggregate + (\k t -> I.complete (I.prove_aggregate k t)) , structure , testGroup "taproot-assets vectors" (zipWith V.execute files vs) ] @@ -265,9 +268,9 @@ 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 :: I.Tree -> Bool +compact :: I.Tree Void -> Bool compact = isJust . go 0 [] where - go :: Int -> [Bool] -> I.Tree -> Maybe Int + go :: Int -> [Bool] -> I.Tree Void -> Maybe Int go _ _ I.Empty = Just 0 go d path (I.Leaf _ _ k _) | reverse path == fmap (kbit k) [0 .. d - 1] = Just 1 @@ -276,46 +279,51 @@ compact = isJust . go 0 [] where a <- go (d + 1) (False : path) l b <- go (d + 1) (True : path) r if a + b >= 2 then Just (a + b) else Nothing - go _ _ (I.Stub {}) = Nothing -- whether a key's path ends at another key's leaf -at_leaf :: Key -> I.Tree -> Bool +at_leaf :: Key -> I.Tree Void -> Bool at_leaf k = go 0 where + go :: Int -> I.Tree Void -> Bool 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) - I.Stub {} -> False -- the internal tree underlying a split tree -build_raw :: [E] -> Maybe I.Tree +build_raw :: [E] -> Maybe (I.Tree Void) build_raw = build_with I.Split -build_with :: I.Scheme -> [E] -> Maybe I.Tree -build_with sc = foldM (\t (E k v s) -> I.insert_with sc k v s t) I.empty +build_with :: I.Scheme -> [E] -> Maybe (I.Tree Void) +build_with sc = + foldM (\t (E k v s) -> I.complete (I.insert_with sc k v s t)) I.empty -- a tree held entirely elsewhere: its root as a stub, and a store of its -- nodes by commitment, each with its subtrees as stubs -held :: I.Tree -> (I.Tree, M.Map (Hash, Word64) I.Tree) +held + :: I.Tree Void + -> (I.Tree I.Kind, M.Map (Hash, Word64) (I.Tree I.Kind)) held t0 = (stub t0, go t0 M.empty) where + stub :: I.Tree Void -> I.Tree I.Kind stub t = case t of I.Empty -> I.Empty I.Leaf c _ _ _ -> I.Stub I.Single c I.Node _ c _ -> I.Stub I.Branch c - I.Stub {} -> t + go + :: I.Tree Void -> M.Map (Hash, Word64) (I.Tree I.Kind) + -> M.Map (Hash, Word64) (I.Tree I.Kind) go t m = case t of I.Empty -> m - I.Leaf c _ _ _ -> M.insert (ckey c) t m + I.Leaf c lh k v -> M.insert (ckey c) (I.Leaf c lh k v) m I.Node l c r -> go l (go r (M.insert (ckey c) (I.Node (stub l) c (stub r)) m)) - I.Stub {} -> m ckey :: Commitment -> (Hash, Word64) ckey (Commitment h s) = (h, s) -- load a stub's contents from a store from_store - :: M.Map (Hash, Word64) I.Tree -> I.Kind -> Commitment -> Maybe I.Tree + :: M.Map (Hash, Word64) (I.Tree I.Kind) -> I.Kind -> Commitment + -> Maybe (I.Tree I.Kind) from_store m _ c = M.lookup (ckey c) m with_tree :: Ops t p -> [E] -> (t -> Q.Property) -> Q.Property @@ -440,43 +448,55 @@ split_proofs = testGroup "split proofs" [ ] -- operations on a tree held entirely elsewhere, loaded along the paths --- they touch, agree with those on the tree itself +-- they touch, agree with those on the tree itself; and report what they +-- need, where they find it held elsewhere partial :: (Eq p, Show p) => String -> I.Scheme - -> (Key -> I.Tree -> p) - -> ( (I.Kind -> Commitment -> Maybe I.Tree) - -> Key -> I.Tree -> Maybe I.Tree) + -> (Key -> I.Tree I.Kind -> Either (I.Missing I.Kind) p) + -> (Key -> I.Tree Void -> p) -> TestTree -partial name sc pf deleting = testGroup ("partial trees (" <> name <> ")") [ +partial name sc pf pf' = testGroup ("partial trees (" <> name <> ")") [ Q.testProperty "lookup" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k -> with es $ \t (h, m) -> fmap (I.lookup k) (I.expand (from_store m) k h) - Q.=== Just (I.lookup k t) + Q.=== Just (Right (I.complete (I.lookup k t))) , Q.testProperty "prove" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k -> with es $ \t (h, m) -> - fmap (pf k) (I.expand (from_store m) k h) Q.=== Just (pf k t) + fmap (pf k) (I.expand (from_store m) k h) Q.=== Just (Right (pf' k t)) , Q.testProperty "insert" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k -> with es $ \t (h, m) -> - let ins = I.insert_with sc k "v" 1 - in fmap root_of (I.expand (from_store m) k h >>= ins) - Q.=== fmap root_of (ins t) + let ins u = I.insert_with sc k "v" 1 u + in fmap (fmap (fmap root_of) . ins) (I.expand (from_store m) k h) + Q.=== Just (Right (fmap root_of (I.complete (ins t)))) , Q.testProperty "delete" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k -> with es $ \t (h, m) -> - let del = I.delete_with sc k - in fmap (root_of . del) (deleting (from_store m) k h) - Q.=== Just (root_of (del t)) + let del u = I.delete_with sc k u + in fmap (fmap root_of . del) (I.expand (from_store m) k h) + Q.=== Just (Right (root_of (I.complete (del t)))) , Q.testProperty "insert_many" $ \x@(Es _ es) -> Q.forAll (gen_batch small x) $ \b -> with es $ \t (h, m) -> - let ins = I.insert_many_with sc b - loaded = foldM (\u (k, _, _) -> deleting (from_store m) k u) h b - in fmap root_of (loaded >>= ins) Q.=== fmap root_of (ins t) + let ins u = I.insert_many_with sc b u + loaded = foldM (\u (k, _, _) -> I.expand (from_store m) k u) h b + in fmap (fmap (fmap root_of) . ins) loaded + Q.=== Just (Right (fmap root_of (I.complete (ins t)))) + + , Q.testProperty "unloaded paths report what they need" $ + \x@(Es _ es) -> Q.forAll (pick x) $ \k -> + with es $ \_ (h, _) -> case h of + I.Stub p c -> + let needed = Left (I.Missing p c) + in I.lookup k h Q.=== needed + Q..&&. fmap (const ()) (pf k h) Q.=== needed + Q..&&. fmap (const ()) (I.insert_with sc k "v" 1 h) Q.=== needed + Q..&&. fmap (const ()) (I.delete_with sc k h) Q.=== needed + _ -> Q.property True ] where root_of = I.root_with sc @@ -492,5 +512,6 @@ structure = testGroup "structure" [ case build_raw es of Nothing -> Q.counterexample "overflow" False Just t -> - compact t Q..&&. compact (foldr (I.delete_with I.Split) t ks) + let del k u = I.complete (I.delete_with I.Split k u) + in compact t Q..&&. compact (foldr del t ks) ]