mssmt-lmdb (empty) → 0.1.0
raw patch · 9 files changed
+1102/−0 lines, 9 filesdep +arraydep +basedep +bytestring
Dependencies added: array, base, bytestring, containers, criterion, deepseq, directory, mssmt, mssmt-lmdb, ppad-lmdb, ppad-sha256, tasty, tasty-quickcheck
Files
- CHANGELOG +8/−0
- LICENSE +20/−0
- bench/Main.hs +124/−0
- lib/Data/MSSMT/LMDB.hs +26/−0
- lib/Data/MSSMT/LMDB/Aggregate.hs +112/−0
- lib/Data/MSSMT/LMDB/Internal.hs +406/−0
- lib/Data/MSSMT/LMDB/Split.hs +115/−0
- mssmt-lmdb.cabal +80/−0
- test/Main.hs +211/−0
+ CHANGELOG view
@@ -0,0 +1,8 @@+# Changelog++- 0.1.0 (2026-11-05)+ * Initial release, supporting Merkle-Sum Sparse Merkle Trees held in+ LMDB, via mssmt and ppad-lmdb: stores of any number of named split or+ aggregate trees, each operation on which runs in its own+ transaction, loading only the paths it touches and writing only the+ nodes it creates.
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 Jared Tobin++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ bench/Main.hs view
@@ -0,0 +1,124 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+{-# LANGUAGE OverloadedStrings #-}++-- Benchmarks after those of the taproot-assets SQL-backed tree store+-- (tapdb/mssmt_bench_test.go): inserting a batch of leaves into a fresh+-- store in one transaction, one at a time or batched, and proving keys+-- in populated stores, each in its own read transaction.++module Main where++import Control.DeepSeq+import Control.Exception (evaluate)+import qualified Crypto.Hash.SHA256 as SHA256+import qualified Data.Array as A+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as B8+import Data.IORef+import Data.MSSMT.Internal (Commitment, Hash, Key, Neighbor, Scheme(..))+import qualified Data.MSSMT.Internal as M+import qualified Data.MSSMT.LMDB.Internal as I+import Data.Word (Word64)+import qualified Database.LMDB as L+import Criterion.Main+import System.Directory (getTemporaryDirectory, removeFile)+import System.IO (hClose, openTempFile)++instance NFData I.Store where+ rnf = rwhnf++instance NFData Hash where+ rnf = rwhnf++instance NFData Key where+ rnf = rwhnf++instance NFData Commitment where+ rnf = rwhnf++instance NFData Neighbor where+ rnf = rwhnf++-- n leaves, after tapdb's benchRandLeaves: pseudorandom keys, values of+-- 1 to 255 bytes, and 32-bit sums+leaves :: Int -> [(Key, BS.ByteString, Word64)]+leaves n = fmap leaf [1 .. n] where+ leaf i =+ let h = SHA256.hash (B8.pack (show i))+ v = BS.take (1 + fromIntegral (BS.index h 0) `mod` 255) . BS.concat $+ [SHA256.hash (h <> B8.pack (show j)) | j <- [0 .. 7 :: Int]]+ s = fromIntegral (BS.foldl' (\a w -> a * 256 + fromIntegral w)+ (0 :: Word64) (BS.take 4 h))+ in case M.key h of+ Just k -> (k, v, s)+ Nothing -> error "bang"++-- a fresh store under a scheme, in a temporary file+fresh :: Bool -> Scheme -> IO (FilePath, I.Store)+fresh synced sc = do+ tmp <- getTemporaryDirectory+ (path, h) <- openTempFile tmp "mssmt-lmdb-bench.mdb"+ hClose h+ st <- I.open sc path L.defaultEnvFlags {+ L.envMapSize = 1024 * 1024 * 1024+ , L.envNoSubdir = True+ , L.envNoSync = not synced+ }+ pure (path, st)++discard :: (FilePath, I.Store) -> IO ()+discard (path, st) = do+ I.close st+ removeFile path+ removeFile (path <> "-lock")++main :: IO ()+main = defaultMain [+ bgroup "insert, fresh store" [+ insert_bench synced sc n+ | n <- [100, 1000], synced <- [True, False], sc <- [Split, Aggregate]+ ]+ , bgroup "prove" [+ prove_bench sc n+ | n <- [1000, 10000, 100000], sc <- [Split, Aggregate]+ ]+ ]++scheme_name :: Scheme -> String+scheme_name Split = "split"+scheme_name Aggregate = "aggregate"++insert_bench :: Bool -> Scheme -> Int -> Benchmark+insert_bench synced sc n = env (pure (leaves n)) $ \ls ->+ bgroup (scheme_name sc <> ", batch=" <> show n <> sync_name) [+ bench "one at a time" $ perRunEnvWithCleanup (fresh synced sc) discard $+ \(_, st) -> L.withWriteTxn (I.store_env st) $ \txn ->+ mapM_ (\(k, v, s) -> I.insert_in st txn "tree" k v s) ls+ , bench "batched" $ perRunEnvWithCleanup (fresh synced sc) discard $+ \(_, st) -> () <$ I.insert_many st "tree" ls+ ]+ where+ sync_name = if synced then "" else ", unsynced"++prove_bench :: Scheme -> Int -> Benchmark+prove_bench sc n = envWithCleanup populated (discard . fst) $ \ ~(_, ks) ->+ bench (scheme_name sc <> ", leaves=" <> show n) $+ whnfIO (next ks)+ where+ populated = do+ fs@(_, st) <- fresh False sc+ let ls = leaves n+ _ <- I.insert_many st "tree" ls+ ref <- newIORef (0 :: Int)+ let arr = A.listArray (0, n - 1) [k | (k, _, _) <- ls]+ _ <- evaluate (force arr)+ pure (fs, (st, arr, ref))++ next (st, arr, ref) = do+ i <- atomicModifyIORef' ref (\j -> (j + 1, j))+ let k = arr A.! (i `mod` n)+ case sc of+ Split -> I.prove_split st "tree" k >>= evaluate . force+ >>= \(_, ps) -> pure (length ps)+ Aggregate -> I.prove_aggregate st "tree" k >>= evaluate . force+ >>= pure . length
+ lib/Data/MSSMT/LMDB.hs view
@@ -0,0 +1,26 @@+{-# OPTIONS_HADDOCK prune #-}++-- |+-- Module: Data.MSSMT.LMDB+-- Copyright: (c) 2026 Jared Tobin+-- License: MIT+-- Maintainer: Jared Tobin <jared@jtobin.io>+--+-- Merkle-sum sparse merkle trees (MS-SMTs) held in LMDB, via+-- "Data.MSSMT" and "Database.LMDB". There's a store for each kind of+-- tree:+--+-- * "Data.MSSMT.LMDB.Split": for trees whose branches commit to the+-- hash and sum of each of their children. This is the default,+-- re-exported here.+--+-- * "Data.MSSMT.LMDB.Aggregate": for trees whose branches commit to+-- their children's hashes and the sum of their sums, as in Taproot+-- Assets.++module Data.MSSMT.LMDB (+ module Data.MSSMT.LMDB.Split+ ) where++import Data.MSSMT.LMDB.Split+import Prelude hiding (lookup)
+ lib/Data/MSSMT/LMDB/Aggregate.hs view
@@ -0,0 +1,112 @@+{-# OPTIONS_HADDOCK prune #-}++-- |+-- Module: Data.MSSMT.LMDB.Aggregate+-- Copyright: (c) 2026 Jared Tobin+-- License: MIT+-- Maintainer: Jared Tobin <jared@jtobin.io>+--+-- A merkle-sum sparse merkle tree (MS-SMT) whose branches commit to+-- their children's hashes and the sum of their sums, as in Taproot+-- Assets, held in LMDB; see "Data.MSSMT.Aggregate".+--+-- A store holds any number of named trees in an LMDB environment. Each+-- operation on a tree runs in its own transaction, loading only the+-- paths it touches.++module Data.MSSMT.LMDB.Aggregate (+ -- * Stores+ Store+ , open+ , close+ , L.EnvFlags(..)+ , L.defaultEnvFlags+ , StoreException(..)++ -- * Trees+ , Tree+ , tree+ , root+ , insert+ , insert_many+ , delete+ , lookup+ , prove++ -- * Keys, commitments, and proofs+ , M.Key+ , M.key+ , M.Hash+ , M.parse_hash+ , M.serialize_hash+ , M.Commitment(..)+ , M.Proof(..)+ , M.verify+ ) where++import qualified Data.ByteString as BS+import Data.MSSMT.Internal (Scheme(..))+import Data.MSSMT.LMDB.Internal (StoreException(..))+import qualified Data.MSSMT.LMDB.Internal as I+import qualified Data.MSSMT.Aggregate as M+import Data.Word (Word64)+import qualified Database.LMDB as L+import Prelude hiding (lookup)++-- | A store of aggregate trees, held in an LMDB environment.+newtype Store = Store I.Store++-- | A named tree in a store.+data Tree = Tree !I.Store !BS.ByteString++-- | Open a store at a path.+--+-- LMDB permits one open environment per path per process.+open :: FilePath -> L.EnvFlags -> IO Store+open path flags = Store <$> I.open Aggregate path flags++-- | Close a store.+close :: Store -> IO ()+close (Store st) = I.close st++-- | The tree with a name in a store; empty, if there's none yet.+tree :: Store -> BS.ByteString -> Tree+tree (Store st) = Tree st++-- | The tree's root commitment.+root :: Tree -> IO M.Commitment+root (Tree st n) = I.root st n++-- | Insert a value and sum at a key, replacing any existing leaf, and+-- return the new root.+--+-- Returns 'Nothing', changing nothing, if the tree's sum would+-- overflow.+insert+ :: Tree -> M.Key -> BS.ByteString -> Word64 -> IO (Maybe M.Commitment)+insert (Tree st n) = I.insert st n++-- | Insert many values and sums, in one transaction, and return the new+-- root.+--+-- 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', changing nothing, if the resulting tree's sum+-- would overflow.+insert_many+ :: Tree -> [(M.Key, BS.ByteString, Word64)] -> IO (Maybe M.Commitment)+insert_many (Tree st n) = I.insert_many st n++-- | Delete the leaf at a key, and return the new root.+delete :: Tree -> M.Key -> IO M.Commitment+delete (Tree st n) = I.delete st n++-- | Look up the value and sum at a key.+lookup :: Tree -> M.Key -> IO (Maybe (BS.ByteString, Word64))+lookup (Tree st n) = I.lookup st n++-- | Produce a proof for the leaf at a key.+--+-- If no leaf exists at the key, this proves its exclusion.+prove :: Tree -> M.Key -> IO M.Proof+prove (Tree st n) k = M.Proof <$> I.prove_aggregate st n k
+ lib/Data/MSSMT/LMDB/Internal.hs view
@@ -0,0 +1,406 @@+{-# OPTIONS_HADDOCK hide #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++-- |+-- Module: Data.MSSMT.LMDB.Internal+-- Copyright: (c) 2026 Jared Tobin+-- License: MIT+-- Maintainer: Jared Tobin <jared@jtobin.io>+--+-- LMDB-backed MS-SMT internals.+--+-- A store holds the nodes of any number of named trees, each keyed by+-- the hash of its commitment, and each tree's root by name. An+-- operation on a tree runs in one transaction: it loads the paths it+-- touches, applies the in-memory operation, and writes the nodes it+-- creates.++module Data.MSSMT.LMDB.Internal (+ -- * Stores+ Store(..)+ , StoreException(..)+ , open+ , close++ -- * Trees+ , root+ , insert+ , insert_many+ , delete+ , lookup+ , prove_split+ , prove_aggregate++ -- * Within transactions+ , root_in+ , insert_in+ , insert_many_in+ , delete_in+ , lookup_in+ , prove_split_in+ , prove_aggregate_in++ -- * Records+ , leaf_record+ , branch_record+ , decode+ ) where++import Control.Exception (Exception, throwIO)+import Control.Monad (foldM, void)+import Data.Bits (unsafeShiftL, unsafeShiftR, (.|.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Internal as BI+import qualified Data.ByteString.Unsafe as BU+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.MSSMT.Hash (unsafe_hash)+import Data.MSSMT.Internal (+ Commitment(..), Hash(..), Key(..), Kind(..), Neighbor, Scheme(..)+ )+import qualified Data.MSSMT.Internal as I+import qualified Data.Set as S+import Data.Word (Word8, Word64)+import qualified Database.LMDB as L+import Foreign.Marshal.Utils (copyBytes, fillBytes)+import Foreign.Ptr (Ptr, castPtr, plusPtr)+import Foreign.Storable (pokeByteOff)+import Prelude hiding (lookup)++-- stores ---------------------------------------------------------------------++-- | A store of trees, held in an LMDB environment.+data Store = Store {+ store_scheme :: !Scheme+ , store_env :: !L.Env+ , store_nodes :: !L.Dbi+ , store_roots :: !L.Dbi+ }++-- | A store whose records are missing or malformed.+data StoreException =+ -- | A node a tree refers to is absent.+ MissingNode !Hash+ -- | A node's record is malformed.+ | BadNode !Hash+ -- | A tree's root record is malformed.+ | BadRoot !BS.ByteString+ -- | An operation met a node it hadn't loaded. Operations load their+ -- paths before running, so this indicates a bug.+ | Unloaded !Hash+ deriving (Eq, Show)++instance Exception StoreException++-- | Open a store of trees under a scheme, at a path.+--+-- The environment holds two databases per scheme, so trees under+-- each can share it.+open :: Scheme -> FilePath -> L.EnvFlags -> IO Store+open sc path flags = do+ env <- L.open path flags { L.envMaxDbs = max 4 (L.envMaxDbs flags) }+ nodes <- L.openDbi env (Just (prefix <> "/nodes")) True+ roots <- L.openDbi env (Just (prefix <> "/roots")) True+ pure (Store sc env nodes roots)+ where+ prefix = case sc of+ Split -> "split"+ Aggregate -> "aggregate"++-- | Close a store.+close :: Store -> IO ()+close = L.close . store_env++-- records --------------------------------------------------------------------++-- A leaf's record is a zero byte, then its hash, sum, key, and value. A+-- branch's is a one byte, then each child's kind (zero for an empty+-- subtree, one for a single leaf, and two for a branch), hash, and sum;+-- an empty child's hash and sum are zero. A root's record is that of a+-- branch's child.++-- | A leaf's record.+leaf_record :: Commitment -> Hash -> Key -> BS.ByteString -> BS.ByteString+leaf_record (Commitment _ s) lh (Key k) v =+ BI.unsafeCreate (73 + BS.length v) $ \p -> do+ pokeByteOff p 0 (0 :: Word8)+ poke_hash p 1 lh+ poke_be64 p 33 s+ poke_hash p 41 k+ BU.unsafeUseAsCString v $ \q ->+ copyBytes (p `plusPtr` 73) (castPtr q) (BS.length v)++-- | A branch's record, given its children.+branch_record :: I.Tree Kind -> I.Tree Kind -> BS.ByteString+branch_record l r = BI.unsafeCreate 83 $ \p -> do+ pokeByteOff p 0 (1 :: Word8)+ poke_child p 1 l+ poke_child p 42 r++root_record :: I.Tree Kind -> BS.ByteString+root_record t = BI.unsafeCreate 41 $ \p -> poke_child p 0 t++poke_child :: Ptr Word8 -> Int -> I.Tree Kind -> IO ()+poke_child p i t = case t of+ I.Empty -> do+ pokeByteOff p i (0 :: Word8)+ fillBytes (p `plusPtr` (i + 1)) 0 40+ I.Leaf c _ _ _ -> with 1 c+ I.Node _ c _ -> with 2 c+ I.Stub Single c -> with 1 c+ I.Stub Branch c -> with 2 c+ where+ with :: Word8 -> Commitment -> IO ()+ with kd (Commitment h s) = do+ pokeByteOff p i kd+ poke_hash p (i + 1) h+ poke_be64 p (i + 33) s++poke_hash :: Ptr Word8 -> Int -> Hash -> IO ()+poke_hash p i (Hash a b c d) = do+ poke_be64 p i a+ poke_be64 p (i + 8) b+ poke_be64 p (i + 16) c+ poke_be64 p (i + 24) d++poke_be64 :: Ptr Word8 -> Int -> Word64 -> IO ()+poke_be64 p i w = do+ pokeByteOff p (i + 0) (fromIntegral (w `unsafeShiftR` 56) :: Word8)+ pokeByteOff p (i + 1) (fromIntegral (w `unsafeShiftR` 48) :: Word8)+ pokeByteOff p (i + 2) (fromIntegral (w `unsafeShiftR` 40) :: Word8)+ pokeByteOff p (i + 3) (fromIntegral (w `unsafeShiftR` 32) :: Word8)+ pokeByteOff p (i + 4) (fromIntegral (w `unsafeShiftR` 24) :: Word8)+ pokeByteOff p (i + 5) (fromIntegral (w `unsafeShiftR` 16) :: Word8)+ pokeByteOff p (i + 6) (fromIntegral (w `unsafeShiftR` 8) :: Word8)+ pokeByteOff p (i + 7) (fromIntegral w :: Word8)++-- big-endian word at an offset; callers check the length+be64_at :: BS.ByteString -> Int -> Word64+be64_at bs i = go 0 0 where+ go !acc j+ | j == 8 = acc+ | otherwise =+ let w = fromIntegral (BU.unsafeIndex bs (i + j)) :: Word64+ in go (acc `unsafeShiftL` 8 .|. w) (j + 1)++-- a commitment at an offset; callers check the length+commitment_at :: BS.ByteString -> Int -> Commitment+commitment_at bs i =+ Commitment (unsafe_hash (BU.unsafeDrop i bs)) (be64_at bs (i + 32))++-- a child at an offset, as a stub; callers check the length+child_at :: BS.ByteString -> Int -> Maybe (I.Tree Kind)+child_at bs i = case BU.unsafeIndex bs i of+ 0 -> Just I.Empty+ 1 -> Just (I.Stub Single (commitment_at bs (i + 1)))+ 2 -> Just (I.Stub Branch (commitment_at bs (i + 1)))+ _ -> Nothing++-- | A node from its record, given its commitment, with its subtrees as+-- stubs.+decode :: Commitment -> BS.ByteString -> Maybe (I.Tree Kind)+decode c bs+ | n == 83 && tag == 1 = do+ l <- child_at bs 1+ r <- child_at bs 42+ pure (I.Node l c r)+ | n >= 73 && tag == 0 = do+ k <- I.key (BS.take 32 (BU.unsafeDrop 41 bs))+ let Commitment _ s = c+ if be64_at bs 33 == s+ then pure (I.Leaf c (unsafe_hash (BU.unsafeDrop 1 bs)) k+ (BU.unsafeDrop 73 bs))+ else Nothing+ | otherwise = Nothing+ where+ n = BS.length bs+ tag = if n == 0 then 255 else BU.unsafeIndex bs 0++decode_root :: BS.ByteString -> Maybe (I.Tree Kind)+decode_root bs+ | BS.length bs == 41 = case child_at bs 0 of+ Just I.Empty -> Nothing+ t -> t+ | otherwise = Nothing++-- loading and persisting -----------------------------------------------------++-- load a stub's node from a store, noting its hash+loader+ :: Store -> L.Txn t -> IORef (S.Set Hash) -> Kind -> Commitment+ -> IO (I.Tree Kind)+loader st txn seen _ c@(Commitment h _) = do+ mr <- L.get txn (store_nodes st) (I.serialize_hash h)+ case mr of+ Nothing -> throwIO (MissingNode h)+ Just r -> case decode c r of+ Nothing -> throwIO (BadNode h)+ Just t -> do+ modifyIORef' seen (S.insert h)+ pure t++-- a tree's root, as a stub+stored_root :: Store -> L.Txn t -> BS.ByteString -> IO (I.Tree Kind)+stored_root st txn name = do+ mr <- L.get txn (store_roots st) name+ case mr of+ Nothing -> pure I.Empty+ Just r -> maybe (throwIO (BadRoot name)) pure (decode_root r)++-- write the nodes of a tree that weren't loaded from the store+persist :: Store -> L.Txn L.RW -> S.Set Hash -> I.Tree Kind -> IO ()+persist st txn seen = go where+ go t = case t of+ I.Empty -> pure ()+ I.Stub {} -> pure ()+ I.Leaf c@(Commitment h _) lh k v+ | S.member h seen -> pure ()+ | otherwise ->+ L.put txn (store_nodes st) (I.serialize_hash h)+ (leaf_record c lh k v)+ I.Node l (Commitment h _) r+ | S.member h seen -> pure ()+ | otherwise -> do+ L.put txn (store_nodes st) (I.serialize_hash h) (branch_record l r)+ go l+ go r++-- the tree at a name, with the paths to some keys loaded+loaded+ :: Store -> L.Txn t -> IORef (S.Set Hash) -> BS.ByteString -> [Key]+ -> IO (I.Tree Kind)+loaded st txn seen name ks = do+ r <- stored_root st txn name+ foldM (\t k -> I.expand (loader st txn seen) k t) r ks++-- the result of an operation on a tree with its paths loaded+settled :: Either (I.Missing Kind) a -> IO a+settled = either (\(I.Missing _ (Commitment h _)) -> throwIO (Unloaded h)) pure++-- apply an update to the tree at a name, loading the paths to some keys+-- first, and writing what it creates+update_in+ :: Store -> L.Txn L.RW -> BS.ByteString -> [Key]+ -> (I.Tree Kind -> Either (I.Missing Kind) (Maybe (I.Tree Kind)))+ -> IO (Maybe Commitment)+update_in st txn name ks f = do+ seen <- newIORef S.empty+ t <- loaded st txn seen name ks+ r <- settled (f t)+ case r of+ Nothing -> pure Nothing+ Just t' -> do+ s <- readIORef seen+ persist st txn s t'+ case t' of+ I.Empty -> void (L.del txn (store_roots st) name)+ _ -> L.put txn (store_roots st) name (root_record t')+ pure (Just (I.root_with (store_scheme st) t'))++-- within transactions --------------------------------------------------------++-- | 'root', within a transaction.+root_in :: Store -> L.Txn t -> BS.ByteString -> IO Commitment+root_in st txn name = I.root_with (store_scheme st) <$> stored_root st txn name++-- | 'insert', within a transaction.+insert_in+ :: Store -> L.Txn L.RW -> BS.ByteString -> Key -> BS.ByteString -> Word64+ -> IO (Maybe Commitment)+insert_in st txn name k v s =+ update_in st txn name [k] (I.insert_with (store_scheme st) k v s)++-- | 'insert_many', within a transaction.+insert_many_in+ :: Store -> L.Txn L.RW -> BS.ByteString -> [(Key, BS.ByteString, Word64)]+ -> IO (Maybe Commitment)+insert_many_in st txn name kvs =+ update_in st txn name [k | (k, _, _) <- kvs]+ (I.insert_many_with (store_scheme st) kvs)++-- | 'delete', within a transaction.+delete_in :: Store -> L.Txn L.RW -> BS.ByteString -> Key -> IO Commitment+delete_in st txn name k = do+ mr <- update_in st txn name [k]+ (fmap Just . I.delete_with (store_scheme st) k)+ maybe (root_in st txn name) pure mr++-- | 'lookup', within a transaction.+lookup_in+ :: Store -> L.Txn t -> BS.ByteString -> Key+ -> IO (Maybe (BS.ByteString, Word64))+lookup_in st txn name k = do+ seen <- newIORef S.empty+ t <- loaded st txn seen name [k]+ settled (I.lookup k t)++-- | 'prove_split', within a transaction.+prove_split_in+ :: Store -> L.Txn t -> BS.ByteString -> Key+ -> IO (Maybe Neighbor, [Commitment])+prove_split_in st txn name k = do+ seen <- newIORef S.empty+ t <- loaded st txn seen name [k]+ settled (I.prove_split k t)++-- | 'prove_aggregate', within a transaction.+prove_aggregate_in+ :: Store -> L.Txn t -> BS.ByteString -> Key -> IO [Commitment]+prove_aggregate_in st txn name k = do+ seen <- newIORef S.empty+ t <- loaded st txn seen name [k]+ settled (I.prove_aggregate k t)++-- trees ----------------------------------------------------------------------++-- | The root commitment of the tree at a name.+root :: Store -> BS.ByteString -> IO Commitment+root st name = L.withReadTxn (store_env st) $ \txn -> root_in st txn name++-- | Insert a value and sum at a key in the tree at a name, replacing any+-- existing leaf, and return the new root.+--+-- Returns 'Nothing', changing nothing, if the tree's sum would+-- overflow.+insert+ :: Store -> BS.ByteString -> Key -> BS.ByteString -> Word64+ -> IO (Maybe Commitment)+insert st name k v s =+ L.withWriteTxn (store_env st) $ \txn -> insert_in st txn name k v s++-- | Insert many values and sums in the tree at a name, in one+-- transaction, and return the new root.+--+-- 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', changing nothing, if the resulting tree's sum+-- would overflow.+insert_many+ :: Store -> BS.ByteString -> [(Key, BS.ByteString, Word64)]+ -> IO (Maybe Commitment)+insert_many st name kvs =+ L.withWriteTxn (store_env st) $ \txn -> insert_many_in st txn name kvs++-- | Delete the leaf at a key in the tree at a name, and return the new+-- root.+delete :: Store -> BS.ByteString -> Key -> IO Commitment+delete st name k =+ L.withWriteTxn (store_env st) $ \txn -> delete_in st txn name k++-- | Look up the value and sum at a key in the tree at a name.+lookup+ :: Store -> BS.ByteString -> Key -> IO (Maybe (BS.ByteString, Word64))+lookup st name k =+ L.withReadTxn (store_env st) $ \txn -> lookup_in st txn name k++-- | The siblings along a key's path in the split tree at a name, and the+-- leaf the path ends at, where that's another key's.+prove_split+ :: Store -> BS.ByteString -> Key -> IO (Maybe Neighbor, [Commitment])+prove_split st name k =+ L.withReadTxn (store_env st) $ \txn -> prove_split_in st txn name k++-- | The 256 siblings along a key's path in the aggregate tree at a name.+prove_aggregate :: Store -> BS.ByteString -> Key -> IO [Commitment]+prove_aggregate st name k =+ L.withReadTxn (store_env st) $ \txn -> prove_aggregate_in st txn name k
+ lib/Data/MSSMT/LMDB/Split.hs view
@@ -0,0 +1,115 @@+{-# OPTIONS_HADDOCK prune #-}++-- |+-- Module: Data.MSSMT.LMDB.Split+-- Copyright: (c) 2026 Jared Tobin+-- License: MIT+-- Maintainer: Jared Tobin <jared@jtobin.io>+--+-- A merkle-sum sparse merkle tree (MS-SMT) whose branches commit to+-- the hash and sum of each of their children, held in LMDB; see+-- "Data.MSSMT.Split".+--+-- A store holds any number of named trees in an LMDB environment. Each+-- operation on a tree runs in its own transaction, loading only the+-- paths it touches.++module Data.MSSMT.LMDB.Split (+ -- * Stores+ Store+ , open+ , close+ , L.EnvFlags(..)+ , L.defaultEnvFlags+ , StoreException(..)++ -- * Trees+ , Tree+ , tree+ , root+ , insert+ , insert_many+ , delete+ , lookup+ , prove++ -- * Keys, commitments, and proofs+ , M.Key+ , M.key+ , M.Hash+ , M.parse_hash+ , M.serialize_hash+ , M.Commitment(..)+ , M.Proof(..)+ , M.Neighbor(..)+ , M.verify+ ) where++import qualified Data.ByteString as BS+import Data.MSSMT.Internal (Scheme(..))+import Data.MSSMT.LMDB.Internal (StoreException(..))+import qualified Data.MSSMT.LMDB.Internal as I+import qualified Data.MSSMT.Split as M+import Data.Word (Word64)+import qualified Database.LMDB as L+import Prelude hiding (lookup)++-- | A store of split trees, held in an LMDB environment.+newtype Store = Store I.Store++-- | A named tree in a store.+data Tree = Tree !I.Store !BS.ByteString++-- | Open a store at a path.+--+-- LMDB permits one open environment per path per process.+open :: FilePath -> L.EnvFlags -> IO Store+open path flags = Store <$> I.open Split path flags++-- | Close a store.+close :: Store -> IO ()+close (Store st) = I.close st++-- | The tree with a name in a store; empty, if there's none yet.+tree :: Store -> BS.ByteString -> Tree+tree (Store st) = Tree st++-- | The tree's root commitment.+root :: Tree -> IO M.Commitment+root (Tree st n) = I.root st n++-- | Insert a value and sum at a key, replacing any existing leaf, and+-- return the new root.+--+-- Returns 'Nothing', changing nothing, if the tree's sum would+-- overflow.+insert+ :: Tree -> M.Key -> BS.ByteString -> Word64 -> IO (Maybe M.Commitment)+insert (Tree st n) = I.insert st n++-- | Insert many values and sums, in one transaction, and return the new+-- root.+--+-- 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', changing nothing, if the resulting tree's sum+-- would overflow.+insert_many+ :: Tree -> [(M.Key, BS.ByteString, Word64)] -> IO (Maybe M.Commitment)+insert_many (Tree st n) = I.insert_many st n++-- | Delete the leaf at a key, and return the new root.+delete :: Tree -> M.Key -> IO M.Commitment+delete (Tree st n) = I.delete st n++-- | Look up the value and sum at a key.+lookup :: Tree -> M.Key -> IO (Maybe (BS.ByteString, Word64))+lookup (Tree st n) = I.lookup st n++-- | Produce a proof for the leaf at a key.+--+-- If no leaf exists at the key, this proves its exclusion.+prove :: Tree -> M.Key -> IO M.Proof+prove (Tree st n) k = do+ (nb, ps) <- I.prove_split st n k+ pure (M.Proof nb ps)
+ mssmt-lmdb.cabal view
@@ -0,0 +1,80 @@+cabal-version: 3.0+name: mssmt-lmdb+version: 0.1.0+synopsis: An LMDB-backed Merkle-Sum Sparse Merkle Tree.+license: MIT+license-file: LICENSE+author: Jared Tobin+maintainer: jared@jtobin.io+category: Data Structures+build-type: Simple+tested-with: GHC == 9.10.3+extra-doc-files: CHANGELOG+description:+ A Merkle-Sum Sparse Merkle Tree (MS-SMT) held in an LMDB environment,+ via mssmt and ppad-lmdb.++flag llvm+ description: Use GHC's LLVM backend.+ default: False+ manual: True++library+ default-language: Haskell2010+ hs-source-dirs: lib+ ghc-options:+ -Wall+ if flag(llvm)+ ghc-options: -fllvm -O2+ exposed-modules:+ Data.MSSMT.LMDB+ , Data.MSSMT.LMDB.Aggregate+ , Data.MSSMT.LMDB.Internal+ , Data.MSSMT.LMDB.Split+ build-depends:+ base >= 4.11 && < 5+ , bytestring >= 0.10.2 && < 0.13+ , containers >= 0.6 && < 0.8+ , mssmt >= 0.1 && < 0.2+ , ppad-lmdb >= 0.2 && < 0.3++test-suite mssmt-lmdb-tests+ type: exitcode-stdio-1.0+ default-language: Haskell2010+ hs-source-dirs: test+ main-is: Main.hs++ ghc-options:+ -rtsopts -Wall -O2++ build-depends:+ base+ , bytestring+ , directory+ , mssmt+ , mssmt-lmdb+ , tasty+ , tasty-quickcheck++benchmark mssmt-lmdb-bench+ type: exitcode-stdio-1.0+ default-language: Haskell2010+ hs-source-dirs: bench+ main-is: Main.hs++ ghc-options:+ -rtsopts -O2 -Wall+ if flag(llvm)+ ghc-options: -fllvm++ build-depends:+ array+ , base+ , bytestring+ , criterion+ , deepseq+ , directory+ , mssmt+ , mssmt-lmdb+ , ppad-lmdb+ , ppad-sha256
+ test/Main.hs view
@@ -0,0 +1,211 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}++module Main where++import Control.Exception (bracket)+import Control.Monad (foldM, forM, forM_)+import qualified Data.ByteString as BS+import qualified Data.MSSMT.Aggregate as MA+import qualified Data.MSSMT.LMDB.Aggregate as LA+import qualified Data.MSSMT.LMDB.Split as LS+import qualified Data.MSSMT.Split as MS+import Data.Word (Word32, Word64)+import Prelude hiding (lookup)+import System.Directory (getTemporaryDirectory, removeFile)+import System.IO (hClose, openTempFile)+import Test.Tasty+import qualified Test.Tasty.QuickCheck as Q++main :: IO ()+main = defaultMain $ testGroup "mssmt-lmdb" [+ properties "split" split_ops+ , properties "aggregate" aggregate_ops+ ]++-- stores ---------------------------------------------------------------------++-- a store and an in-memory tree under one scheme+data Ops s t m p = Ops {+ o_open :: FilePath -> IO s+ , o_close :: s -> IO ()+ , o_tree :: s -> BS.ByteString -> t+ , o_root :: t -> IO MS.Commitment+ , o_insert :: t -> MS.Key -> BS.ByteString -> Word64+ -> IO (Maybe MS.Commitment)+ , o_insert_many :: t -> [(MS.Key, BS.ByteString, Word64)]+ -> IO (Maybe MS.Commitment)+ , o_delete :: t -> MS.Key -> IO MS.Commitment+ , o_lookup :: t -> MS.Key -> IO (Maybe (BS.ByteString, Word64))+ , o_prove :: t -> MS.Key -> IO p+ , m_empty :: m+ , m_insert :: MS.Key -> BS.ByteString -> Word64 -> m -> Maybe m+ , m_insert_many :: [(MS.Key, BS.ByteString, Word64)] -> m -> Maybe m+ , m_delete :: MS.Key -> m -> m+ , m_lookup :: MS.Key -> m -> Maybe (BS.ByteString, Word64)+ , m_root :: m -> MS.Commitment+ , m_prove :: MS.Key -> m -> p+ }++flags :: LS.EnvFlags+flags = LS.defaultEnvFlags {+ LS.envMapSize = 64 * 1024 * 1024+ , LS.envNoSubdir = True+ , LS.envNoSync = True+ }++split_ops :: Ops LS.Store LS.Tree MS.Tree MS.Proof+split_ops = Ops {+ o_open = \p -> LS.open p flags+ , o_close = LS.close+ , o_tree = LS.tree+ , o_root = LS.root+ , o_insert = LS.insert+ , o_insert_many = LS.insert_many+ , o_delete = LS.delete+ , o_lookup = LS.lookup+ , o_prove = LS.prove+ , m_empty = MS.empty+ , m_insert = MS.insert+ , m_insert_many = MS.insert_many+ , m_delete = MS.delete+ , m_lookup = MS.lookup+ , m_root = MS.root+ , m_prove = MS.prove+ }++aggregate_ops :: Ops LA.Store LA.Tree MA.Tree MA.Proof+aggregate_ops = Ops {+ o_open = \p -> LA.open p flags+ , o_close = LA.close+ , o_tree = LA.tree+ , o_root = LA.root+ , o_insert = LA.insert+ , o_insert_many = LA.insert_many+ , o_delete = LA.delete+ , o_lookup = LA.lookup+ , o_prove = LA.prove+ , m_empty = MA.empty+ , m_insert = MA.insert+ , m_insert_many = MA.insert_many+ , m_delete = MA.delete+ , m_lookup = MA.lookup+ , m_root = MA.root+ , m_prove = MA.prove+ }++-- a fresh temporary path for a store, removed afterwards+with_path :: (FilePath -> IO a) -> IO a+with_path = bracket fresh clean where+ fresh = do+ tmp <- getTemporaryDirectory+ bracket (openTempFile tmp "mssmt-lmdb.mdb") (hClose . snd) (pure . fst)+ clean path = do+ removeFile path+ removeFile (path <> "-lock")++-- a fresh store, closed and removed afterwards+with_store :: Ops s t m p -> (s -> IO a) -> IO a+with_store Ops {..} act = with_path $ \path ->+ bracket (o_open path) o_close act++-- operations -----------------------------------------------------------------++data Op =+ Insert !MS.Key !BS.ByteString !Word64+ | Delete !MS.Key+ | Many [(MS.Key, BS.ByteString, Word64)]+ deriving Show++-- operations at keys sharing a random prefix, so that their paths share+-- up to 256 levels, and keys recur+data Ops' = Ops' [MS.Key] [Op]+ deriving Show++gen_key :: BS.ByteString -> Q.Gen MS.Key+gen_key pre =+ fmap ((pre <>) . BS.pack) (Q.vector (32 - BS.length pre))+ `Q.suchThatMap` MS.key++instance Q.Arbitrary Ops' where+ arbitrary = do+ pre <- BS.pack <$> (Q.chooseInt (0, 32) >>= Q.vector)+ ks <- Q.listOf1 (gen_key pre)+ let leaf = (,,) <$> Q.elements ks+ <*> Q.oneof [pure mempty, fmap BS.pack (Q.listOf1 Q.arbitrary)]+ <*> Q.oneof [pure 0, fmap fromIntegral (Q.arbitrary :: Q.Gen Word32)]+ op = Q.frequency [+ (4, (\(k, v, s) -> Insert k v s) <$> leaf)+ , (2, Delete <$> Q.elements ks)+ , (1, Many <$> Q.listOf leaf)+ ]+ Ops' ks <$> Q.listOf op+ shrink (Ops' ks os) = Ops' ks <$> Q.shrinkList (const []) os++-- apply an operation to a stored tree+run :: Ops s t m p -> t -> Op -> IO ()+run Ops {..} t op = case op of+ Insert k v s -> () <$ o_insert t k v s+ Delete k -> () <$ o_delete t k+ Many kvs -> () <$ o_insert_many t kvs++-- apply an operation to a stored tree and an in-memory one, returning+-- the new in-memory tree and whether their roots agree+step :: Ops s t m p -> t -> m -> Op -> IO (m, Bool)+step Ops {..} t m op = case op of+ Insert k v s -> do+ r <- o_insert t k v s+ pure $ case m_insert k v s m of+ Nothing -> (m, r == Nothing)+ Just m' -> (m', r == Just (m_root m'))+ Delete k -> do+ r <- o_delete t k+ let m' = m_delete k m+ pure (m', r == m_root m')+ Many kvs -> do+ r <- o_insert_many t kvs+ pure $ case m_insert_many kvs m of+ Nothing -> (m, r == Nothing)+ Just m' -> (m', r == Just (m_root m'))++-- properties -----------------------------------------------------------------++properties+ :: (Eq p, Show p) => String -> Ops s t m p -> TestTree+properties name o@Ops {..} = testGroup name [+ Q.testProperty "stored trees agree with in-memory ones" $+ \(Ops' ks os) -> Q.ioProperty $ with_store o $ \st -> do+ let t = o_tree st "tree"+ (m, ok) <- foldM (\(m, ok) op -> do+ (m', ok') <- step o t m op+ pure (m', ok && ok')) (m_empty, True) os+ r <- o_root t+ ls <- forM ks (o_lookup t)+ ps <- forM ks (o_prove t)+ pure $ Q.conjoin [+ Q.counterexample "roots" (ok Q..&&. r Q.=== m_root m)+ , Q.counterexample "lookups" (ls Q.=== fmap (`m_lookup` m) ks)+ , Q.counterexample "proofs" (ps Q.=== fmap (`m_prove` m) ks)+ ]++ , Q.testProperty "trees persist across reopening" $+ \(Ops' ks os) -> Q.ioProperty $ with_path $ \path -> do+ (r, ls) <- bracket (o_open path) o_close $ \st -> do+ let t = o_tree st "tree"+ forM_ os (run o t)+ (,) <$> o_root t <*> forM ks (o_lookup t)+ (r', ls') <- bracket (o_open path) o_close $ \st -> do+ let t = o_tree st "tree"+ (,) <$> o_root t <*> forM ks (o_lookup t)+ pure (r' Q.=== r Q..&&. ls' Q.=== ls)++ , Q.testProperty "named trees are independent" $+ \(Ops' _ os) (Ops' _ os') -> Q.ioProperty $ with_store o $ \st -> do+ let a = o_tree st "a"+ b = o_tree st "b"+ forM_ os (run o a)+ ra <- o_root a+ forM_ os' (run o b)+ ra' <- o_root a+ pure (ra' Q.=== ra)+ ]