Internal.hs (13667B)
1 {-# OPTIONS_HADDOCK hide #-} 2 {-# LANGUAGE BangPatterns #-} 3 {-# LANGUAGE OverloadedStrings #-} 4 5 -- | 6 -- Module: Data.MSSMT.LMDB.Internal 7 -- Copyright: (c) 2026 Jared Tobin 8 -- License: MIT 9 -- Maintainer: Jared Tobin <jared@jtobin.io> 10 -- 11 -- LMDB-backed MS-SMT internals. 12 -- 13 -- A store holds the nodes of any number of named trees, each keyed by 14 -- the hash of its commitment, and each tree's root by name. An 15 -- operation on a tree runs in one transaction: it loads the paths it 16 -- touches, applies the in-memory operation, and writes the nodes it 17 -- creates. 18 19 module Data.MSSMT.LMDB.Internal ( 20 -- * Stores 21 Store(..) 22 , StoreException(..) 23 , open 24 , close 25 26 -- * Trees 27 , root 28 , insert 29 , insert_many 30 , delete 31 , lookup 32 , prove_split 33 , prove_aggregate 34 35 -- * Within transactions 36 , root_in 37 , insert_in 38 , insert_many_in 39 , delete_in 40 , lookup_in 41 , prove_split_in 42 , prove_aggregate_in 43 44 -- * Records 45 , leaf_record 46 , branch_record 47 , decode 48 ) where 49 50 import Control.Exception (Exception, throwIO) 51 import Control.Monad (foldM, void) 52 import Data.Bits (unsafeShiftL, unsafeShiftR, (.|.)) 53 import qualified Data.ByteString as BS 54 import qualified Data.ByteString.Internal as BI 55 import qualified Data.ByteString.Unsafe as BU 56 import Data.IORef (IORef, modifyIORef', newIORef, readIORef) 57 import Data.MSSMT.Hash (unsafe_hash) 58 import Data.MSSMT.Internal ( 59 Commitment(..), Hash(..), Key(..), Kind(..), Neighbor, Scheme(..) 60 ) 61 import qualified Data.MSSMT.Internal as I 62 import qualified Data.Set as S 63 import Data.Word (Word8, Word64) 64 import qualified Database.LMDB as L 65 import Foreign.Marshal.Utils (copyBytes, fillBytes) 66 import Foreign.Ptr (Ptr, castPtr, plusPtr) 67 import Foreign.Storable (pokeByteOff) 68 import Prelude hiding (lookup) 69 70 -- stores --------------------------------------------------------------------- 71 72 -- | A store of trees, held in an LMDB environment. 73 data Store = Store { 74 store_scheme :: !Scheme 75 , store_env :: !L.Env 76 , store_nodes :: !L.Dbi 77 , store_roots :: !L.Dbi 78 } 79 80 -- | A store whose records are missing or malformed. 81 data StoreException = 82 -- | A node a tree refers to is absent. 83 MissingNode !Hash 84 -- | A node's record is malformed. 85 | BadNode !Hash 86 -- | A tree's root record is malformed. 87 | BadRoot !BS.ByteString 88 -- | An operation met a node it hadn't loaded. Operations load their 89 -- paths before running, so this indicates a bug. 90 | Unloaded !Hash 91 deriving (Eq, Show) 92 93 instance Exception StoreException 94 95 -- | Open a store of trees under a scheme, at a path. 96 -- 97 -- The environment holds two databases per scheme, so trees under 98 -- each can share it. 99 open :: Scheme -> FilePath -> L.EnvFlags -> IO Store 100 open sc path flags = do 101 env <- L.open path flags { L.envMaxDbs = max 4 (L.envMaxDbs flags) } 102 nodes <- L.openDbi env (Just (prefix <> "/nodes")) True 103 roots <- L.openDbi env (Just (prefix <> "/roots")) True 104 pure (Store sc env nodes roots) 105 where 106 prefix = case sc of 107 Split -> "split" 108 Aggregate -> "aggregate" 109 110 -- | Close a store. 111 close :: Store -> IO () 112 close = L.close . store_env 113 114 -- records -------------------------------------------------------------------- 115 116 -- A leaf's record is a zero byte, then its hash, sum, key, and value. A 117 -- branch's is a one byte, then each child's kind (zero for an empty 118 -- subtree, one for a single leaf, and two for a branch), hash, and sum; 119 -- an empty child's hash and sum are zero. A root's record is that of a 120 -- branch's child. 121 122 -- | A leaf's record. 123 leaf_record :: Commitment -> Hash -> Key -> BS.ByteString -> BS.ByteString 124 leaf_record (Commitment _ s) lh (Key k) v = 125 BI.unsafeCreate (73 + BS.length v) $ \p -> do 126 pokeByteOff p 0 (0 :: Word8) 127 poke_hash p 1 lh 128 poke_be64 p 33 s 129 poke_hash p 41 k 130 BU.unsafeUseAsCString v $ \q -> 131 copyBytes (p `plusPtr` 73) (castPtr q) (BS.length v) 132 133 -- | A branch's record, given its children. 134 branch_record :: I.Tree Kind -> I.Tree Kind -> BS.ByteString 135 branch_record l r = BI.unsafeCreate 83 $ \p -> do 136 pokeByteOff p 0 (1 :: Word8) 137 poke_child p 1 l 138 poke_child p 42 r 139 140 root_record :: I.Tree Kind -> BS.ByteString 141 root_record t = BI.unsafeCreate 41 $ \p -> poke_child p 0 t 142 143 poke_child :: Ptr Word8 -> Int -> I.Tree Kind -> IO () 144 poke_child p i t = case t of 145 I.Empty -> do 146 pokeByteOff p i (0 :: Word8) 147 fillBytes (p `plusPtr` (i + 1)) 0 40 148 I.Leaf c _ _ _ -> with 1 c 149 I.Node _ c _ -> with 2 c 150 I.Stub Single c -> with 1 c 151 I.Stub Branch c -> with 2 c 152 where 153 with :: Word8 -> Commitment -> IO () 154 with kd (Commitment h s) = do 155 pokeByteOff p i kd 156 poke_hash p (i + 1) h 157 poke_be64 p (i + 33) s 158 159 poke_hash :: Ptr Word8 -> Int -> Hash -> IO () 160 poke_hash p i (Hash a b c d) = do 161 poke_be64 p i a 162 poke_be64 p (i + 8) b 163 poke_be64 p (i + 16) c 164 poke_be64 p (i + 24) d 165 166 poke_be64 :: Ptr Word8 -> Int -> Word64 -> IO () 167 poke_be64 p i w = do 168 pokeByteOff p (i + 0) (fromIntegral (w `unsafeShiftR` 56) :: Word8) 169 pokeByteOff p (i + 1) (fromIntegral (w `unsafeShiftR` 48) :: Word8) 170 pokeByteOff p (i + 2) (fromIntegral (w `unsafeShiftR` 40) :: Word8) 171 pokeByteOff p (i + 3) (fromIntegral (w `unsafeShiftR` 32) :: Word8) 172 pokeByteOff p (i + 4) (fromIntegral (w `unsafeShiftR` 24) :: Word8) 173 pokeByteOff p (i + 5) (fromIntegral (w `unsafeShiftR` 16) :: Word8) 174 pokeByteOff p (i + 6) (fromIntegral (w `unsafeShiftR` 8) :: Word8) 175 pokeByteOff p (i + 7) (fromIntegral w :: Word8) 176 177 -- big-endian word at an offset; callers check the length 178 be64_at :: BS.ByteString -> Int -> Word64 179 be64_at bs i = go 0 0 where 180 go !acc j 181 | j == 8 = acc 182 | otherwise = 183 let w = fromIntegral (BU.unsafeIndex bs (i + j)) :: Word64 184 in go (acc `unsafeShiftL` 8 .|. w) (j + 1) 185 186 -- a commitment at an offset; callers check the length 187 commitment_at :: BS.ByteString -> Int -> Commitment 188 commitment_at bs i = 189 Commitment (unsafe_hash (BU.unsafeDrop i bs)) (be64_at bs (i + 32)) 190 191 -- a child at an offset, as a stub; callers check the length 192 child_at :: BS.ByteString -> Int -> Maybe (I.Tree Kind) 193 child_at bs i = case BU.unsafeIndex bs i of 194 0 -> Just I.Empty 195 1 -> Just (I.Stub Single (commitment_at bs (i + 1))) 196 2 -> Just (I.Stub Branch (commitment_at bs (i + 1))) 197 _ -> Nothing 198 199 -- | A node from its record, given its commitment, with its subtrees as 200 -- stubs. 201 decode :: Commitment -> BS.ByteString -> Maybe (I.Tree Kind) 202 decode c bs 203 | n == 83 && tag == 1 = do 204 l <- child_at bs 1 205 r <- child_at bs 42 206 pure (I.Node l c r) 207 | n >= 73 && tag == 0 = do 208 k <- I.key (BS.take 32 (BU.unsafeDrop 41 bs)) 209 let Commitment _ s = c 210 if be64_at bs 33 == s 211 then pure (I.Leaf c (unsafe_hash (BU.unsafeDrop 1 bs)) k 212 (BU.unsafeDrop 73 bs)) 213 else Nothing 214 | otherwise = Nothing 215 where 216 n = BS.length bs 217 tag = if n == 0 then 255 else BU.unsafeIndex bs 0 218 219 decode_root :: BS.ByteString -> Maybe (I.Tree Kind) 220 decode_root bs 221 | BS.length bs == 41 = case child_at bs 0 of 222 Just I.Empty -> Nothing 223 t -> t 224 | otherwise = Nothing 225 226 -- loading and persisting ----------------------------------------------------- 227 228 -- load a stub's node from a store, noting its hash 229 loader 230 :: Store -> L.Txn t -> IORef (S.Set Hash) -> Kind -> Commitment 231 -> IO (I.Tree Kind) 232 loader st txn seen _ c@(Commitment h _) = do 233 mr <- L.get txn (store_nodes st) (I.serialize_hash h) 234 case mr of 235 Nothing -> throwIO (MissingNode h) 236 Just r -> case decode c r of 237 Nothing -> throwIO (BadNode h) 238 Just t -> do 239 modifyIORef' seen (S.insert h) 240 pure t 241 242 -- a tree's root, as a stub 243 stored_root :: Store -> L.Txn t -> BS.ByteString -> IO (I.Tree Kind) 244 stored_root st txn name = do 245 mr <- L.get txn (store_roots st) name 246 case mr of 247 Nothing -> pure I.Empty 248 Just r -> maybe (throwIO (BadRoot name)) pure (decode_root r) 249 250 -- write the nodes of a tree that weren't loaded from the store 251 persist :: Store -> L.Txn L.RW -> S.Set Hash -> I.Tree Kind -> IO () 252 persist st txn seen = go where 253 go t = case t of 254 I.Empty -> pure () 255 I.Stub {} -> pure () 256 I.Leaf c@(Commitment h _) lh k v 257 | S.member h seen -> pure () 258 | otherwise -> 259 L.put txn (store_nodes st) (I.serialize_hash h) 260 (leaf_record c lh k v) 261 I.Node l (Commitment h _) r 262 | S.member h seen -> pure () 263 | otherwise -> do 264 L.put txn (store_nodes st) (I.serialize_hash h) (branch_record l r) 265 go l 266 go r 267 268 -- the tree at a name, with the paths to some keys loaded 269 loaded 270 :: Store -> L.Txn t -> IORef (S.Set Hash) -> BS.ByteString -> [Key] 271 -> IO (I.Tree Kind) 272 loaded st txn seen name ks = do 273 r <- stored_root st txn name 274 foldM (\t k -> I.expand (loader st txn seen) k t) r ks 275 276 -- the result of an operation on a tree with its paths loaded 277 settled :: Either (I.Missing Kind) a -> IO a 278 settled = either (\(I.Missing _ (Commitment h _)) -> throwIO (Unloaded h)) pure 279 280 -- apply an update to the tree at a name, loading the paths to some keys 281 -- first, and writing what it creates 282 update_in 283 :: Store -> L.Txn L.RW -> BS.ByteString -> [Key] 284 -> (I.Tree Kind -> Either (I.Missing Kind) (Maybe (I.Tree Kind))) 285 -> IO (Maybe Commitment) 286 update_in st txn name ks f = do 287 seen <- newIORef S.empty 288 t <- loaded st txn seen name ks 289 r <- settled (f t) 290 case r of 291 Nothing -> pure Nothing 292 Just t' -> do 293 s <- readIORef seen 294 persist st txn s t' 295 case t' of 296 I.Empty -> void (L.del txn (store_roots st) name) 297 _ -> L.put txn (store_roots st) name (root_record t') 298 pure (Just (I.root_with (store_scheme st) t')) 299 300 -- within transactions -------------------------------------------------------- 301 302 -- | 'root', within a transaction. 303 root_in :: Store -> L.Txn t -> BS.ByteString -> IO Commitment 304 root_in st txn name = I.root_with (store_scheme st) <$> stored_root st txn name 305 306 -- | 'insert', within a transaction. 307 insert_in 308 :: Store -> L.Txn L.RW -> BS.ByteString -> Key -> BS.ByteString -> Word64 309 -> IO (Maybe Commitment) 310 insert_in st txn name k v s = 311 update_in st txn name [k] (I.insert_with (store_scheme st) k v s) 312 313 -- | 'insert_many', within a transaction. 314 insert_many_in 315 :: Store -> L.Txn L.RW -> BS.ByteString -> [(Key, BS.ByteString, Word64)] 316 -> IO (Maybe Commitment) 317 insert_many_in st txn name kvs = 318 update_in st txn name [k | (k, _, _) <- kvs] 319 (I.insert_many_with (store_scheme st) kvs) 320 321 -- | 'delete', within a transaction. 322 delete_in :: Store -> L.Txn L.RW -> BS.ByteString -> Key -> IO Commitment 323 delete_in st txn name k = do 324 mr <- update_in st txn name [k] 325 (fmap Just . I.delete_with (store_scheme st) k) 326 maybe (root_in st txn name) pure mr 327 328 -- | 'lookup', within a transaction. 329 lookup_in 330 :: Store -> L.Txn t -> BS.ByteString -> Key 331 -> IO (Maybe (BS.ByteString, Word64)) 332 lookup_in st txn name k = do 333 seen <- newIORef S.empty 334 t <- loaded st txn seen name [k] 335 settled (I.lookup k t) 336 337 -- | 'prove_split', within a transaction. 338 prove_split_in 339 :: Store -> L.Txn t -> BS.ByteString -> Key 340 -> IO (Maybe Neighbor, [Commitment]) 341 prove_split_in st txn name k = do 342 seen <- newIORef S.empty 343 t <- loaded st txn seen name [k] 344 settled (I.prove_split k t) 345 346 -- | 'prove_aggregate', within a transaction. 347 prove_aggregate_in 348 :: Store -> L.Txn t -> BS.ByteString -> Key -> IO [Commitment] 349 prove_aggregate_in st txn name k = do 350 seen <- newIORef S.empty 351 t <- loaded st txn seen name [k] 352 settled (I.prove_aggregate k t) 353 354 -- trees ---------------------------------------------------------------------- 355 356 -- | The root commitment of the tree at a name. 357 root :: Store -> BS.ByteString -> IO Commitment 358 root st name = L.withReadTxn (store_env st) $ \txn -> root_in st txn name 359 360 -- | Insert a value and sum at a key in the tree at a name, replacing any 361 -- existing leaf, and return the new root. 362 -- 363 -- Returns 'Nothing', changing nothing, if the tree's sum would 364 -- overflow. 365 insert 366 :: Store -> BS.ByteString -> Key -> BS.ByteString -> Word64 367 -> IO (Maybe Commitment) 368 insert st name k v s = 369 L.withWriteTxn (store_env st) $ \txn -> insert_in st txn name k v s 370 371 -- | Insert many values and sums in the tree at a name, in one 372 -- transaction, and return the new root. 373 -- 374 -- Where a key appears more than once, its last appearance wins, and 375 -- an empty value with zero sum deletes whatever is at its key. 376 -- Returns 'Nothing', changing nothing, if the resulting tree's sum 377 -- would overflow. 378 insert_many 379 :: Store -> BS.ByteString -> [(Key, BS.ByteString, Word64)] 380 -> IO (Maybe Commitment) 381 insert_many st name kvs = 382 L.withWriteTxn (store_env st) $ \txn -> insert_many_in st txn name kvs 383 384 -- | Delete the leaf at a key in the tree at a name, and return the new 385 -- root. 386 delete :: Store -> BS.ByteString -> Key -> IO Commitment 387 delete st name k = 388 L.withWriteTxn (store_env st) $ \txn -> delete_in st txn name k 389 390 -- | Look up the value and sum at a key in the tree at a name. 391 lookup 392 :: Store -> BS.ByteString -> Key -> IO (Maybe (BS.ByteString, Word64)) 393 lookup st name k = 394 L.withReadTxn (store_env st) $ \txn -> lookup_in st txn name k 395 396 -- | The siblings along a key's path in the split tree at a name, and the 397 -- leaf the path ends at, where that's another key's. 398 prove_split 399 :: Store -> BS.ByteString -> Key -> IO (Maybe Neighbor, [Commitment]) 400 prove_split st name k = 401 L.withReadTxn (store_env st) $ \txn -> prove_split_in st txn name k 402 403 -- | The 256 siblings along a key's path in the aggregate tree at a name. 404 prove_aggregate :: Store -> BS.ByteString -> Key -> IO [Commitment] 405 prove_aggregate st name k = 406 L.withReadTxn (store_env st) $ \txn -> prove_aggregate_in st txn name k