packages feed

secp256k1-haskell-3.1.1: src/Crypto/Secp256k1/Internal/EllSwift.hs

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE NoFieldSelectors #-}

-- | Internal module. Everything is exported, including the raw v'EllSwift'
-- constructor that "Crypto.Secp256k1.EllSwift" hides, and there is no API
-- stability guarantee. This module is only built when the @ellswift@ flag of
-- the package is on.
--
-- Every 64 bytes are the encoding of some point, so the only thing the raw
-- constructor can get wrong is the length. Every function here checks it
-- before calling the C library and raises an 'Control.Exception.ErrorCall'
-- when it is wrong.
--
-- As in "Crypto.Secp256k1.Internal.Base", every function uses the global
-- context of the package and none takes one.
module Crypto.Secp256k1.Internal.EllSwift where

import Control.DeepSeq (NFData)
import Control.Exception (evaluate)
import Control.Monad.IO.Class (MonadIO (..))
import Crypto.Secp256k1.Internal.Base (PubKey (..), SecKey (..))
import Crypto.Secp256k1.Internal.Context (globalContext)
import Crypto.Secp256k1.Internal.EllSwiftOps qualified as Ops
import Crypto.Secp256k1.Internal.ForeignTypes (isSuccess)
import Crypto.Secp256k1.Internal.Util
  ( decodeHex,
    showsHex,
    useFixedByteString,
    withOutput,
  )
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Hashable (Hashable)
import Data.Maybe (fromMaybe)
import Data.String (IsString (..))
import Foreign (castPtr, nullPtr, peek)
import GHC.Generics (Generic)
import System.Entropy (getEntropy)
import System.IO.Unsafe (unsafePerformIO)
import Text.Read
  ( Lexeme (String),
    lexP,
    parens,
    pfail,
    readPrec,
  )

-- | ElligatorSwift encoding of a public key: 64 bytes, two field elements u
-- and t as 32-byte big-endian numbers. Unlike the @get@ field of a t'PubKey',
-- these bytes are a standard encoding, the same on every platform, and they
-- are what BIP 324 sends on the wire.
--
-- Any 64 bytes are a valid encoding: each decodes to a point of the curve,
-- including values of u or t at or above the field size, which are taken
-- modulo p. A point has many encodings, chosen at random when it is encoded,
-- so 'Eq' compares encodings, not points.
--
-- 'Show', 'Read' and 'IsString' use hex.
newtype EllSwift = EllSwift {get :: ByteString}
  deriving (Eq, Ord, Generic, Hashable, NFData)

instance Read EllSwift where
  readPrec = parens $ do
    String str <- lexP
    maybe pfail return $ ellSwift =<< decodeHex str

instance IsString EllSwift where
  fromString = fromMaybe e . (ellSwift =<<) . decodeHex
    where
      e = error "Could not decode ElligatorSwift encoding from hex string"

instance Show EllSwift where
  showsPrec _ (EllSwift bs) = showsHex bs

-- | Which side of an x-only Diffie-Hellman exchange a party is. The two
-- encodings are hashed in the order A then B, so both sides must agree on
-- who is who. In BIP 324 the initiator of the connection is A and the
-- responder is B.
data Party = PartyA | PartyB
  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)

instance NFData Party

-- | An encoding from its 64 bytes. 'Nothing' only for another length: every
-- 64 bytes encode a point.
ellSwift :: ByteString -> Maybe EllSwift
ellSwift bs
  | BS.length bs == 64 = Just (EllSwift bs)
  | otherwise = Nothing

-- | Encode a public key with 32 bytes of randomness. 'Nothing' unless the
-- randomness is 32 bytes long.
--
-- The randomness picks one of the many encodings of the point. It should be
-- uniformly random and unknown to anyone who tries to tell the encoding from
-- random bytes, and it must not be a function of the public key alone. The
-- encoding of a given key and randomness may change between versions of
-- libsecp256k1. Runs in variable time, which is harmless for a public key.
-- Prefer 'ellSwiftCreate' when the secret key is at hand.
ellSwiftEncode :: PubKey -> ByteString -> Maybe EllSwift
ellSwiftEncode (PubKey pub_key) rnd
  | BS.length rnd /= 32 = Nothing
  | otherwise =
      Just . unsafePerformIO $
        useFixedByteString "PubKey" 64 pub_key $ \(pub_key_ptr, _) ->
          useFixedByteString "randomness" 32 rnd $ \(rnd_ptr, _) -> do
            out <- withOutput 64 $ \ell_ptr ->
              isSuccess <$> Ops.ellSwiftEncode globalContext ell_ptr pub_key_ptr rnd_ptr
            -- libsecp256k1 documents that this function always succeeds.
            maybe (error "could not encode public key") (return . EllSwift) out

-- | The public key of a secret key, encoded with ElligatorSwift. The secret
-- key itself is a source of randomness for the choice of the encoding, and
-- the optional 32 bytes of auxiliary randomness add to it, as
-- @EllSwiftCreate@ does in Bitcoin Core. 'Nothing' when the auxiliary
-- randomness is given and is not 32 bytes long.
--
-- Without auxiliary randomness the encoding is a function of the secret key,
-- and still looks uniformly random to anyone who does not know the key. BIP
-- 324 recommends fresh randomness: see 'ellSwiftCreateIO'. Constant time in
-- the secret key and the randomness, but not in the resulting public key.
ellSwiftCreate :: SecKey -> Maybe ByteString -> Maybe EllSwift
ellSwiftCreate (SecKey sec_key) aux = case aux of
  Just a | BS.length a /= 32 -> Nothing
  _ ->
    Just . unsafePerformIO $
      useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) ->
        withAux $ \aux_ptr -> do
          out <- withOutput 64 $ \ell_ptr ->
            isSuccess <$> Ops.ellSwiftCreate globalContext ell_ptr sec_key_ptr aux_ptr
          -- It fails only for a secret key out of range, which a t'SecKey' is
          -- not.
          maybe (error "could not create ElligatorSwift public key") (return . EllSwift) out
  where
    withAux f = case aux of
      Nothing -> f nullPtr
      Just a -> useFixedByteString "auxiliary randomness" 32 a $ f . castPtr . fst

-- | 'ellSwiftCreate' with 32 bytes of fresh auxiliary randomness from the
-- operating system, as Bitcoin Core does for every connection.
ellSwiftCreateIO :: (MonadIO m) => SecKey -> m EllSwift
ellSwiftCreateIO key = liftIO $ do
  aux <- getEntropy 32
  evaluate . fromMaybe (error "getEntropy gave the wrong length") $ ellSwiftCreate key (Just aux)

-- | The public key that an encoding stands for. Every encoding decodes to a
-- point, so this is total. The y coordinate of the point has the parity of
-- t. Runs in variable time.
ellSwiftDecode :: EllSwift -> PubKey
ellSwiftDecode (EllSwift ell) =
  unsafePerformIO $
    useFixedByteString "EllSwift" 64 ell $ \(ell_ptr, _) -> do
      out <- withOutput 64 $ \pub_key_ptr ->
        isSuccess <$> Ops.ellSwiftDecode globalContext pub_key_ptr ell_ptr
      -- libsecp256k1 documents that this function always succeeds.
      maybe (error "could not decode ElligatorSwift encoding") (return . PubKey) out

-- | The shared secret of BIP 324: x-only Diffie-Hellman between our secret key
-- and the other party's encoded public key, hashed with the tagged hash
-- @bip324_ellswift_xonly_ecdh@ of the encoding of A, the encoding of B and the
-- shared x coordinate. The first two arguments are the encodings of A and B,
-- in that order; the secret key is that of the party named by the last
-- argument, whose encoding must be the one that comes from that key. That
-- correspondence is not checked: a wrong one gives a secret that the other
-- side does not share.
--
-- This is @CKey::ComputeBIP324ECDHSecret@ of Bitcoin Core, which passes the
-- initiator as A. It is faster than decoding the other key and doing the
-- Diffie-Hellman exchange by hand, and constant time in the secret key.
ellSwiftXdhBip324 :: EllSwift -> EllSwift -> SecKey -> Party -> ByteString
ellSwiftXdhBip324 (EllSwift ell_a) (EllSwift ell_b) (SecKey sec_key) party =
  unsafePerformIO $
    useFixedByteString "EllSwift" 64 ell_a $ \(a_ptr, _) ->
      useFixedByteString "EllSwift" 64 ell_b $ \(b_ptr, _) ->
        useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) -> do
          hash_fun <- peek Ops.ellSwiftXdhHashFunctionBip324
          out <- withOutput 32 $ \out_ptr ->
            isSuccess
              <$> Ops.ellSwiftXdh globalContext out_ptr a_ptr b_ptr sec_key_ptr side hash_fun nullPtr
          -- It fails only for a secret key out of range, or when the hash
          -- function fails, which the BIP 324 one never does.
          maybe (error "could not compute ElligatorSwift shared secret") return out
  where
    side = case party of
      PartyA -> 0
      PartyB -> 1