mssmt-lmdb

An LMDB-backed Merkle-Sum Sparse Merkle Tree.
git clone git://git.jtobin.io/mssmt-lmdb.git
Log | Files | Refs | README | LICENSE | git.jtobin.io

commit 295a91b084bf7d17235456ed16ecf493bc2c7692
Author: Jared Tobin <jared@jtobin.io>
Date:   Wed,  4 Nov 2026 22:48:43 +0400

lib: init

An LMDB-backed merkle-sum sparse merkle tree, via mssmt and ppad-lmdb.
A store holds any number of named trees under one scheme, split or
aggregate: their nodes, keyed by the hash of their commitments, and
each tree's root, by name.

Each operation runs in one transaction: it loads only the paths it
touches into an in-memory tree of stubs, applies mssmt's in-memory
operation, and writes the nodes it created. Data.MSSMT.LMDB.Split and
Data.MSSMT.LMDB.Aggregate export each scheme's store, with
Data.MSSMT.LMDB re-exporting Split.

Tests check, under both schemes, that stored trees agree with
in-memory ones over random operations (roots after each, and lookups
and proofs at the end), that trees persist across reopening, and that
named trees in one store are independent.

Diffstat:
A.gitignore | 1+
ALICENSE | 20++++++++++++++++++++
Aflake.lock | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aflake.nix | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Alib/Data/MSSMT/LMDB.hs | 26++++++++++++++++++++++++++
Alib/Data/MSSMT/LMDB/Aggregate.hs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Alib/Data/MSSMT/LMDB/Internal.hs | 402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Alib/Data/MSSMT/LMDB/Split.hs | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amssmt-lmdb.cabal | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atest/Main.hs | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 1264 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +dist-newstyle/ diff --git a/LICENSE b/LICENSE @@ -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. diff --git a/flake.lock b/flake.lock @@ -0,0 +1,224 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "mssmt": { + "inputs": { + "flake-utils": [ + "mssmt", + "ppad-nixpkgs", + "flake-utils" + ], + "nixpkgs": [ + "mssmt", + "ppad-nixpkgs", + "nixpkgs" + ], + "ppad-base16": [ + "ppad-base16" + ], + "ppad-nixpkgs": [ + "ppad-nixpkgs" + ], + "ppad-sha256": [ + "ppad-sha256" + ] + }, + "locked": { + "lastModified": 1793817010, + "narHash": "sha256-4yU/PgQwloSN/zePgY2+FRhBt+uoDet+ewGbdoanXaU=", + "ref": "refs/heads/master", + "rev": "485b72aab2e5246dc778ae04f0dbd024ba65f36a", + "revCount": 22, + "type": "git", + "url": "file:///Users/jtobin/src/mssmt" + }, + "original": { + "type": "git", + "url": "file:///Users/jtobin/src/mssmt" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1766840161, + "narHash": "sha256-Ss/LHpJJsng8vz1Pe33RSGIWUOcqM1fjrehjUkdrWio=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "3edc4a30ed3903fdf6f90c837f961fa6b49582d1", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "ppad-base16": { + "inputs": { + "flake-utils": [ + "ppad-base16", + "ppad-nixpkgs", + "flake-utils" + ], + "nixpkgs": [ + "ppad-base16", + "ppad-nixpkgs", + "nixpkgs" + ], + "ppad-nixpkgs": [ + "ppad-nixpkgs" + ] + }, + "locked": { + "lastModified": 1791644351, + "narHash": "sha256-Bxy64e428CycDJlUIQ/s8UvYt9+Synvt85hw7u2Zz8Q=", + "ref": "master", + "rev": "a87cfc3f6c0fc78ed3611ac653114bb61de3c426", + "revCount": 43, + "type": "git", + "url": "git://git.ppad.tech/base16.git" + }, + "original": { + "ref": "master", + "type": "git", + "url": "git://git.ppad.tech/base16.git" + } + }, + "ppad-lmdb": { + "inputs": { + "flake-utils": [ + "ppad-lmdb", + "ppad-nixpkgs", + "flake-utils" + ], + "nixpkgs": [ + "ppad-lmdb", + "ppad-nixpkgs", + "nixpkgs" + ], + "ppad-nixpkgs": [ + "ppad-nixpkgs" + ] + }, + "locked": { + "lastModified": 1793817508, + "narHash": "sha256-Gon+HJrLte7IudHLpDoqkmFJRfWXLg8kz0hndDM0H4Q=", + "ref": "master", + "rev": "571c6343547f037fce42fc28a397a1b18b3eb7f1", + "revCount": 20, + "type": "git", + "url": "git://git.ppad.tech/lmdb.git" + }, + "original": { + "ref": "master", + "type": "git", + "url": "git://git.ppad.tech/lmdb.git" + } + }, + "ppad-nixpkgs": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + }, + "locked": { + "lastModified": 1766932084, + "narHash": "sha256-GvVsbTfW+B7IQ9K/QP2xcXJAm1lhBin1jYZWNjOzT+o=", + "ref": "master", + "rev": "353e61763b959b960a55321a85423501e3e9ed7a", + "revCount": 2, + "type": "git", + "url": "git://git.ppad.tech/nixpkgs.git" + }, + "original": { + "ref": "master", + "type": "git", + "url": "git://git.ppad.tech/nixpkgs.git" + } + }, + "ppad-sha256": { + "inputs": { + "flake-utils": [ + "ppad-sha256", + "ppad-nixpkgs", + "flake-utils" + ], + "nixpkgs": [ + "ppad-sha256", + "ppad-nixpkgs", + "nixpkgs" + ], + "ppad-base16": [ + "ppad-base16" + ], + "ppad-nixpkgs": [ + "ppad-nixpkgs" + ] + }, + "locked": { + "lastModified": 1793438429, + "narHash": "sha256-cyiBtzrb1Mco1Owc5h5Kl+iNVVrmjXcNBHHomREFlic=", + "ref": "master", + "rev": "902e3f6a31fbccc8b92f9c6e4ab80f94237b45b5", + "revCount": 153, + "type": "git", + "url": "git://git.ppad.tech/sha256.git" + }, + "original": { + "ref": "master", + "type": "git", + "url": "git://git.ppad.tech/sha256.git" + } + }, + "root": { + "inputs": { + "flake-utils": [ + "ppad-nixpkgs", + "flake-utils" + ], + "mssmt": "mssmt", + "nixpkgs": [ + "ppad-nixpkgs", + "nixpkgs" + ], + "ppad-base16": "ppad-base16", + "ppad-lmdb": "ppad-lmdb", + "ppad-nixpkgs": "ppad-nixpkgs", + "ppad-sha256": "ppad-sha256" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix @@ -0,0 +1,97 @@ +{ + description = "An LMDB-backed merkle-sum sparse merkle tree."; + + inputs = { + mssmt = { + url = "git+file:///Users/jtobin/src/mssmt"; + inputs.ppad-base16.follows = "ppad-base16"; + inputs.ppad-sha256.follows = "ppad-sha256"; + inputs.ppad-nixpkgs.follows = "ppad-nixpkgs"; + }; + ppad-lmdb = { + type = "git"; + url = "git://git.ppad.tech/lmdb.git"; + ref = "master"; + inputs.ppad-nixpkgs.follows = "ppad-nixpkgs"; + }; + ppad-base16 = { + type = "git"; + url = "git://git.ppad.tech/base16.git"; + ref = "master"; + inputs.ppad-nixpkgs.follows = "ppad-nixpkgs"; + }; + ppad-sha256 = { + type = "git"; + url = "git://git.ppad.tech/sha256.git"; + ref = "master"; + inputs.ppad-base16.follows = "ppad-base16"; + inputs.ppad-nixpkgs.follows = "ppad-nixpkgs"; + }; + ppad-nixpkgs = { + type = "git"; + url = "git://git.ppad.tech/nixpkgs.git"; + ref = "master"; + }; + flake-utils.follows = "ppad-nixpkgs/flake-utils"; + nixpkgs.follows = "ppad-nixpkgs/nixpkgs"; + }; + + outputs = { self, nixpkgs, flake-utils, ppad-nixpkgs + , mssmt, ppad-lmdb, ppad-base16, ppad-sha256 + }: + flake-utils.lib.eachDefaultSystem (system: + let + lib = "mssmt-lmdb"; + + pkgs = import nixpkgs { inherit system; }; + hlib = pkgs.haskell.lib; + llvm = pkgs.llvmPackages_19.llvm; + clang = pkgs.llvmPackages_19.clang; + + with-llvm = p: + hlib.addBuildTools (hlib.enableCabalFlag p "llvm") [ llvm clang ]; + + hpkgs = pkgs.haskell.packages.ghc910.extend (new: old: { + ppad-base16 = with-llvm ppad-base16.packages.${system}.default; + ppad-sha256 = with-llvm ppad-sha256.packages.${system}.default; + ppad-lmdb = with-llvm ppad-lmdb.packages.${system}.default; + mssmt = with-llvm mssmt.packages.${system}.default; + ${lib} = new.callCabal2nix lib ./. { + mssmt = new.mssmt; + ppad-lmdb = new.ppad-lmdb; + }; + }); + + cc = pkgs.stdenv.cc; + ghc = hpkgs.ghc; + cabal = hpkgs.cabal-install; + in + { + packages.default = hpkgs.${lib}; + + devShells.default = hpkgs.shellFor { + packages = p: [ + (hlib.doBenchmark p.${lib}) + ]; + + buildInputs = [ + cabal + cc + llvm + clang + ]; + + doBenchmark = true; + + shellHook = '' + PS1="[${lib}] \w$ " + echo "entering ${system} shell, using" + echo "cc: $(${cc}/bin/cc --version | head -1)" + echo "ghc: $(${ghc}/bin/ghc --version)" + echo "cabal: $(${cabal}/bin/cabal --version | head -1)" + echo "llc: $(${llvm}/bin/llc --version | head -2 | tail -1)" + ''; + }; + } + ); +} diff --git a/lib/Data/MSSMT/LMDB.hs b/lib/Data/MSSMT/LMDB.hs @@ -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) diff --git a/lib/Data/MSSMT/LMDB/Aggregate.hs b/lib/Data/MSSMT/LMDB/Aggregate.hs @@ -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 diff --git a/lib/Data/MSSMT/LMDB/Internal.hs b/lib/Data/MSSMT/LMDB/Internal.hs @@ -0,0 +1,402 @@ +{-# 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 + 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 + BU.unsafeUseAsCString k $ \q -> copyBytes (p `plusPtr` 41) (castPtr q) 32 + BU.unsafeUseAsCString v $ \q -> + copyBytes (p `plusPtr` 73) (castPtr q) (BS.length v) + +-- | A branch's record, given its children. +branch_record :: I.Tree -> I.Tree -> 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 -> BS.ByteString +root_record t = BI.unsafeCreate 41 $ \p -> poke_child p 0 t + +poke_child :: Ptr Word8 -> Int -> I.Tree -> 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 +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 +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 +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 +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 +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 -> 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) -> Bool -> BS.ByteString + -> [Key] -> IO I.Tree +loaded st txn seen deleting name ks = do + r <- stored_root st txn name + foldM (\t k -> expander (loader st txn seen) k t) r ks + where + expander + | deleting && store_scheme st == Aggregate = I.expand_deleting + | otherwise = I.expand + +-- 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 -> Bool -> [Key] + -> (I.Tree -> Maybe I.Tree) -> IO (Maybe Commitment) +update_in st txn name deleting ks f = do + seen <- newIORef S.empty + t <- loaded st txn seen deleting name ks + case f t 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 (vacant v s) [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 (any (\(_, v, s) -> vacant v s) kvs) + [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 True [k] + (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 + I.lookup k <$> loaded st txn seen False name [k] + +-- | '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 + I.prove_split k <$> loaded st txn seen False name [k] + +-- | '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 + I.prove_aggregate k <$> loaded st txn seen False name [k] + +vacant :: BS.ByteString -> Word64 -> Bool +vacant v s = BS.null v && s == 0 + +-- 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 diff --git a/lib/Data/MSSMT/LMDB/Split.hs b/lib/Data/MSSMT/LMDB/Split.hs @@ -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) diff --git a/mssmt-lmdb.cabal b/mssmt-lmdb.cabal @@ -0,0 +1,56 @@ +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 +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 diff --git a/test/Main.hs b/test/Main.hs @@ -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) + ]