mssmt

A high-performance Merkle-Sum Sparse Merkle Tree.
git clone git://git.jtobin.io/mssmt.git
Log | Files | Refs | README | LICENSE | git.jtobin.io

Vectors.hs (7161B)


      1 {-# LANGUAGE OverloadedStrings #-}
      2 {-# LANGUAGE RecordWildCards #-}
      3 
      4 -- Test vectors from taproot-assets (mssmt/testdata).
      5 
      6 module Vectors (
      7     Vectors
      8   , execute
      9   ) where
     10 
     11 import Control.Monad (foldM, forM_, guard)
     12 import Data.Aeson ((.:), (.:?))
     13 import qualified Data.Aeson as A
     14 import qualified Data.Aeson.Key as AK
     15 import qualified Data.Aeson.Types as AT
     16 import Data.Bits (shiftL, testBit, (.|.))
     17 import qualified Data.ByteString as BS
     18 import qualified Data.ByteString.Base16 as B16
     19 import qualified Data.ByteString.Char8 as B8
     20 import qualified Data.Map.Strict as M
     21 import Data.Maybe (fromMaybe, isJust, isNothing)
     22 import Data.MSSMT.Aggregate
     23 import qualified Data.Set as S
     24 import Data.Word (Word64)
     25 import Test.Tasty (TestTree, testGroup)
     26 import Test.Tasty.HUnit
     27 
     28 data Leaf = Leaf !Key !BS.ByteString !Word64
     29 
     30 data Valid = Valid {
     31     v_root     :: !Commitment
     32   , v_inserted :: ![Key]
     33   , v_deleted  :: ![Key]
     34   , v_replaced :: ![Leaf]
     35   , v_included :: ![(Key, Proof)]
     36   , v_excluded :: ![(Key, Proof)]
     37   , v_comment  :: !String
     38   }
     39 
     40 data Invalid = Invalid {
     41     i_inserted :: ![Key]
     42   , i_comment  :: !String
     43   }
     44 
     45 -- | A file of test vectors.
     46 data Vectors = Vectors {
     47     vs_leaves  :: ![Leaf]
     48   , vs_valid   :: ![Valid]
     49   , vs_invalid :: ![Invalid]
     50   }
     51 
     52 -- execution ------------------------------------------------------------------
     53 
     54 -- | Run a file's test cases.
     55 execute :: String -> Vectors -> TestTree
     56 execute name Vectors {..} = testGroup name $
     57      fmap (execute_valid vs_leaves) vs_valid
     58   <> fmap (execute_invalid vs_leaves) vs_invalid
     59 
     60 -- leaves are inserted in file order, as in the taproot-assets runner
     61 inserting :: [Leaf] -> [Key] -> [Leaf]
     62 inserting ls ks = filter (\(Leaf k _ _) -> S.member k set) ls where
     63   set = S.fromList ks
     64 
     65 insert_all :: Tree -> [Leaf] -> Maybe Tree
     66 insert_all = foldM (\t (Leaf k v s) -> insert k v s t)
     67 
     68 execute_valid :: [Leaf] -> Valid -> TestTree
     69 execute_valid ls Valid {..} = testGroup v_comment [
     70       testCase "root" $
     71         assertEqual mempty (Just v_root) (fmap root tree)
     72     , testCase ("inclusion proofs (" <> show (length v_included) <> ")") $
     73         forM_ (zip [0 :: Int ..] v_included) $ \(i, (k, p)) ->
     74           case (tree, M.lookup k leaves) of
     75             (Just t, Just (Leaf _ v s)) -> do
     76               assertEqual ("prove " <> show i) p (prove k t)
     77               assertBool ("verify " <> show i) (verify k v s p (root t))
     78             _ -> assertFailure ("missing tree or leaf " <> show i)
     79     , testCase ("exclusion proofs (" <> show (length v_excluded) <> ")") $
     80         forM_ (zip [0 :: Int ..] v_excluded) $ \(i, (k, p)) ->
     81           case tree of
     82             Just t -> do
     83               assertEqual ("prove " <> show i) p (prove k t)
     84               assertBool ("verify " <> show i) (verify k mempty 0 p (root t))
     85             Nothing -> assertFailure "missing tree"
     86     ]
     87   where
     88     leaves = M.fromList [(k, l) | l@(Leaf k _ _) <- ls]
     89     tree = do
     90       t <- insert_all empty (inserting ls v_inserted)
     91       insert_all (foldr delete t v_deleted) v_replaced
     92 
     93 -- every insert but the last succeeds; the last overflows
     94 execute_invalid :: [Leaf] -> Invalid -> TestTree
     95 execute_invalid ls Invalid {..} = testCase i_comment $ do
     96   let leaves = inserting ls i_inserted
     97   assertBool "no leaves" (not (null leaves))
     98   assertBool "prefix" $
     99     isJust (insert_all empty (take (length leaves - 1) leaves))
    100   assertBool "overflow" $
    101     isNothing (insert_all empty leaves)
    102 
    103 -- parsing --------------------------------------------------------------------
    104 
    105 instance A.FromJSON Vectors where
    106   parseJSON = A.withObject "Vectors" $ \o -> Vectors
    107     <$> o .: "all_tree_leaves"
    108     <*> list o "valid_test_cases"
    109     <*> list o "error_test_cases"
    110 
    111 instance A.FromJSON Leaf where
    112   parseJSON = A.withObject "Leaf" $ \o -> do
    113     n <- o .: "node"
    114     Leaf
    115       <$> (o .: "key" >>= parse_key)
    116       <*> (n .: "value" >>= parse_hex)
    117       <*> (n .: "sum" >>= parse_sum)
    118 
    119 instance A.FromJSON Valid where
    120   parseJSON = A.withObject "Valid" $ \o -> do
    121     h <- o .: "root_hash" >>= parse_hex >>= parse_digest
    122     s <- o .: "root_sum" >>= parse_sum
    123     Valid (Commitment h s)
    124       <$> (list o "inserted_leaves" >>= traverse parse_key)
    125       <*> (list o "deleted_leaves" >>= traverse parse_key)
    126       <*> list o "replaced_leaves"
    127       <*> (list o "inclusion_proofs" >>= traverse parse_case)
    128       <*> (list o "exclusion_proofs" >>= traverse parse_case)
    129       <*> o .: "comment"
    130 
    131 instance A.FromJSON Invalid where
    132   parseJSON = A.withObject "Invalid" $ \o -> Invalid
    133     <$> (list o "inserted_leaves" >>= traverse parse_key)
    134     <*> o .: "comment"
    135 
    136 -- absent and null lists are empty
    137 list :: A.FromJSON a => A.Object -> AK.Key -> AT.Parser [a]
    138 list o k = fromMaybe [] <$> o .:? k
    139 
    140 parse_case :: A.Value -> AT.Parser (Key, Proof)
    141 parse_case = A.withObject "ProofCase" $ \o -> (,)
    142   <$> (o .: "proof_key" >>= parse_key)
    143   <*> (o .: "compressed_proof" >>= parse_hex >>= parse_proof)
    144 
    145 parse_hex :: String -> AT.Parser BS.ByteString
    146 parse_hex s = maybe (fail ("bad hex: " <> s)) pure (B16.decode (B8.pack s))
    147 
    148 parse_digest :: BS.ByteString -> AT.Parser Hash
    149 parse_digest bs = maybe (fail "bad hash") pure (parse_hash bs)
    150 
    151 parse_key :: String -> AT.Parser Key
    152 parse_key s = parse_hex s >>= maybe (fail ("bad key: " <> s)) pure . key
    153 
    154 parse_sum :: String -> AT.Parser Word64
    155 parse_sum s = case reads s :: [(Integer, String)] of
    156   [(n, "")] | n >= 0 && n <= toInteger (maxBound :: Word64) ->
    157     pure (fromInteger n)
    158   _ -> fail ("bad sum: " <> s)
    159 
    160 parse_proof :: BS.ByteString -> AT.Parser Proof
    161 parse_proof = maybe (fail "bad compressed proof") pure . decompress
    162 
    163 -- compressed proofs ----------------------------------------------------------
    164 
    165 -- a compressed proof is a big-endian uint16 count n, then n siblings
    166 -- as (32-byte hash, big-endian uint64 sum), then a 256-bit vector
    167 -- (LSB-first per byte) marking which siblings are empty subtrees
    168 decompress :: BS.ByteString -> Maybe Proof
    169 decompress bs0 = do
    170     let (c, bs1) = BS.splitAt 2 bs0
    171     guard (BS.length c == 2)
    172     (nodes, bs2) <- siblings (fromIntegral (be c)) bs1
    173     guard (BS.length bs2 == 32)
    174     let bits = concatMap (\w -> fmap (testBit w) [0 .. 7]) (BS.unpack bs2)
    175     es <- empties
    176     Proof <$> fill bits nodes es
    177   where
    178     -- aggregate empty-subtree commitments, leaf up: the siblings of any
    179     -- key in the empty tree
    180     empties = do
    181       k <- key (BS.replicate 32 0)
    182       let Proof es = prove k empty
    183       pure es
    184 
    185     siblings :: Int -> BS.ByteString -> Maybe ([Commitment], BS.ByteString)
    186     siblings 0 bs = Just ([], bs)
    187     siblings n bs
    188       | BS.length bs < 40 = Nothing
    189       | otherwise = do
    190           let (h, rest0) = BS.splitAt 32 bs
    191               (s, rest1) = BS.splitAt 8 rest0
    192           d <- parse_hash h
    193           (ps, rest) <- siblings (n - 1) rest1
    194           pure (Commitment d (be s) : ps, rest)
    195 
    196     fill (b:bs) ns (e:es)
    197       | b = (e :) <$> fill bs ns es
    198       | otherwise = case ns of
    199           (n:rest) -> (n :) <$> fill bs rest es
    200           [] -> Nothing
    201     fill [] [] [] = Just []
    202     fill _ _ _ = Nothing
    203 
    204 be :: BS.ByteString -> Word64
    205 be = BS.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) 0