packages feed

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

{-# 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