packages feed

mssmt-0.1.0: test/Vectors.hs

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

-- Test vectors from taproot-assets (mssmt/testdata).

module Vectors (
    Vectors
  , execute
  ) where

import Control.Monad (foldM, forM_, guard)
import Data.Aeson ((.:), (.:?))
import qualified Data.Aeson as A
import qualified Data.Aeson.Key as AK
import qualified Data.Aeson.Types as AT
import Data.Bits (shiftL, testBit, (.|.))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe, isJust, isNothing)
import Data.MSSMT.Aggregate
import qualified Data.Set as S
import Data.Word (Word64)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit

data Leaf = Leaf !Key !BS.ByteString !Word64

data Valid = Valid {
    v_root     :: !Commitment
  , v_inserted :: ![Key]
  , v_deleted  :: ![Key]
  , v_replaced :: ![Leaf]
  , v_included :: ![(Key, Proof)]
  , v_excluded :: ![(Key, Proof)]
  , v_comment  :: !String
  }

data Invalid = Invalid {
    i_inserted :: ![Key]
  , i_comment  :: !String
  }

-- | A file of test vectors.
data Vectors = Vectors {
    vs_leaves  :: ![Leaf]
  , vs_valid   :: ![Valid]
  , vs_invalid :: ![Invalid]
  }

-- execution ------------------------------------------------------------------

-- | Run a file's test cases.
execute :: String -> Vectors -> TestTree
execute name Vectors {..} = testGroup name $
     fmap (execute_valid vs_leaves) vs_valid
  <> fmap (execute_invalid vs_leaves) vs_invalid

-- leaves are inserted in file order, as in the taproot-assets runner
inserting :: [Leaf] -> [Key] -> [Leaf]
inserting ls ks = filter (\(Leaf k _ _) -> S.member k set) ls where
  set = S.fromList ks

insert_all :: Tree -> [Leaf] -> Maybe Tree
insert_all = foldM (\t (Leaf k v s) -> insert k v s t)

execute_valid :: [Leaf] -> Valid -> TestTree
execute_valid ls Valid {..} = testGroup v_comment [
      testCase "root" $
        assertEqual mempty (Just v_root) (fmap root tree)
    , testCase ("inclusion proofs (" <> show (length v_included) <> ")") $
        forM_ (zip [0 :: Int ..] v_included) $ \(i, (k, p)) ->
          case (tree, M.lookup k leaves) of
            (Just t, Just (Leaf _ v s)) -> do
              assertEqual ("prove " <> show i) p (prove k t)
              assertBool ("verify " <> show i) (verify k v s p (root t))
            _ -> assertFailure ("missing tree or leaf " <> show i)
    , testCase ("exclusion proofs (" <> show (length v_excluded) <> ")") $
        forM_ (zip [0 :: Int ..] v_excluded) $ \(i, (k, p)) ->
          case tree of
            Just t -> do
              assertEqual ("prove " <> show i) p (prove k t)
              assertBool ("verify " <> show i) (verify k mempty 0 p (root t))
            Nothing -> assertFailure "missing tree"
    ]
  where
    leaves = M.fromList [(k, l) | l@(Leaf k _ _) <- ls]
    tree = do
      t <- insert_all empty (inserting ls v_inserted)
      insert_all (foldr delete t v_deleted) v_replaced

-- every insert but the last succeeds; the last overflows
execute_invalid :: [Leaf] -> Invalid -> TestTree
execute_invalid ls Invalid {..} = testCase i_comment $ do
  let leaves = inserting ls i_inserted
  assertBool "no leaves" (not (null leaves))
  assertBool "prefix" $
    isJust (insert_all empty (take (length leaves - 1) leaves))
  assertBool "overflow" $
    isNothing (insert_all empty leaves)

-- parsing --------------------------------------------------------------------

instance A.FromJSON Vectors where
  parseJSON = A.withObject "Vectors" $ \o -> Vectors
    <$> o .: "all_tree_leaves"
    <*> list o "valid_test_cases"
    <*> list o "error_test_cases"

instance A.FromJSON Leaf where
  parseJSON = A.withObject "Leaf" $ \o -> do
    n <- o .: "node"
    Leaf
      <$> (o .: "key" >>= parse_key)
      <*> (n .: "value" >>= parse_hex)
      <*> (n .: "sum" >>= parse_sum)

instance A.FromJSON Valid where
  parseJSON = A.withObject "Valid" $ \o -> do
    h <- o .: "root_hash" >>= parse_hex >>= parse_digest
    s <- o .: "root_sum" >>= parse_sum
    Valid (Commitment h s)
      <$> (list o "inserted_leaves" >>= traverse parse_key)
      <*> (list o "deleted_leaves" >>= traverse parse_key)
      <*> list o "replaced_leaves"
      <*> (list o "inclusion_proofs" >>= traverse parse_case)
      <*> (list o "exclusion_proofs" >>= traverse parse_case)
      <*> o .: "comment"

instance A.FromJSON Invalid where
  parseJSON = A.withObject "Invalid" $ \o -> Invalid
    <$> (list o "inserted_leaves" >>= traverse parse_key)
    <*> o .: "comment"

-- absent and null lists are empty
list :: A.FromJSON a => A.Object -> AK.Key -> AT.Parser [a]
list o k = fromMaybe [] <$> o .:? k

parse_case :: A.Value -> AT.Parser (Key, Proof)
parse_case = A.withObject "ProofCase" $ \o -> (,)
  <$> (o .: "proof_key" >>= parse_key)
  <*> (o .: "compressed_proof" >>= parse_hex >>= parse_proof)

parse_hex :: String -> AT.Parser BS.ByteString
parse_hex s = maybe (fail ("bad hex: " <> s)) pure (B16.decode (B8.pack s))

parse_digest :: BS.ByteString -> AT.Parser Hash
parse_digest bs = maybe (fail "bad hash") pure (parse_hash bs)

parse_key :: String -> AT.Parser Key
parse_key s = parse_hex s >>= maybe (fail ("bad key: " <> s)) pure . key

parse_sum :: String -> AT.Parser Word64
parse_sum s = case reads s :: [(Integer, String)] of
  [(n, "")] | n >= 0 && n <= toInteger (maxBound :: Word64) ->
    pure (fromInteger n)
  _ -> fail ("bad sum: " <> s)

parse_proof :: BS.ByteString -> AT.Parser Proof
parse_proof = maybe (fail "bad compressed proof") pure . decompress

-- compressed proofs ----------------------------------------------------------

-- a compressed proof is a big-endian uint16 count n, then n siblings
-- as (32-byte hash, big-endian uint64 sum), then a 256-bit vector
-- (LSB-first per byte) marking which siblings are empty subtrees
decompress :: BS.ByteString -> Maybe Proof
decompress bs0 = do
    let (c, bs1) = BS.splitAt 2 bs0
    guard (BS.length c == 2)
    (nodes, bs2) <- siblings (fromIntegral (be c)) bs1
    guard (BS.length bs2 == 32)
    let bits = concatMap (\w -> fmap (testBit w) [0 .. 7]) (BS.unpack bs2)
    es <- empties
    Proof <$> fill bits nodes es
  where
    -- aggregate empty-subtree commitments, leaf up: the siblings of any
    -- key in the empty tree
    empties = do
      k <- key (BS.replicate 32 0)
      let Proof es = prove k empty
      pure es

    siblings :: Int -> BS.ByteString -> Maybe ([Commitment], BS.ByteString)
    siblings 0 bs = Just ([], bs)
    siblings n bs
      | BS.length bs < 40 = Nothing
      | otherwise = do
          let (h, rest0) = BS.splitAt 32 bs
              (s, rest1) = BS.splitAt 8 rest0
          d <- parse_hash h
          (ps, rest) <- siblings (n - 1) rest1
          pure (Commitment d (be s) : ps, rest)

    fill (b:bs) ns (e:es)
      | b = (e :) <$> fill bs ns es
      | otherwise = case ns of
          (n:rest) -> (n :) <$> fill bs rest es
          [] -> Nothing
    fill [] [] [] = Just []
    fill _ _ _ = Nothing

be :: BS.ByteString -> Word64
be = BS.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) 0