packages feed

mssmt-0.1.0: test/Main.hs

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Main where

import Control.Monad (foldM)
import qualified Data.Aeson as A
import Data.Bits (testBit)
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as M
import Data.Maybe (isJust)
import Data.MSSMT
import qualified Data.MSSMT.Aggregate as Agg
import qualified Data.MSSMT.Hash as H
import qualified Data.MSSMT.Internal as I
import Data.Void (Void)
import Data.Word (Word32, Word64)
import Prelude hiding (lookup)
import Test.Tasty
import Test.Tasty.HUnit
import qualified Test.Tasty.QuickCheck as Q
import qualified Reference as R
import qualified Vectors as V

main :: IO ()
main = do
  vs <- traverse load files
  defaultMain $ testGroup "mssmt" [
      units
    , hashing
    , properties "split" split_ops
    , properties "aggregate" aggregate_ops
    , split_proofs
    , partial "split" I.Split I.prove_split
        (\k t -> I.complete (I.prove_split k t))
    , partial "aggregate" I.Aggregate I.prove_aggregate
        (\k t -> I.complete (I.prove_aggregate k t))
    , structure
    , testGroup "taproot-assets vectors" (zipWith V.execute files vs)
    ]
  where
    files = [
        "mssmt_tree_proofs.json"
      , "mssmt_tree_deletion.json"
      , "mssmt_tree_replacement.json"
      , "mssmt_tree_error_cases.json"
      ]
    load :: FilePath -> IO V.Vectors
    load f = A.eitherDecodeFileStrict' ("etc/" <> f)
      >>= either (\e -> fail (f <> ": " <> e)) pure

-- units ----------------------------------------------------------------------

units :: TestTree
units = testGroup "units" [
    testCase "keys are 32 bytes" $ do
      assertBool "31" (not (isJust (key (BS.replicate 31 0))))
      assertBool "32" (isJust (key (BS.replicate 32 0)))
      assertBool "33" (not (isJust (key (BS.replicate 33 0))))
  , testCase "hashes are 32 bytes" $ do
      assertBool "31" (not (isJust (parse_hash (BS.replicate 31 0))))
      assertBool "33" (not (isJust (parse_hash (BS.replicate 33 0))))
  , Q.testProperty "serialize_hash . parse_hash ~ id" $
      Q.forAll (BS.pack <$> Q.vector 32) $ \bs ->
        fmap serialize_hash (parse_hash bs) Q.=== Just bs
  , testCase "an empty value with zero sum is the empty leaf" $
      case key (BS.replicate 32 0) of
        Nothing -> assertFailure "key"
        Just k -> assertEqual mempty (Just empty) (insert k mempty 0 empty)
  , testCase "empty roots agree with the reference" $ do
      let Commitment h s = root empty
          Commitment g n = Agg.root Agg.empty
      assertEqual "split" (R.root M.empty) (serialize_hash h, s)
      assertEqual "aggregate" (R.root_aggregate M.empty) (serialize_hash g, n)
  , testCase "aggregate proofs have 256 siblings" $
      case key (BS.replicate 32 0) of
        Nothing -> assertFailure "key"
        Just k -> case Agg.insert k "a" 1 Agg.empty of
          Nothing -> assertFailure "insert"
          Just t -> do
            let Agg.Proof ps = Agg.prove k t
                r = Agg.root t
            assertEqual "length" 256 (length ps)
            assertBool "short" $
              not (Agg.verify k "a" 1 (Agg.Proof (drop 1 ps)) r)
            assertBool "long" $
              not (Agg.verify k "a" 1 (Agg.Proof (ps <> take 1 ps)) r)
  , testCase "split proofs run only as deep as their key's slot" $
      case key (BS.replicate 32 0) of
        Nothing -> assertFailure "key"
        Just k -> case insert k "a" 1 empty of
          Nothing -> assertFailure "insert"
          Just t -> do
            let p@(Proof nb ps) = prove k t
                r = root t
                e = root empty
            assertEqual "siblings" 0 (length ps)
            assertEqual "neighbor" Nothing nb
            assertBool "verify" (verify k "a" 1 p r)
            assertBool "long" $ not (verify k "a" 1 (Proof nb [e]) r)
            assertBool "too long" $
              not (verify k "a" 1 (Proof nb (replicate 257 e)) r)
  , testCase "proofs whose sums overflow are rejected" $
      case key z of
        Nothing -> assertFailure "key"
        Just k -> do
          -- roots over the leaf ("a", 1) at the all-zero key, whose path
          -- runs left at every level, and siblings of hash g, the
          -- deepest of the given sum and the rest of zero sum, with
          -- sums added as words, which wrap
          let g = H.unsafe_hash (BS.replicate 32 7)
              gb = serialize_hash g
              split_root n =
                let h = R.hash_node_split (R.hash_leaf_split z "a" 1) 1 gb n
                in  Commitment (H.unsafe_hash h) (1 + n)
              aggregate_root n =
                let up (h, t) gs =
                      (R.hash_node_aggregate h gb (t + gs), t + gs)
                    (rh, rt) = foldl up (R.hash_leaf_aggregate "a" 1, 1)
                      (n : replicate 255 0)
                in  Commitment (H.unsafe_hash rh) rt
              split_proof n = Proof Nothing [Commitment g n]
              aggregate_proof n =
                Agg.Proof (Commitment g n : replicate 255 (Commitment g 0))
              fits = maxBound - 1
          assertBool "split, fits" $
            verify k "a" 1 (split_proof fits) (split_root fits)
          assertBool "split, overflows" . not $
            verify k "a" 1 (split_proof maxBound) (split_root maxBound)
          assertBool "aggregate, fits" $
            Agg.verify k "a" 1 (aggregate_proof fits) (aggregate_root fits)
          assertBool "aggregate, overflows" . not $
            Agg.verify k "a" 1 (aggregate_proof maxBound)
              (aggregate_root maxBound)
  ]
  where
    z = BS.replicate 32 0

-- hashing --------------------------------------------------------------------

gen_hash :: Q.Gen Hash
gen_hash = fmap BS.pack (Q.vector 32) `Q.suchThatMap` parse_hash

-- each hash agrees with the reference; the native paths are checked
-- only where hardware SHA-256 is available
hashing :: TestTree
hashing = testGroup "hashing" $ [
      Q.testProperty "hash_leaf_split ~ reference" $
        Q.forAll gen_hash $ \k v -> Q.forAll big $ \s ->
          serialize_hash (I.hash_leaf_split k (I.hash_value (BS.pack v)) s)
            Q.=== R.hash_leaf_split (serialize_hash k) (BS.pack v) s
    , Q.testProperty "hash_leaf_aggregate ~ reference" $
        \v -> Q.forAll big $ \s ->
          serialize_hash (I.hash_leaf_aggregate (BS.pack v) s)
            Q.=== R.hash_leaf_aggregate (BS.pack v) s
    , split "hash_node_split_pure" I.hash_node_split_pure
    , aggregate "hash_node_aggregate_pure" I.hash_node_aggregate_pure
    ]
  <> [ split "hash_node_split_native" I.hash_node_split_native | I.native ]
  <> [ aggregate "hash_node_aggregate_native" I.hash_node_aggregate_native
     | I.native
     ]
  where
    split name f = Q.testProperty (name <> " ~ reference") $
      Q.forAll gen_hash $ \l -> Q.forAll big $ \sl ->
      Q.forAll gen_hash $ \r -> Q.forAll big $ \sr ->
        serialize_hash (f l sl r sr)
          Q.=== R.hash_node_split (serialize_hash l) sl (serialize_hash r) sr
    aggregate name f = Q.testProperty (name <> " ~ reference") $
      Q.forAll gen_hash $ \l -> Q.forAll gen_hash $ \r ->
      Q.forAll big $ \s ->
        serialize_hash (f l r s)
          Q.=== R.hash_node_aggregate (serialize_hash l) (serialize_hash r) s

-- properties -----------------------------------------------------------------

-- a key with the given prefix
gen_key :: BS.ByteString -> Q.Gen Key
gen_key pre =
  fmap ((pre <>) . BS.pack) (Q.vector (32 - BS.length pre))
    `Q.suchThatMap` key

-- a nonempty leaf, with a sum small enough that trees of leaves don't
-- overflow
data E = E !Key !BS.ByteString !Word64
  deriving Show

-- leaves whose keys share a random prefix, so that their paths share
-- up to 256 levels (and keys may collide)
data Es = Es !BS.ByteString [E]
  deriving Show

instance Q.Arbitrary Es where
  arbitrary = do
    pre <- BS.pack <$> (Q.chooseInt (0, 32) >>= Q.vector)
    Es pre <$> Q.listOf (E
      <$> gen_key pre
      <*> fmap BS.pack (Q.listOf1 Q.arbitrary)
      <*> fmap fromIntegral (Q.arbitrary :: Q.Gen Word32))
  shrink (Es pre es) = Es pre <$> Q.shrinkList (const []) es

-- a tree module's operations, and its reference root
data Ops t p = Ops {
    o_empty  :: t
  , o_insert :: Key -> BS.ByteString -> Word64 -> t -> Maybe t
  , o_insert_many :: [(Key, BS.ByteString, Word64)] -> t -> Maybe t
  , o_delete :: Key -> t -> t
  , o_lookup :: Key -> t -> Maybe (BS.ByteString, Word64)
  , o_root   :: t -> Commitment
  , o_prove  :: Key -> t -> p
  , o_verify :: Key -> BS.ByteString -> Word64 -> p -> Commitment -> Bool
  , o_ref    :: R.Leaves -> (BS.ByteString, Word64)
  }

split_ops :: Ops Tree Proof
split_ops = Ops empty insert insert_many delete lookup root prove verify R.root

aggregate_ops :: Ops Agg.Tree Agg.Proof
aggregate_ops = Ops
  Agg.empty Agg.insert Agg.insert_many Agg.delete Agg.lookup Agg.root
  Agg.prove Agg.verify R.root_aggregate

build :: Ops t p -> [E] -> Maybe t
build Ops {..} = foldM (\t (E k v s) -> o_insert k v s t) o_empty

-- later leaves replace earlier ones
model :: [E] -> M.Map Key (BS.ByteString, Word64)
model es = M.fromList [(k, (v, s)) | E k v s <- es]

-- a key from the leaves, or a fresh one under their prefix
pick :: Es -> Q.Gen Key
pick (Es pre es) = Q.oneof (gen_key pre : [Q.elements ks | not (null ks)])
  where
    ks = [k | E k _ _ <- es]

-- a batch of puts and deletions, at keys from the leaves or fresh ones
-- under their prefix, with sums from the given generator
gen_batch :: Q.Gen Word64 -> Es -> Q.Gen [(Key, BS.ByteString, Word64)]
gen_batch sums x = Q.listOf $ do
  k <- pick x
  Q.frequency [
      (3, (,,) k <$> fmap BS.pack (Q.listOf1 Q.arbitrary) <*> sums)
    , (1, pure (k, mempty, 0))
    ]

-- a sum small enough that batches of them don't overflow
small :: Q.Gen Word64
small = fromIntegral <$> (Q.arbitrary :: Q.Gen Word32)

-- a sum, often near maxBound
big :: Q.Gen Word64
big = Q.oneof [
    Q.arbitrary
  , (maxBound -) . fromIntegral <$> (Q.arbitrary :: Q.Gen Word32)
  ]

-- a key's raw bytes
raw_key :: Key -> BS.ByteString
raw_key (I.Key h) = I.serialize_hash h

-- key the model by raw bytes
raw :: M.Map Key a -> M.Map BS.ByteString a
raw = M.mapKeysMonotonic raw_key

-- path bit at the given depth; LSB-first within each byte
kbit :: Key -> Int -> Bool
kbit k d = testBit (BS.index (raw_key k) (d `quot` 8)) (d `rem` 8)

-- every branch holds two or more leaves, and every leaf's key follows
-- its path
compact :: I.Tree Void -> Bool
compact = isJust . go 0 [] where
  go :: Int -> [Bool] -> I.Tree Void -> Maybe Int
  go _ _ I.Empty = Just 0
  go d path (I.Leaf _ _ k _)
    | reverse path == fmap (kbit k) [0 .. d - 1] = Just 1
    | otherwise = Nothing
  go d path (I.Node l _ r) = do
    a <- go (d + 1) (False : path) l
    b <- go (d + 1) (True : path) r
    if a + b >= 2 then Just (a + b) else Nothing

-- whether a key's path ends at another key's leaf
at_leaf :: Key -> I.Tree Void -> Bool
at_leaf k = go 0 where
  go :: Int -> I.Tree Void -> Bool
  go d t = case t of
    I.Empty -> False
    I.Leaf _ _ k' _ -> k' /= k
    I.Node l _ r -> go (d + 1) (if kbit k d then r else l)

-- the internal tree underlying a split tree
build_raw :: [E] -> Maybe (I.Tree Void)
build_raw = build_with I.Split

build_with :: I.Scheme -> [E] -> Maybe (I.Tree Void)
build_with sc =
  foldM (\t (E k v s) -> I.complete (I.insert_with sc k v s t)) I.empty

-- a tree held entirely elsewhere: its root as a stub, and a store of its
-- nodes by commitment, each with its subtrees as stubs
held
  :: I.Tree Void
  -> (I.Tree I.Kind, M.Map (Hash, Word64) (I.Tree I.Kind))
held t0 = (stub t0, go t0 M.empty) where
  stub :: I.Tree Void -> I.Tree I.Kind
  stub t = case t of
    I.Empty -> I.Empty
    I.Leaf c _ _ _ -> I.Stub I.Single c
    I.Node _ c _ -> I.Stub I.Branch c
  go
    :: I.Tree Void -> M.Map (Hash, Word64) (I.Tree I.Kind)
    -> M.Map (Hash, Word64) (I.Tree I.Kind)
  go t m = case t of
    I.Empty -> m
    I.Leaf c lh k v -> M.insert (ckey c) (I.Leaf c lh k v) m
    I.Node l c r ->
      go l (go r (M.insert (ckey c) (I.Node (stub l) c (stub r)) m))

ckey :: Commitment -> (Hash, Word64)
ckey (Commitment h s) = (h, s)

-- load a stub's contents from a store
from_store
  :: M.Map (Hash, Word64) (I.Tree I.Kind) -> I.Kind -> Commitment
  -> Maybe (I.Tree I.Kind)
from_store m _ c = M.lookup (ckey c) m

with_tree :: Ops t p -> [E] -> (t -> Q.Property) -> Q.Property
with_tree o es f = case build o es of
  Nothing -> Q.counterexample "overflow" False
  Just t -> f t

properties :: (Eq t, Show t) => String -> Ops t p -> TestTree
properties name o@Ops {..} = testGroup ("properties (" <> name <> ")") [
    Q.testProperty "lookup agrees with a map model" $ \(Es _ es) ->
      with_tree o es $ \t ->
        Q.property $
          all (\(k, l) -> o_lookup k t == Just l) (M.toList (model es))

  , Q.testProperty "root sum is the sum of leaf sums" $ \(Es _ es) ->
      with_tree o es $ \t ->
        let Commitment _ s = o_root t
        in  toInteger s Q.=== sum (fmap (toInteger . snd) (model es))

  , Q.testProperty "root agrees with the reference" $ \(Es _ es) ->
      with_tree o es $ \t ->
        let Commitment h s = o_root t
        in  (serialize_hash h, s) Q.=== o_ref (raw (model es))

  , Q.testProperty "trees are independent of insertion history" $
      \(Es _ es) ->
        let canonical = [E k v s | (k, (v, s)) <- M.toList (model es)]
        in  build o es Q.=== build o canonical

  , Q.testProperty "delete k . insert k v s == delete k" $ \x@(Es _ es) ->
      Q.forAll (pick x) $ \k ->
        with_tree o es $ \t ->
          fmap (o_delete k) (o_insert k "v" 1 t) Q.=== Just (o_delete k t)

  , Q.testProperty "deleting every leaf yields the empty tree" $ \(Es _ es) ->
      with_tree o es $ \t ->
        foldr o_delete t (M.keys (model es)) Q.=== o_empty

  , Q.testProperty "inclusion proofs verify" $ \(Es _ es) ->
      with_tree o es $ \t ->
        Q.property $ all
          (\(k, (v, s)) -> o_verify k v s (o_prove k t) (o_root t))
          (M.toList (model es))

  , Q.testProperty "exclusion proofs verify" $ \x@(Es _ es) ->
      Q.forAll (pick x) $ \k ->
        M.notMember k (model es) Q.==>
          with_tree o es $ \t ->
            Q.classify (maybe False (at_leaf k) (build_raw es))
              "ends at another leaf" $
              o_verify k mempty 0 (o_prove k t) (o_root t)

  , Q.testProperty "proofs reject a wrong value or sum" $ \(Es _ es) ->
      with_tree o es $ \t ->
        let r = o_root t
        in  Q.property $ all
              (\(k, (v, s)) ->
                   not (o_verify k (v <> "x") s (o_prove k t) r)
                && not (o_verify k v (s + 1) (o_prove k t) r)
                && not (o_verify k mempty 0 (o_prove k t) r))
              (M.toList (model es))

  , Q.testProperty "insert_many agrees with successive inserts" $
      \x@(Es _ es) -> Q.forAll (gen_batch small x) $ \b ->
        with_tree o es $ \t ->
          o_insert_many b t
            Q.=== foldM (\u (k, v, s) -> o_insert k v s u) t b

  , Q.testProperty "insert_many fails iff the root sum would overflow" $
      \x@(Es _ es) -> Q.forAll (gen_batch (Q.oneof [small, big]) x) $ \b ->
        with_tree o es $ \t ->
          let apply m (k, v, s)
                | BS.null v && s == 0 = M.delete k m
                | otherwise = M.insert k (v, s) m
              final = foldl apply (model es) b
              fits = sum (fmap (toInteger . snd) final)
                  <= toInteger (maxBound :: Word64)
          in  Q.classify fits "fits" $ isJust (o_insert_many b t) Q.=== fits

  , Q.testProperty "insert fails iff the root sum would overflow" $
      \x@(Es _ es) -> Q.forAll (pick x) $ \k -> Q.forAll big $ \s ->
        with_tree o es $ \t ->
          let m    = model es
              rest = sum (fmap (toInteger . snd) (M.delete k m))
              fits = rest + toInteger s <= toInteger (maxBound :: Word64)
          in  Q.classify fits "fits" $ isJust (o_insert k "v" s t) Q.=== fits
  ]

-- split proofs, which run only as deep as their key's slot
split_proofs :: TestTree
split_proofs = testGroup "split proofs" [
    Q.testProperty "proofs end at their key's slot" $ \x@(Es _ es) ->
      Q.forAll (pick x) $ \k ->
        with_tree split_ops es $ \t ->
          let Proof nb ps = prove k t
              neighbor (Neighbor k' _ _) = raw_key k'
          in  (length ps, fmap neighbor nb)
                Q.=== R.slot (raw (model es)) (raw_key k)

  , Q.testProperty "a present key's own leaf proves nothing" $
      \(Es _ es) ->
        with_tree split_ops es $ \t ->
          Q.property $ all
            (\(k, (v, s)) ->
               let Proof _ ps = prove k t
                   own = Proof (Just (Neighbor k (I.hash_value v) s)) ps
               in     not (verify k mempty 0 own (root t))
                   && not (verify k v s own (root t)))
            (M.toList (model es))

  , Q.testProperty "exclusion proofs reject a forged neighbor" $
      \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
        with_tree split_ops es $ \t -> case prove k t of
          Proof (Just (Neighbor k' h s)) ps ->
            let r = root t
                with n = verify k mempty 0 (Proof (Just n) ps) r
            in  Q.property $
                     with (Neighbor k' h s)
                  && not (with (Neighbor k' h (s + 1)))
                  && not (with (Neighbor k h s))
          Proof Nothing _ -> Q.discard
  ]

-- operations on a tree held entirely elsewhere, loaded along the paths
-- they touch, agree with those on the tree itself; and report what they
-- need, where they find it held elsewhere
partial
  :: (Eq p, Show p)
  => String
  -> I.Scheme
  -> (Key -> I.Tree I.Kind -> Either (I.Missing I.Kind) p)
  -> (Key -> I.Tree Void -> p)
  -> TestTree
partial name sc pf pf' = testGroup ("partial trees (" <> name <> ")") [
    Q.testProperty "lookup" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
      with es $ \t (h, m) ->
        fmap (I.lookup k) (I.expand (from_store m) k h)
          Q.=== Just (Right (I.complete (I.lookup k t)))

  , Q.testProperty "prove" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
      with es $ \t (h, m) ->
        fmap (pf k) (I.expand (from_store m) k h) Q.=== Just (Right (pf' k t))

  , Q.testProperty "insert" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
      with es $ \t (h, m) ->
        let ins u = I.insert_with sc k "v" 1 u
        in  fmap (fmap (fmap root_of) . ins) (I.expand (from_store m) k h)
              Q.=== Just (Right (fmap root_of (I.complete (ins t))))

  , Q.testProperty "delete" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
      with es $ \t (h, m) ->
        let del u = I.delete_with sc k u
        in  fmap (fmap root_of . del) (I.expand (from_store m) k h)
              Q.=== Just (Right (root_of (I.complete (del t))))

  , Q.testProperty "insert_many" $ \x@(Es _ es) ->
      Q.forAll (gen_batch small x) $ \b ->
        with es $ \t (h, m) ->
          let ins u = I.insert_many_with sc b u
              loaded = foldM (\u (k, _, _) -> I.expand (from_store m) k u) h b
          in  fmap (fmap (fmap root_of) . ins) loaded
                Q.=== Just (Right (fmap root_of (I.complete (ins t))))

  , Q.testProperty "unloaded paths report what they need" $
      \x@(Es _ es) -> Q.forAll (pick x) $ \k ->
        with es $ \_ (h, _) -> case h of
          I.Stub p c ->
            let needed = Left (I.Missing p c)
            in      I.lookup k h Q.=== needed
              Q..&&. fmap (const ()) (pf k h) Q.=== needed
              Q..&&. fmap (const ()) (I.insert_with sc k "v" 1 h) Q.=== needed
              Q..&&. fmap (const ()) (I.delete_with sc k h) Q.=== needed
          _ -> Q.property True
  ]
  where
    root_of = I.root_with sc
    with es f = case build_with sc es of
      Nothing -> Q.counterexample "overflow" False
      Just t -> f t (held t)

-- the shape of the underlying tree, which doesn't depend on the scheme
structure :: TestTree
structure = testGroup "structure" [
    Q.testProperty "trees are compact" $ \(Es _ es) ->
      Q.forAll (Q.sublistOf (M.keys (model es))) $ \ks ->
        case build_raw es of
          Nothing -> Q.counterexample "overflow" False
          Just t ->
            let del k u = I.complete (I.delete_with I.Split k u)
            in  compact t Q..&&. compact (foldr del t ks)
  ]