packages feed

secp256k1-haskell-3.1.0: test/Crypto/Secp256k1/EllSwiftSpec.hs

{-# LANGUAGE CPP #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

-- | ElligatorSwift and the Diffie-Hellman exchange of BIP 324. The module
-- under test only exists when the @ellswift@ flag of the package is on, so
-- the whole specification is behind the same flag. This module avoids string
-- gaps, because CPP would join their lines.
--
-- The vectors are the files of BIP 324, copied unchanged into @test/data@
-- from <https://github.com/bitcoin/bips/tree/master/bip-0324> at commit
-- 8455d73ddfd763c1057e176d4919b0b061c786f6.
module Crypto.Secp256k1.EllSwiftSpec (spec) where

import Test.Hspec

#ifdef ELLSWIFT

import Control.Exception (evaluate)
import Control.Monad (forM_, unless)
import Crypto.Secp256k1
import Crypto.Secp256k1.EllSwift
import Crypto.Secp256k1.Internal.EllSwift (EllSwift (EllSwift))
import Crypto.Secp256k1.Internal.Util (decodeHex)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as C
import Data.Maybe (fromJust, isNothing)
import Data.String (fromString)
import Test.QuickCheck
import Text.Read (readMaybe)

spec :: Spec
spec = describe "ElligatorSwift" $ do
  vectorSpec
  propertySpec
  valueSpec

-- * The files of BIP 324

-- | The rows of a CSV file of the BIP, each as a list of fields by name. The
-- files have no quoted fields.
readCsv :: FilePath -> IO [[(ByteString, ByteString)]]
readCsv path = do
  ls <- filter (not . BS.null) . C.lines . C.filter (/= '\r') <$> BS.readFile path
  case ls of
    [] -> fail ("empty file " <> path)
    hdr : rows -> return [zip (C.split ',' hdr) (C.split ',' r) | r <- rows]

field :: ByteString -> [(ByteString, ByteString)] -> ByteString
field name row = maybe (error ("no field " <> C.unpack name)) id (lookup name row)

hexField :: ByteString -> [(ByteString, ByteString)] -> ByteString
hexField name = fromJust . decodeHex . field name

-- | The x coordinate of a public key, from its compressed encoding.
xOf :: PubKey -> ByteString
xOf = BS.drop 1 . exportPubKey True

vectorSpec :: Spec
vectorSpec = describe "vectors of BIP 324" $ do
  it "decodes the 76 encodings of ellswift_decode_test_vectors.csv" $ do
    rows <- readCsv "test/data/ellswift_decode_test_vectors.csv"
    length rows `shouldBe` 76
    forM_ rows $ \row -> do
      let ell = fromJust (ellSwift (hexField "ellswift" row))
      (field "comment" row, xOf (ellSwiftDecode ell))
        `shouldBe` (field "comment" row, hexField "x" row)
  -- libsecp256k1 does not expose the inverse map xswiftec_inv, so which of
  -- the eight cases gives which t, and that the empty cases have none,
  -- cannot be checked through it. Every t that the file gives is checked
  -- the other way: u and t decode to the point of x.
  it "decodes u and each of the 98 values of t of xswiftec_inv_test_vectors.csv to x" $ do
    rows <- readCsv "test/data/xswiftec_inv_test_vectors.csv"
    length rows `shouldBe` 32
    let pairs =
          [ (hexField "u" row <> t, hexField "x" row)
          | row <- rows,
            c <- [0 .. 7 :: Int],
            let name = "case" <> C.pack (show c) <> "_t",
            not (BS.null (field name row)),
            let t = hexField name row
          ]
    length pairs `shouldBe` 98
    forM_ pairs $ \(ell, x) -> xOf (ellSwiftDecode (fromJust (ellSwift ell))) `shouldBe` x
  it "computes the keys and secrets of the 7 rows of packet_encoding_test_vectors.csv" $ do
    rows <- readCsv "test/data/packet_encoding_test_vectors.csv"
    length rows `shouldBe` 7
    forM_ rows $ \row -> do
      let priv = fromJust (secKey (hexField "in_priv_ours" row))
          ours = fromJust (ellSwift (hexField "in_ellswift_ours" row))
          theirs = fromJust (ellSwift (hexField "in_ellswift_theirs" row))
          initiating = field "in_initiating" row == "1"
          shared
            | initiating = ellSwiftXdhBip324 ours theirs priv PartyA
            | otherwise = ellSwiftXdhBip324 theirs ours priv PartyB
          point = fromJust (tweakMulPubKey (ellSwiftDecode theirs) (fromJust (tweak priv.get)))
      xOf (derivePubKey priv) `shouldBe` hexField "mid_x_ours" row
      xOf (ellSwiftDecode ours) `shouldBe` hexField "mid_x_ours" row
      xOf (ellSwiftDecode theirs) `shouldBe` hexField "mid_x_theirs" row
      xOf point `shouldBe` hexField "mid_x_shared" row
      shared `shouldBe` hexField "mid_shared_secret" row

propertySpec :: Spec
propertySpec = describe "properties" $ do
  it "decodes the encoding of a secret key to its public key (key_ellswift of Bitcoin Core)" $
    property $ \key aux -> do
      let ell = fromJust (ellSwiftCreate key (Just (bytes32 aux)))
      ellSwiftDecode ell `shouldBe` derivePubKey key
  it "decodes the encoding of a secret key made without randomness" $
    property $ \key ->
      ellSwiftDecode (fromJust (ellSwiftCreate key Nothing)) `shouldBe` derivePubKey key
  it "decodes an encoded public key to the same key" $
    property $ \key rnd -> do
      let pub = derivePubKey key
      ellSwiftDecode (fromJust (ellSwiftEncode pub (bytes32 rnd))) `shouldBe` pub
  it "gives both parties the same secret, and another secret to a third key" $
    property $ \a b c auxA auxB -> do
      let ellA = fromJust (ellSwiftCreate a (Just (bytes32 auxA)))
          ellB = fromJust (ellSwiftCreate b (Just (bytes32 auxB)))
          secretA = ellSwiftXdhBip324 ellA ellB a PartyA
          secretB = ellSwiftXdhBip324 ellA ellB b PartyB
      secretA `shouldBe` secretB
      BS.length secretA `shouldBe` 32
      unless (c == a) $ ellSwiftXdhBip324 ellA ellB c PartyA `shouldNotBe` secretA
  it "gives another secret when the parties swap their roles" $
    property $ \a b -> do
      let ellA = fromJust (ellSwiftCreate a Nothing)
          ellB = fromJust (ellSwiftCreate b Nothing)
      ellSwiftXdhBip324 ellB ellA a PartyB `shouldNotBe` ellSwiftXdhBip324 ellA ellB a PartyA
  it "decodes any 64 bytes" $
    property $ \(Bytes64 bs) ->
      BS.length (exportPubKey True (ellSwiftDecode (fromJust (ellSwift bs)))) `shouldBe` 33

valueSpec :: Spec
valueSpec = describe "values" $ do
  it "refuses an encoding of another length than 64 bytes" $
    forM_ [0, 1, 32, 63, 65, 128] $ \n ->
      ellSwift (BS.replicate n 0) `shouldSatisfy` isNothing
  it "refuses randomness of another length than 32 bytes" $ do
    let key = fromJust (secKey (BS.replicate 31 0 <> "\1"))
    forM_ [0, 16, 31, 33] $ \n -> do
      ellSwiftCreate key (Just (BS.replicate n 0)) `shouldSatisfy` isNothing
      ellSwiftEncode (derivePubKey key) (BS.replicate n 0) `shouldSatisfy` isNothing
  it "makes a fresh encoding each time with ellSwiftCreateIO" $ do
    let key = fromJust (secKey (BS.replicate 31 0 <> "\2"))
    e1 <- ellSwiftCreateIO key
    e2 <- ellSwiftCreateIO key
    e1 `shouldNotBe` e2
    ellSwiftDecode e1 `shouldBe` ellSwiftDecode e2
  it "shows, reads and parses hex" $
    property $ \(Bytes64 bs) -> do
      let e = EllSwift bs
      readMaybe (show e) `shouldBe` Just e
      fromString (read (show e)) `shouldBe` e
      e.get `shouldBe` bs
  it "raises an error for a raw encoding of the wrong length" $
    evaluate (ellSwiftDecode (EllSwift "short")) `shouldThrow` anyErrorCall

-- | 32 bytes from a list of arbitrary bytes, padded or cut.
bytes32 :: [Word] -> ByteString
bytes32 ws = BS.pack (take 32 (map fromIntegral ws ++ repeat 0))

-- | 64 arbitrary bytes.
newtype Bytes64 = Bytes64 ByteString
  deriving (Show)

instance Arbitrary Bytes64 where
  arbitrary = Bytes64 . BS.pack <$> vectorOf 64 arbitrary

#else

spec :: Spec
spec = describe "ElligatorSwift" $
  it "is not built: the ellswift flag is off" (pendingWith "flag ellswift off")

#endif