packages feed

secp256k1-haskell 2.0.1 → 3.0.0

raw patch · 16 files changed

+1239/−999 lines, 16 filesdep −secp256k1-haskellsetup-changedPVP ok

version bump matches the API change (PVP)

Dependencies removed: secp256k1-haskell

API changes (from Hackage documentation)

- Crypto.Secp256k1: cloneContext :: Ctx -> IO Ctx
- Crypto.Secp256k1: createContext :: IO Ctx
- Crypto.Secp256k1: data Ctx
- Crypto.Secp256k1: randomizeContext :: Ctx -> IO ()
- Crypto.Secp256k1: withContext :: (Ctx -> IO a) -> IO a
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeyCombine :: Ptr LCtx -> Ptr PubKey64 -> Ptr (Ptr PubKey64) -> CSize -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeyCreate :: Ptr LCtx -> Ptr PubKey64 -> Ptr SecKey32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeyParse :: Ptr LCtx -> Ptr PubKey64 -> Ptr CUChar -> CSize -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeySerialize :: Ptr LCtx -> Ptr CUChar -> Ptr CSize -> Ptr PubKey64 -> SerFlags -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeyTweakAdd :: Ptr LCtx -> Ptr PubKey64 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecPubKeyTweakMul :: Ptr LCtx -> Ptr PubKey64 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecSecKeyTweakAdd :: Ptr LCtx -> Ptr SecKey32 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecSecKeyTweakMul :: Ptr LCtx -> Ptr SecKey32 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecSecKeyVerify :: Ptr LCtx -> Ptr SecKey32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecTweakNegate :: Ptr LCtx -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSign :: Ptr LCtx -> Ptr Sig64 -> Ptr Msg32 -> Ptr SecKey32 -> FunPtr (NonceFun a) -> Ptr a -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSignatureNormalize :: Ptr LCtx -> Ptr Sig64 -> Ptr Sig64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSignatureParseCompact :: Ptr LCtx -> Ptr Sig64 -> Ptr Compact64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSignatureParseDer :: Ptr LCtx -> Ptr Sig64 -> Ptr CUChar -> CSize -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSignatureSerializeCompact :: Ptr LCtx -> Ptr Compact64 -> Ptr Sig64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaSignatureSerializeDer :: Ptr LCtx -> Ptr CUChar -> Ptr CSize -> Ptr Sig64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: ecdsaVerify :: Ptr LCtx -> Ptr Sig64 -> Ptr Msg32 -> Ptr PubKey64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: keyPairCreate :: Ptr LCtx -> Ptr KeyPair96 -> Ptr SecKey32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: keyPairSec :: Ptr LCtx -> Ptr SecKey32 -> Ptr KeyPair96 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: keyPairXOnlyPub :: Ptr LCtx -> Ptr XOnlyPubKey64 -> Ptr CInt -> Ptr KeyPair96 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: keyPairXOnlyTweakAdd :: Ptr LCtx -> Ptr KeyPair96 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: schnorrSigSign32 :: Ptr LCtx -> Ptr SchnorrSig64 -> Ptr Msg32 -> Ptr KeyPair96 -> Ptr AuxRand32 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: schnorrSigVerify :: Ptr LCtx -> Ptr SchnorrSig64 -> Ptr CUChar -> CSize -> Ptr XOnlyPubKey64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: xOnlyPubKeyFromPubKey :: Ptr LCtx -> Ptr XOnlyPubKey64 -> Ptr CInt -> Ptr PubKey64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: xOnlyPubKeySerialize :: Ptr LCtx -> Ptr CUChar -> Ptr XOnlyPubKey64 -> IO Ret
- Crypto.Secp256k1.Internal.BaseOps: xOnlyPubKeyTweakAdd :: Ptr LCtx -> Ptr PubKey64 -> Ptr XOnlyPubKey64 -> Ptr Tweak32 -> IO Ret
- Crypto.Secp256k1.Internal.Context: Ctx :: ForeignPtr LCtx -> Ctx
- Crypto.Secp256k1.Internal.Context: cloneContext :: Ctx -> IO Ctx
- Crypto.Secp256k1.Internal.Context: contextClone :: Ptr LCtx -> IO (Ptr LCtx)
- Crypto.Secp256k1.Internal.Context: contextCreate :: CtxFlags -> IO (Ptr LCtx)
- Crypto.Secp256k1.Internal.Context: contextDestroy :: Ptr LCtx -> IO ()
- Crypto.Secp256k1.Internal.Context: contextDestroyFunPtr :: FunPtr (Ptr LCtx -> IO ())
- Crypto.Secp256k1.Internal.Context: contextRandomize :: Ptr LCtx -> Ptr Seed32 -> IO Ret
- Crypto.Secp256k1.Internal.Context: createContext :: IO Ctx
- Crypto.Secp256k1.Internal.Context: data Ctx
- Crypto.Secp256k1.Internal.Context: illegalCallbackFunPtr :: FunPtr (CString -> Ptr a -> IO ())
- Crypto.Secp256k1.Internal.Context: none :: CtxFlags
- Crypto.Secp256k1.Internal.Context: randomizeContext :: Ctx -> IO ()
- Crypto.Secp256k1.Internal.Context: setErrorCallback :: Ptr LCtx -> FunPtr (CString -> Ptr a -> IO ()) -> Ptr a -> IO ()
- Crypto.Secp256k1.Internal.Context: setIllegalCallback :: Ptr LCtx -> FunPtr (CString -> Ptr a -> IO ()) -> Ptr a -> IO ()
- Crypto.Secp256k1.Internal.Context: sign :: CtxFlags
- Crypto.Secp256k1.Internal.Context: signVerify :: CtxFlags
- Crypto.Secp256k1.Internal.Context: validationContext :: Ctx
- Crypto.Secp256k1.Internal.Context: verify :: CtxFlags
- Crypto.Secp256k1.Internal.Context: withContext :: (Ctx -> IO a) -> IO a
- Crypto.Secp256k1.Internal.Context: wrapContext :: Ptr LCtx -> IO Ctx
- Crypto.Secp256k1.Internal.ForeignTypes: data LCtx
- Crypto.Secp256k1.Internal.ForeignTypes: type CtxFlags = CUInt
- Crypto.Secp256k1.Internal.RecoveryOps: ecdsaRecover :: Ptr LCtx -> Ptr PubKey64 -> Ptr RecSig65 -> Ptr Msg32 -> IO Ret
- Crypto.Secp256k1.Internal.RecoveryOps: ecdsaRecoverableSignatureConvert :: Ptr LCtx -> Ptr Sig64 -> Ptr RecSig65 -> IO Ret
- Crypto.Secp256k1.Internal.RecoveryOps: ecdsaRecoverableSignatureParseCompact :: Ptr LCtx -> Ptr RecSig65 -> Ptr Compact64 -> CInt -> IO Ret
- Crypto.Secp256k1.Internal.RecoveryOps: ecdsaRecoverableSignatureSerializeCompact :: Ptr LCtx -> Ptr Compact64 -> Ptr CInt -> Ptr RecSig65 -> IO Ret
- Crypto.Secp256k1.Internal.RecoveryOps: ecdsaSignRecoverable :: Ptr LCtx -> Ptr RecSig65 -> Ptr Msg32 -> Ptr SecKey32 -> FunPtr (NonceFun a) -> Ptr a -> IO Ret
- Crypto.Secp256k1: combinePubKeys :: Ctx -> [PubKey] -> Maybe PubKey
+ Crypto.Secp256k1: combinePubKeys :: [PubKey] -> Maybe PubKey
- Crypto.Secp256k1: derivePubKey :: Ctx -> SecKey -> PubKey
+ Crypto.Secp256k1: derivePubKey :: SecKey -> PubKey
- Crypto.Secp256k1: exportCompactSig :: Ctx -> Sig -> CompactSig
+ Crypto.Secp256k1: exportCompactSig :: Sig -> CompactSig
- Crypto.Secp256k1: exportPubKey :: Ctx -> Bool -> PubKey -> ByteString
+ Crypto.Secp256k1: exportPubKey :: Bool -> PubKey -> ByteString
- Crypto.Secp256k1: exportSig :: Ctx -> Sig -> ByteString
+ Crypto.Secp256k1: exportSig :: Sig -> ByteString
- Crypto.Secp256k1: exportXOnlyPubKey :: Ctx -> PubKey -> ByteString
+ Crypto.Secp256k1: exportXOnlyPubKey :: PubKey -> ByteString
- Crypto.Secp256k1: importCompactSig :: Ctx -> CompactSig -> Maybe Sig
+ Crypto.Secp256k1: importCompactSig :: CompactSig -> Maybe Sig
- Crypto.Secp256k1: importPubKey :: Ctx -> ByteString -> Maybe PubKey
+ Crypto.Secp256k1: importPubKey :: ByteString -> Maybe PubKey
- Crypto.Secp256k1: importSig :: Ctx -> ByteString -> Maybe Sig
+ Crypto.Secp256k1: importSig :: ByteString -> Maybe Sig
- Crypto.Secp256k1: importXOnlyPubKey :: Ctx -> ByteString -> Maybe PubKey
+ Crypto.Secp256k1: importXOnlyPubKey :: ByteString -> Maybe PubKey
- Crypto.Secp256k1: isLowR :: Ctx -> Sig -> Bool
+ Crypto.Secp256k1: isLowR :: Sig -> Bool
- Crypto.Secp256k1: isLowS :: Ctx -> Sig -> Bool
+ Crypto.Secp256k1: isLowS :: Sig -> Bool
- Crypto.Secp256k1: normalizeSig :: Ctx -> Sig -> Sig
+ Crypto.Secp256k1: normalizeSig :: Sig -> Sig
- Crypto.Secp256k1: signMsg :: Ctx -> SecKey -> Msg -> Sig
+ Crypto.Secp256k1: signMsg :: SecKey -> Msg -> Sig
- Crypto.Secp256k1: signMsgLowR :: Ctx -> SecKey -> Msg -> Sig
+ Crypto.Secp256k1: signMsgLowR :: SecKey -> Msg -> Sig
- Crypto.Secp256k1: signSchnorr :: Ctx -> SecKey -> Msg -> SchnorrSig
+ Crypto.Secp256k1: signSchnorr :: SecKey -> Msg -> SchnorrSig
- Crypto.Secp256k1: signSchnorrIO :: MonadIO m => Ctx -> SecKey -> Msg -> m SchnorrSig
+ Crypto.Secp256k1: signSchnorrIO :: MonadIO m => SecKey -> Msg -> m SchnorrSig
- Crypto.Secp256k1: signSchnorrWithAux :: Ctx -> SecKey -> Msg -> ByteString -> Maybe SchnorrSig
+ Crypto.Secp256k1: signSchnorrWithAux :: SecKey -> Msg -> ByteString -> Maybe SchnorrSig
- Crypto.Secp256k1: tweakAddPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1: tweakAddPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1: tweakAddSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1: tweakAddSecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1: tweakAddXOnlyPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1: tweakAddXOnlyPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1: tweakAddXOnlySecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1: tweakAddXOnlySecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1: tweakMulPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1: tweakMulPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1: tweakMulSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1: tweakMulSecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1: tweakNegate :: Ctx -> Tweak -> Maybe Tweak
+ Crypto.Secp256k1: tweakNegate :: Tweak -> Maybe Tweak
- Crypto.Secp256k1: verifySchnorr :: Ctx -> PubKey -> SchnorrSig -> Msg -> Bool
+ Crypto.Secp256k1: verifySchnorr :: PubKey -> SchnorrSig -> Msg -> Bool
- Crypto.Secp256k1: verifySig :: Ctx -> PubKey -> Sig -> Msg -> Bool
+ Crypto.Secp256k1: verifySig :: PubKey -> Sig -> Msg -> Bool
- Crypto.Secp256k1.Internal.Base: combinePubKeys :: Ctx -> [PubKey] -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: combinePubKeys :: [PubKey] -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: derivePubKey :: Ctx -> SecKey -> PubKey
+ Crypto.Secp256k1.Internal.Base: derivePubKey :: SecKey -> PubKey
- Crypto.Secp256k1.Internal.Base: exportCompactSig :: Ctx -> Sig -> CompactSig
+ Crypto.Secp256k1.Internal.Base: exportCompactSig :: Sig -> CompactSig
- Crypto.Secp256k1.Internal.Base: exportPubKey :: Ctx -> Bool -> PubKey -> ByteString
+ Crypto.Secp256k1.Internal.Base: exportPubKey :: Bool -> PubKey -> ByteString
- Crypto.Secp256k1.Internal.Base: exportSig :: Ctx -> Sig -> ByteString
+ Crypto.Secp256k1.Internal.Base: exportSig :: Sig -> ByteString
- Crypto.Secp256k1.Internal.Base: exportXOnlyPubKey :: Ctx -> PubKey -> ByteString
+ Crypto.Secp256k1.Internal.Base: exportXOnlyPubKey :: PubKey -> ByteString
- Crypto.Secp256k1.Internal.Base: importCompactSig :: Ctx -> CompactSig -> Maybe Sig
+ Crypto.Secp256k1.Internal.Base: importCompactSig :: CompactSig -> Maybe Sig
- Crypto.Secp256k1.Internal.Base: importPubKey :: Ctx -> ByteString -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: importPubKey :: ByteString -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: importSig :: Ctx -> ByteString -> Maybe Sig
+ Crypto.Secp256k1.Internal.Base: importSig :: ByteString -> Maybe Sig
- Crypto.Secp256k1.Internal.Base: importXOnlyPubKey :: Ctx -> ByteString -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: importXOnlyPubKey :: ByteString -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: isLowR :: Ctx -> Sig -> Bool
+ Crypto.Secp256k1.Internal.Base: isLowR :: Sig -> Bool
- Crypto.Secp256k1.Internal.Base: isLowS :: Ctx -> Sig -> Bool
+ Crypto.Secp256k1.Internal.Base: isLowS :: Sig -> Bool
- Crypto.Secp256k1.Internal.Base: normalizeSig :: Ctx -> Sig -> Sig
+ Crypto.Secp256k1.Internal.Base: normalizeSig :: Sig -> Sig
- Crypto.Secp256k1.Internal.Base: signMsg :: Ctx -> SecKey -> Msg -> Sig
+ Crypto.Secp256k1.Internal.Base: signMsg :: SecKey -> Msg -> Sig
- Crypto.Secp256k1.Internal.Base: signMsgLowR :: Ctx -> SecKey -> Msg -> Sig
+ Crypto.Secp256k1.Internal.Base: signMsgLowR :: SecKey -> Msg -> Sig
- Crypto.Secp256k1.Internal.Base: signMsgWith :: Ctx -> SecKey -> Msg -> Maybe ByteString -> Sig
+ Crypto.Secp256k1.Internal.Base: signMsgWith :: SecKey -> Msg -> Maybe ByteString -> Sig
- Crypto.Secp256k1.Internal.Base: signSchnorr :: Ctx -> SecKey -> Msg -> SchnorrSig
+ Crypto.Secp256k1.Internal.Base: signSchnorr :: SecKey -> Msg -> SchnorrSig
- Crypto.Secp256k1.Internal.Base: signSchnorrIO :: MonadIO m => Ctx -> SecKey -> Msg -> m SchnorrSig
+ Crypto.Secp256k1.Internal.Base: signSchnorrIO :: MonadIO m => SecKey -> Msg -> m SchnorrSig
- Crypto.Secp256k1.Internal.Base: signSchnorrInternal :: Ctx -> SecKey -> Msg -> Maybe ByteString -> SchnorrSig
+ Crypto.Secp256k1.Internal.Base: signSchnorrInternal :: SecKey -> Msg -> Maybe ByteString -> SchnorrSig
- Crypto.Secp256k1.Internal.Base: signSchnorrWithAux :: Ctx -> SecKey -> Msg -> ByteString -> Maybe SchnorrSig
+ Crypto.Secp256k1.Internal.Base: signSchnorrWithAux :: SecKey -> Msg -> ByteString -> Maybe SchnorrSig
- Crypto.Secp256k1.Internal.Base: tweakAddPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: tweakAddPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: tweakAddSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1.Internal.Base: tweakAddSecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1.Internal.Base: tweakAddXOnlyPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: tweakAddXOnlyPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: tweakAddXOnlySecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1.Internal.Base: tweakAddXOnlySecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1.Internal.Base: tweakMulPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Base: tweakMulPubKey :: PubKey -> Tweak -> Maybe PubKey
- Crypto.Secp256k1.Internal.Base: tweakMulSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
+ Crypto.Secp256k1.Internal.Base: tweakMulSecKey :: SecKey -> Tweak -> Maybe SecKey
- Crypto.Secp256k1.Internal.Base: tweakNegate :: Ctx -> Tweak -> Maybe Tweak
+ Crypto.Secp256k1.Internal.Base: tweakNegate :: Tweak -> Maybe Tweak
- Crypto.Secp256k1.Internal.Base: verifyFreshSignature :: Ptr LCtx -> Ptr KeyPair96 -> Ptr SchnorrSig64 -> Ptr CUChar -> IO Bool
+ Crypto.Secp256k1.Internal.Base: verifyFreshSignature :: Ptr KeyPair96 -> Ptr SchnorrSig64 -> Ptr CUChar -> IO Bool
- Crypto.Secp256k1.Internal.Base: verifySchnorr :: Ctx -> PubKey -> SchnorrSig -> Msg -> Bool
+ Crypto.Secp256k1.Internal.Base: verifySchnorr :: PubKey -> SchnorrSig -> Msg -> Bool
- Crypto.Secp256k1.Internal.Base: verifySig :: Ctx -> PubKey -> Sig -> Msg -> Bool
+ Crypto.Secp256k1.Internal.Base: verifySig :: PubKey -> Sig -> Msg -> Bool
- Crypto.Secp256k1.Internal.Base: withKeyPair :: Ptr LCtx -> ByteString -> (Ptr KeyPair96 -> IO a) -> IO (Maybe a)
+ Crypto.Secp256k1.Internal.Base: withKeyPair :: ByteString -> (Ptr KeyPair96 -> IO a) -> IO (Maybe a)
- Crypto.Secp256k1.Internal.Base: withXOnlyPubKey :: Ptr LCtx -> ByteString -> (Ptr XOnlyPubKey64 -> IO a) -> IO (Maybe a)
+ Crypto.Secp256k1.Internal.Base: withXOnlyPubKey :: ByteString -> (Ptr XOnlyPubKey64 -> IO a) -> IO (Maybe a)
- Crypto.Secp256k1.Internal.Recovery: convertRecSig :: Ctx -> RecSig -> Sig
+ Crypto.Secp256k1.Internal.Recovery: convertRecSig :: RecSig -> Sig
- Crypto.Secp256k1.Internal.Recovery: exportCompactRecSig :: Ctx -> RecSig -> (CompactSig, Word8)
+ Crypto.Secp256k1.Internal.Recovery: exportCompactRecSig :: RecSig -> (CompactSig, Word8)
- Crypto.Secp256k1.Internal.Recovery: importCompactRecSig :: Ctx -> CompactSig -> Word8 -> Maybe RecSig
+ Crypto.Secp256k1.Internal.Recovery: importCompactRecSig :: CompactSig -> Word8 -> Maybe RecSig
- Crypto.Secp256k1.Internal.Recovery: recover :: Ctx -> RecSig -> Msg -> Maybe PubKey
+ Crypto.Secp256k1.Internal.Recovery: recover :: RecSig -> Msg -> Maybe PubKey
- Crypto.Secp256k1.Internal.Recovery: signRecMsg :: Ctx -> SecKey -> Msg -> RecSig
+ Crypto.Secp256k1.Internal.Recovery: signRecMsg :: SecKey -> Msg -> RecSig
- Crypto.Secp256k1.Recovery: convertRecSig :: Ctx -> RecSig -> Sig
+ Crypto.Secp256k1.Recovery: convertRecSig :: RecSig -> Sig
- Crypto.Secp256k1.Recovery: exportCompactRecSig :: Ctx -> RecSig -> (CompactSig, Word8)
+ Crypto.Secp256k1.Recovery: exportCompactRecSig :: RecSig -> (CompactSig, Word8)
- Crypto.Secp256k1.Recovery: importCompactRecSig :: Ctx -> CompactSig -> Word8 -> Maybe RecSig
+ Crypto.Secp256k1.Recovery: importCompactRecSig :: CompactSig -> Word8 -> Maybe RecSig
- Crypto.Secp256k1.Recovery: recover :: Ctx -> RecSig -> Msg -> Maybe PubKey
+ Crypto.Secp256k1.Recovery: recover :: RecSig -> Msg -> Maybe PubKey
- Crypto.Secp256k1.Recovery: signRecMsg :: Ctx -> SecKey -> Msg -> RecSig
+ Crypto.Secp256k1.Recovery: signRecMsg :: SecKey -> Msg -> RecSig

Files

CHANGELOG.md view
@@ -4,6 +4,79 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [3.0.0] - 2026-11-15++The context is now global and no longer part of the API. This breaks every+program that uses the package, on purpose: see Migrating.++### Removed++- `Ctx`, `createContext`, `withContext`, `cloneContext` and `randomizeContext`+  are gone from `Crypto.Secp256k1`.+- The `Ctx` argument is gone from every function of `Crypto.Secp256k1` and+  `Crypto.Secp256k1.Recovery` that took one: `derivePubKey`, `importPubKey`,+  `exportPubKey`, `signMsg`, `signMsgLowR`, `verifySig`, `normalizeSig`,+  `isLowS`, `isLowR`, `importSig`, `exportSig`, `importCompactSig`,+  `exportCompactSig`, `tweakAddSecKey`, `tweakMulSecKey`, `tweakAddPubKey`,+  `tweakMulPubKey`, `combinePubKeys`, `tweakNegate`, `signSchnorr`,+  `signSchnorrWithAux`, `signSchnorrIO`, `verifySchnorr`,+  `importXOnlyPubKey`, `exportXOnlyPubKey`, `tweakAddXOnlyPubKey`,+  `tweakAddXOnlySecKey`, `signRecMsg`, `recover`, `convertRecSig`,+  `importCompactRecSig` and `exportCompactRecSig`. The other arguments keep+  their order, for example `signMsg :: SecKey -> Msg -> Sig` and+  `exportPubKey :: Bool -> PubKey -> ByteString`.+- The package no longer exposes anything that makes, takes or names a+  context. `Crypto.Secp256k1.Internal.Context`, `Crypto.Secp256k1.Internal.BaseOps`+  and `Crypto.Secp256k1.Internal.RecoveryOps` are hidden modules now, so the+  raw foreign imports and the bindings that create, clone, randomize and+  destroy contexts cannot be imported. `LCtx` and `CtxFlags` are gone from+  `Crypto.Secp256k1.Internal.ForeignTypes`. `Ctx`, `wrapContext` and+  `validationContext` no longer exist. There is no replacement: code that+  called the raw bindings with its own context uses the functions of+  `Crypto.Secp256k1` and `Crypto.Secp256k1.Recovery`.+- The functions of+  `Crypto.Secp256k1.Internal.Base` and `Crypto.Secp256k1.Internal.Recovery`+  lost their context argument too, including the helpers `signMsgWith`,+  `signSchnorrInternal`, `withXOnlyPubKey`, `withKeyPair` and+  `verifyFreshSignature`.++### Changed++- The package creates a single libsecp256k1 context the first time a function+  needs one, randomizes it once, and uses it for every call in the process.+  After its creation it is only read, so it is safe to use from any number of+  threads. It is never randomized again, because that modifies the context+  and is a data race with any thread that is using it, and it is never+  destroyed. It is kept in a hidden module, so no code outside the package+  can reach it.+- `Show`, `Read` and `IsString`, and `pubKey`, `sig` and `recSig`, use the+  global context instead of a separate one for validation.+- The test suite compiles the sources of the library itself instead of+  depending on the library, so that it can still test the raw bindings in the+  hidden modules.++### Migrating++- Delete the code that made a context: `createContext`, `withContext` and+  `cloneContext`, and any `Ctx` you kept in a record, a reader environment or+  a function argument.+- Delete the context argument from every call: `signMsg ctx key m` becomes+  `signMsg key m`.+- Delete calls to `randomizeContext`. There is no replacement: the context is+  randomized once, when it is created.+- What is no longer possible: a context per thread or per use, and+  re-randomizing during a long run. Results do not depend on either.++## [2.1.0] - 2026-11-07++### Changed++- `show` of a `SecKey` prints `SecKey <redacted>` instead of the key in hex,+  so that a record which holds a key and derives `Show` can be logged or put+  in an error message without revealing it. `Read` and `IsString` still parse+  hex, so `read (show key)` no longer gives the key back. Use `get` to write+  a key out.+ ## [2.0.1] - 2026-11-07  ### Changed
README.md view
@@ -58,9 +58,12 @@   computation. - **Never abort the process.** By default libsecp256k1 calls `abort()` on an   illegal argument, which kills the whole Haskell program and cannot be caught.-  Every context this package creates installs a callback that makes the C-  function fail instead, so a bad argument becomes `Nothing`, `False` or an-  exception.+  The context of this package installs a callback that makes the C function+  fail instead, so a bad argument becomes `Nothing`, `False` or an exception.+- **No context to carry.** libsecp256k1 wants a context object in every call.+  The package keeps one for the whole process, randomized once and never+  modified again, and passes it itself. No function takes a context. See+  [Contexts](#contexts). - **Pure where the mathematics is pure.** Signing with deterministic nonces,   verifying, deriving and tweaking keys are pure functions. Only operations   that need fresh randomness run in `IO`.@@ -84,7 +87,7 @@ | Taproot (BIP-341)    | Tweaking an x-only public key and its secret key                                               | | Key arithmetic       | Add or multiply secret and public keys by a tweak, negate, combine public keys                 | | Recovery             | Recoverable ECDSA signatures and public key recovery, as Bitcoin signed messages use           |-| Safety               | Validated values, no aborts, length checks before every C call, contexts shared across threads |+| Safety               | Validated values, no aborts, length checks before every C call, one read-only context for all threads | | Testing              | QuickCheck `Arbitrary` instances for secret keys, hashes and tweaks                            |  ### What is not included@@ -155,7 +158,7 @@     ```yaml    extra-deps:-     - secp256k1-haskell-2.0.1+     - secp256k1-haskell-3.0.0      - base16-2.0    ``` @@ -182,23 +185,21 @@  main :: IO () main = do-  ctx <- createContext-   -- Hex literals go through IsString, which validates them.   let key = "c7e5a2b4f4c5d7e8a9b0c1d2e3f405162738495a6b7c8d9e0f1a2b3c4d5e6f70" :: SecKey       hash = "4b688df40bcedbe641ddb16ff0a1842d9c67ea1c3bf63f3e0471baa664531d1a" :: Msg-      pub = derivePubKey ctx key+      pub = derivePubKey key    -- ECDSA-  let s = signMsg ctx key hash-  print (verifySig ctx pub s hash)+  let s = signMsg key hash+  print (verifySig pub s hash)    -- BIP-340 Schnorr, with fresh auxiliary randomness-  schnorr <- signSchnorrIO ctx key hash-  print (verifySchnorr ctx pub schnorr hash)+  schnorr <- signSchnorrIO key hash+  print (verifySchnorr pub schnorr hash)    -- Round trip through the standard encodings-  let Just pub' = importPubKey ctx (exportPubKey ctx True pub)+  let Just pub' = importPubKey (exportPubKey True pub)   print (pub == pub') ``` @@ -207,16 +208,16 @@ This walks through what a wallet or a protocol implementation typically does, and why each step looks the way it does. -### 1. Create one context and share it+### 1. Nothing to set up  ```haskell-ctx <- createContext+import Crypto.Secp256k1 ``` -A context holds precomputed tables and random blinding values. Creating one is-relatively expensive, and one context can be used by every thread for the life-of the program. `createContext` randomizes it once, which is what libsecp256k1-recommends.+libsecp256k1 needs a context, which holds random blinding values, but there is+none to create here. The package makes one the first time a function needs it,+randomizes it, and uses it for every call from every thread. See+[Contexts](#contexts).  ### 2. Get keys from bytes @@ -239,7 +240,7 @@  ```haskell let Just m = msg hashBytes-    s = signMsgLowR ctx key m -- or signMsg for plain RFC 6979+    s = signMsgLowR key m -- or signMsg for plain RFC 6979 ```  Signing is deterministic: the same key and hash give the same signature, so@@ -251,19 +252,19 @@ internal layout. Use the standard encodings:  ```haskell-let pubBytes = exportPubKey ctx True pub -- 33-byte compressed SEC1-    derBytes = exportSig ctx s -- DER, as in Bitcoin transactions-    compactBytes = exportCompactSig ctx s -- 64 bytes r || s+let pubBytes = exportPubKey True pub -- 33-byte compressed SEC1+    derBytes = exportSig s -- DER, as in Bitcoin transactions+    compactBytes = exportCompactSig s -- 64 bytes r || s ```  ### 5. Parse and verify what you receive  ```haskell verified = fromMaybe False $ do-  pub <- importPubKey ctx pubBytes-  s <- importSig ctx derBytes+  pub <- importPubKey pubBytes+  s <- importSig derBytes   m <- msg hashBytes-  return (verifySig ctx pub (normalizeSig ctx s) m)+  return (verifySig pub (normalizeSig s) m) ```  Every import returns `Maybe`, so malformed input is handled in one place.@@ -275,9 +276,9 @@ ### 6. Move to Schnorr where the protocol allows  ```haskell-sig <- signSchnorrIO ctx key m-let ok = verifySchnorr ctx pub sig m-    xonly = exportXOnlyPubKey ctx pub -- 32 bytes, as BIP-340 publishes keys+sig <- signSchnorrIO key m+let ok = verifySchnorr pub sig m+    xonly = exportXOnlyPubKey pub -- 32 bytes, as BIP-340 publishes keys ```  Schnorr signatures are always 64 bytes, are not malleable, and are what Taproot@@ -301,14 +302,37 @@  Here n is the order of the curve. The raw constructors are hidden, so these are the only ways to build values. Each type has a `get` field with its bytes.+`Show` prints hex, except for `SecKey`, which it redacts. See+[Security notes](#security-notes).  ### Contexts -Every operation takes a `Ctx`. It is created once, shared freely between-threads, and destroyed by the garbage collector. The only operation that-modifies a context is `randomizeContext`, which needs exclusive access; most-programs never call it.+There is no context in the API. libsecp256k1 needs a context object for every+call, which holds its error callbacks and the random blinding values that+protect secret key operations against side channels. The package keeps a+single global one: +- **Created on first use.** The first call that needs it creates it, once per+  process, even when several threads arrive together. That call is slower+  than the following ones by the time it takes to create the context and+  read 32 bytes from the operating system's secure random source.+- **Randomized once.** It is seeded with those bytes before it is used, as+  libsecp256k1 recommends. Blinding changes how the computation runs, not its+  results.+- **Never re-randomized.** After its creation the context is only read, so+  any number of threads can use it without a lock. Randomizing again writes+  to it, and doing that while another thread signs is a data race in the C+  library. So there is no function for it, and the context is in a hidden+  module where no other code can reach it. The package exposes no way to+  create another context either.+- **Never destroyed.** It lives as long as the process.++What was given up: before version 3.0.0 the caller created contexts and+passed one to every function, which allowed a context per thread or per use+and re-randomizing during a long run. Neither is possible now. See the+[changelog](https://github.com/jprupp/secp256k1-haskell/blob/master/CHANGELOG.md)+for how to migrate.+ ### Errors  Parsing and constructing return `Maybe`. Arithmetic that can produce an@@ -322,18 +346,18 @@ ### Lower-S and low-R  ```haskell-isLowS ctx s -- the form verifySig accepts-isLowR ctx s -- r below 2^255, so DER is at most 70 bytes-normalizeSig ctx s -- the lower-S form of any signature+isLowS s -- the form verifySig accepts+isLowR s -- r below 2^255, so DER is at most 70 bytes+normalizeSig s -- the lower-S form of any signature ```  ### Key tweaking  ```haskell let Just t = tweak tweakBytes-    Just childKey = tweakAddSecKey ctx parentKey t-    Just childPub = tweakAddPubKey ctx parentPub t--- derivePubKey ctx childKey == childPub+    Just childKey = tweakAddSecKey parentKey t+    Just childPub = tweakAddPubKey parentPub t+-- derivePubKey childKey == childPub ```  This is the operation behind BIP-32 derivation; the tweak itself comes from an@@ -345,8 +369,8 @@  ```haskell let Just t = tweak taprootTweakBytes -- tagged hash of key and script tree-    Just outputKey = tweakAddXOnlyPubKey ctx internalKey t-    Just outputSecKey = tweakAddXOnlySecKey ctx internalSecKey t+    Just outputKey = tweakAddXOnlyPubKey internalKey t+    Just outputSecKey = tweakAddXOnlySecKey internalSecKey t ```  Computing the tweak, a BIP-341 tagged hash, is left to the caller.@@ -356,22 +380,22 @@ ```haskell import Crypto.Secp256k1.Recovery -let r = signRecMsg ctx key m-    (compact, recId) = exportCompactRecSig ctx r+let r = signRecMsg key m+    (compact, recId) = exportCompactRecSig r -- the 65-byte message signature is a header byte (27 + recId, + 4 if the key -- is compressed) followed by the 64 compact bytes-recover ctx r m -- Just the signer's PubKey+recover r m -- Just the signer's PubKey ```  ### Testing with QuickCheck  `SecKey`, `Msg` and `Tweak` have `Arbitrary` instances, so properties can-range over them directly. With a context `ctx` created once for the test suite:+range over them directly:  ```haskell prop_roundTrip :: SecKey -> Msg -> Bool prop_roundTrip key m =-  verifySig ctx (derivePubKey ctx key) (signMsg ctx key m) m+  verifySig (derivePubKey key) (signMsg key m) m ```  ## Differences from Bitcoin Core@@ -389,18 +413,29 @@  | Module                                  | Contents                                                  | | --------------------------------------- | --------------------------------------------------------- |-| `Crypto.Secp256k1`                      | The public API: contexts, keys, ECDSA, Schnorr, tweaks    |+| `Crypto.Secp256k1`                      | The public API: keys, ECDSA, Schnorr, tweaks              | | `Crypto.Secp256k1.Recovery`             | Recoverable signatures and public key recovery            |-| `Crypto.Secp256k1.Internal.*`           | Raw constructors and foreign imports; no stability promise |+| `Crypto.Secp256k1.Internal.*`           | Raw constructors and helpers; no stability promise        | +The exposed internal modules are `Base`, `Recovery`, `ForeignTypes` and+`Util`. The modules that hold the global context (`Context`), create contexts+(`ContextOps`) or bind the C functions, which all take a context (`BaseOps`,+`RecoveryOps`), are hidden. Nothing a program can import makes, takes or names+a context, so the raw foreign imports cannot be called from outside the+package. The tests reach them by compiling the sources of the library+themselves.+ ## Security notes  - **Secret keys stay in memory.** A `SecKey` is an ordinary `ByteString`. The   garbage collector may copy it, and nothing clears it when it is no longer   used. If your threat model includes an attacker reading process memory,   keep keys in a hardware device instead.-- **`Show` prints secret keys.** Showing a record that holds a `SecKey`, in a-  log line or an error message, reveals it.+- **`Show` redacts secret keys.** `show` on a `SecKey` gives `SecKey <redacted>`,+  so a record that holds a key and derives `Show` can go in a log line or an+  error message. Only `Show` is redacted. `get` gives the bytes, and `Read`+  and `IsString` parse hex, so a key you write out yourself is yours to+  protect. - **Verification only proves what was signed.** It is your protocol's job to   hash the right data; signing a hash an attacker chose is as good as signing   whatever they want.
Setup.hs view
@@ -1,2 +1,3 @@ import Distribution.Simple+ main = defaultMain
secp256k1-haskell.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           secp256k1-haskell-version:        2.0.1+version:        3.0.0 synopsis:       Bindings for secp256k1 description:    Sign and verify signatures using the secp256k1 library. category:       Crypto@@ -33,11 +33,13 @@   exposed-modules:       Crypto.Secp256k1       Crypto.Secp256k1.Internal.Base-      Crypto.Secp256k1.Internal.BaseOps-      Crypto.Secp256k1.Internal.Context       Crypto.Secp256k1.Internal.ForeignTypes       Crypto.Secp256k1.Internal.Util       Paths_secp256k1_haskell+  other-modules:+      Crypto.Secp256k1.Internal.BaseOps+      Crypto.Secp256k1.Internal.Context+      Crypto.Secp256k1.Internal.ContextOps   autogen-modules:       Paths_secp256k1_haskell   hs-source-dirs:@@ -60,8 +62,9 @@   if flag(recovery)     exposed-modules:         Crypto.Secp256k1.Internal.Recovery-        Crypto.Secp256k1.Internal.RecoveryOps         Crypto.Secp256k1.Recovery+    other-modules:+        Crypto.Secp256k1.Internal.RecoveryOps  test-suite spec   type: exitcode-stdio-1.0@@ -71,12 +74,24 @@       Crypto.Secp256k1.InternalSpec       Crypto.Secp256k1.RecoverySpec       Crypto.Secp256k1Spec+      Crypto.Secp256k1+      Crypto.Secp256k1.Internal.Base+      Crypto.Secp256k1.Internal.BaseOps+      Crypto.Secp256k1.Internal.Context+      Crypto.Secp256k1.Internal.ContextOps+      Crypto.Secp256k1.Internal.ForeignTypes+      Crypto.Secp256k1.Internal.Util       Paths_secp256k1_haskell   autogen-modules:       Paths_secp256k1_haskell   hs-source-dirs:       test+      src   ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N+  c-sources:+      cbits/illegal_callback.c+  pkgconfig-depends:+      libsecp256k1 >= 0.2.0   build-depends:       HUnit     , QuickCheck >=2.9.2@@ -89,9 +104,12 @@     , hspec     , monad-par     , mtl-    , secp256k1-haskell     , string-conversions >=0.4   default-language: Haskell2010   if flag(recovery)+    other-modules:+        Crypto.Secp256k1.Internal.Recovery+        Crypto.Secp256k1.Internal.RecoveryOps+        Crypto.Secp256k1.Recovery     cpp-options: -DRECOVERY   build-tool-depends: hspec-discover:hspec-discover
src/Crypto/Secp256k1.hs view
@@ -20,14 +20,18 @@ --   signature, and invalid input is refused at the boundary where it arrives. -- -- * __Never abort.__ The C library calls @abort()@ on an illegal argument by---   default, which kills the whole Haskell process and cannot be caught. Every---   context this package creates replaces that callback, so a bad argument---   becomes 'Nothing', 'False' or an exception instead.+--   default, which kills the whole Haskell process and cannot be caught. The+--   context of this package replaces that callback, so a bad argument becomes+--   'Nothing', 'False' or an exception instead. --+-- * __No context to carry.__ libsecp256k1 wants a context object in every+--   call. The package keeps one for the whole process and passes it itself,+--   so no function here takes one. See Contexts below.+-- -- * __Pure where the mathematics is pure.__ Signing, verifying and tweaking are --   deterministic functions of their inputs, so they are pure functions here.---   Only the operations that need fresh randomness, such as 'signSchnorrIO'---   and 'randomizeContext', run in 'IO'.+--   Only the operations that need fresh randomness, such as 'signSchnorrIO',+--   run in 'IO'. -- -- * __Standard encodings at the edges.__ Values print and parse in the encodings --   other software understands (SEC1, DER, compact, BIP-340), never in the@@ -61,7 +65,9 @@ -- -- 'Show', 'Read' and 'Data.String.IsString' use hex of a standard encoding: compressed -- SEC1 for 'PubKey', compact for 'Sig', and the plain bytes for the others.--- 'Show' prints secret keys. See 'SecKey' for what that means for logging.+-- The one exception is 'Show' for 'SecKey', which prints @SecKey \<redacted\>@+-- instead of the key, so that a key never reaches a log by accident. 'Read'+-- and 'Data.String.IsString' for 'SecKey' still parse hex. -- -- The raw constructors are not exported from this module. They are in -- "Crypto.Secp256k1.Internal.Base", which has no API stability guarantee.@@ -83,10 +89,41 @@ -- -- == Contexts ----- Every operation takes a 'Ctx'. Create one with 'createContext' and share it--- between threads. Only 'randomizeContext' modifies a context and needs--- exclusive access.+-- There is no context in this API. libsecp256k1 needs a context object for+-- every call, which holds its error callbacks and the random blinding values+-- that protect secret key operations against side-channel leakage. The+-- package keeps a single global one and uses it for every function. --+-- * __When it is created.__ The first time a function that needs it is+--   evaluated, and once per process, even when several threads get there+--   together. Programs that never use the package never pay for it. The first+--   call is slower than the following ones by the time it takes to create the+--   context and read 32 bytes from the operating system's secure random+--   source. If that fails, the call raises an error.+--+-- * __Randomized once.__ The context is seeded with those 32 bytes before it+--   is used, as libsecp256k1 recommends. The blinding changes how the+--   computation runs, not its results.+--+-- * __Never re-randomized.__ After its creation the context is only read,+--   which is what makes it safe to use from any number of threads without a+--   lock, and what lets signing stay a pure function. Randomizing again+--   writes to the context, and doing that while another thread signs is a+--   data race in the C library. So the package has no function for it, and+--   the context is in a hidden module where no other code can reach it+--   either.+--+-- * __What was given up.__ Before version 3.0.0 the caller created contexts+--   with @createContext@ and passed one to every function. That allowed+--   a context per thread or per use, and re-randomizing one with+--   @randomizeContext@ during a long run. Both are gone. In exchange, the+--   argument that carried no information is gone from every signature, a+--   context can no longer be modified under a thread that is using it, and+--   instances such as 'Show' and 'Read' use the same randomized context as+--   everything else.+--+-- The context is never destroyed. It lives as long as the process.+-- -- == Differences from Bitcoin Core -- -- 'signMsg' is plain RFC 6979 and matches the published test vectors.@@ -111,14 +148,7 @@ -- module @Crypto.Secp256k1.Recovery@. It is built when the @recovery@ flag of -- the package is on, which is the default. module Crypto.Secp256k1-  ( -- * Context-    Ctx,-    withContext,-    createContext,-    randomizeContext,-    cloneContext,--    -- * Messages+  ( -- * Messages     Msg (get),     msg, @@ -182,4 +212,3 @@ where  import Crypto.Secp256k1.Internal.Base-import Crypto.Secp256k1.Internal.Context
src/Crypto/Secp256k1/Internal/Base.hs view
@@ -13,6 +13,12 @@ -- raises an 'Control.Exception.ErrorCall' when the length is wrong, but it does not check the -- content. A raw 'PubKey' or 'Sig' with invalid content makes functions -- return 'Nothing', 'False' or throw, never abort or read outside a buffer.+--+-- No function here takes a context. They all use the single global context+-- of the package, which is created and randomized the first time one of them+-- needs it and is only read afterwards. It lives in a hidden module, so it+-- cannot be reached or modified from outside the package. The Contexts+-- section of "Crypto.Secp256k1" explains the design. module Crypto.Secp256k1.Internal.Base where  import Control.DeepSeq (NFData)@@ -46,10 +52,9 @@     xOnlyPubKeySerialize,     xOnlyPubKeyTweakAdd,   )-import Crypto.Secp256k1.Internal.Context (Ctx (..), validationContext)+import Crypto.Secp256k1.Internal.Context (globalContext) import Crypto.Secp256k1.Internal.ForeignTypes   ( KeyPair96,-    LCtx,     SchnorrSig64,     XOnlyPubKey64,     compressed,@@ -86,7 +91,6 @@     peek,     poke,     pokeArray,-    withForeignPtr,   ) import Foreign.C (CUChar) import GHC.Generics (Generic)@@ -143,10 +147,11 @@ -- | 32-byte secret key as a big-endian number in the range 1 to n−1, where n -- is the order of the curve. ----- 'Show', 'Read' and 'IsString' use hex. 'Show' prints the key, so showing a--- record that holds a key, in a log line or an error message for instance,--- reveals it. The bytes live in an ordinary 'ByteString', so the garbage--- collector copies them and nothing ever clears them from memory.+-- 'Read' and 'IsString' use hex. 'Show' prints @SecKey \<redacted\>@ and never+-- the key, so a record that holds a key and derives 'Show' can go in a log+-- line or an error message without revealing it. Read the bytes from @get@+-- when you mean to write a key out. They live in an ordinary 'ByteString', so+-- the garbage collector copies them and nothing ever clears them from memory. newtype SecKey = SecKey {get :: ByteString}   deriving (Eq, Generic, Hashable, NFData) @@ -171,15 +176,15 @@ instance Read PubKey where   readPrec = parens $ do     String str <- lexP-    maybe pfail return $ importPubKey validationContext =<< decodeHex str+    maybe pfail return $ importPubKey =<< decodeHex str  instance IsString PubKey where-  fromString = fromMaybe e . (importPubKey validationContext <=< decodeHex)+  fromString = fromMaybe e . (importPubKey <=< decodeHex)     where       e = error "Could not decode public key from hex string"  instance Show PubKey where-  showsPrec _ = showsHex . exportPubKey validationContext True+  showsPrec _ = showsHex . exportPubKey True  instance Read Msg where   readPrec = parens $ do@@ -205,7 +210,7 @@       e = error "Could not decode signature from hex string"  instance Show Sig where-  showsPrec _ = showsHex . (.get) . exportCompactSig validationContext+  showsPrec _ = showsHex . (.get) . exportCompactSig  instance Read SecKey where   readPrec = parens $ do@@ -217,8 +222,19 @@     where       e = error "Could not decode secret key from hex string" +-- | Prints @SecKey \<redacted\>@. A secret key reaches 'show' by accident more+-- often than on purpose: a record that holds one and derives 'Show', an+-- error message, a debug trace, a REPL. None of those should reveal it.+--+-- The placeholder is constant. Showing the public key instead would tell+-- keys apart, but it needs a point multiplication for every+-- 'show', and a raw key of invalid content from this module has no public+-- key. Call 'derivePubKey' and show that when you need to identify a key.+--+-- 'Read' is not the inverse of 'Show' for this type. It still parses hex, so+-- that keys can be written as literals and read from configuration. instance Show SecKey where-  showsPrec _ = showsHex . (.get)+  showsPrec d _ = showParen (d > 10) $ showString "SecKey <redacted>"  instance Read Tweak where   readPrec = parens $ do@@ -259,19 +275,47 @@ instance Show SchnorrSig where   showsPrec _ = showsHex . (.get) --- | Parse the 64-byte compact encoding into a 'Sig' without a caller-provided--- context. Used by the 'Read' and 'IsString' instances.+-- | Parse the 64-byte compact encoding into a 'Sig'. Used by the 'Read' and+-- 'IsString' instances. sigFromCompactBytes :: ByteString -> Maybe Sig-sigFromCompactBytes = importCompactSig validationContext <=< compactSig+sigFromCompactBytes = importCompactSig <=< compactSig  -- | Order of the secp256k1 group, n, as a 32-byte big-endian number. curveOrder :: ByteString curveOrder =   BS.pack-    [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,-      0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,-      0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,-      0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41+    [ 0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xff,+      0xfe,+      0xba,+      0xae,+      0xdc,+      0xe6,+      0xaf,+      0x48,+      0xa0,+      0x3b,+      0xbf,+      0xd2,+      0x5e,+      0x8c,+      0xd0,+      0x36,+      0x41,+      0x41     ]  -- | Thirty-two zero bytes.@@ -303,20 +347,17 @@ isCanonicalSig bs =   BS.length bs == 64     && unsafePerformIO-      ( withForeignPtr fctx $ \ctx ->-          unsafeUseByteString bs $ \(sig_ptr, _) ->-            allocaBytes 64 $ \compact_ptr -> do-              ret <- ecdsaSignatureSerializeCompact ctx compact_ptr sig_ptr-              if not (isSuccess ret)-                then return False-                else do-                  compact <- packByteString (compact_ptr, 64)-                  parsed <- withOutput 64 $ \out ->-                    isSuccess <$> ecdsaSignatureParseCompact ctx out compact_ptr-                  return (parsed == Just bs && hasNonZeroComponents compact)+      ( unsafeUseByteString bs $ \(sig_ptr, _) ->+          allocaBytes 64 $ \compact_ptr -> do+            ret <- ecdsaSignatureSerializeCompact globalContext compact_ptr sig_ptr+            if not (isSuccess ret)+              then return False+              else do+                compact <- packByteString (compact_ptr, 64)+                parsed <- withOutput 64 $ \out ->+                  isSuccess <$> ecdsaSignatureParseCompact globalContext out compact_ptr+                return (parsed == Just bs && hasNonZeroComponents compact)       )-  where-    Ctx fctx = validationContext  -- | True when neither r nor s of a compact-encoded signature is zero. hasNonZeroComponents :: ByteString -> Bool@@ -344,23 +385,20 @@ isCanonicalPubKey bs =   BS.length bs == 64     && unsafePerformIO-      ( withForeignPtr fctx $ \ctx ->-          unsafeUseByteString bs $ \(pub_key_ptr, _) ->-            alloca $ \len_ptr ->-              allocaBytes 65 $ \ser_ptr -> do-                poke len_ptr 65-                ret <--                  ecPubKeySerialize ctx ser_ptr len_ptr pub_key_ptr uncompressed-                if not (isSuccess ret)-                  then return False-                  else do-                    len <- peek len_ptr-                    parsed <- withOutput 64 $ \out ->-                      isSuccess <$> ecPubKeyParse ctx out ser_ptr len-                    return (parsed == Just bs)+      ( unsafeUseByteString bs $ \(pub_key_ptr, _) ->+          alloca $ \len_ptr ->+            allocaBytes 65 $ \ser_ptr -> do+              poke len_ptr 65+              ret <-+                ecPubKeySerialize globalContext ser_ptr len_ptr pub_key_ptr uncompressed+              if not (isSuccess ret)+                then return False+                else do+                  len <- peek len_ptr+                  parsed <- withOutput 64 $ \out ->+                    isSuccess <$> ecPubKeyParse globalContext out ser_ptr len+                  return (parsed == Just bs)       )-  where-    Ctx fctx = validationContext  -- | Import a 32-byte message hash. msg :: ByteString -> Maybe Msg@@ -394,53 +432,53 @@ -- that form is returned unchanged. 'verifySig' only accepts lower-S -- signatures, so apply this first to signatures that may come from software -- that does not produce them.-normalizeSig :: Ctx -> Sig -> Sig-normalizeSig (Ctx fctx) (Sig sig_bs) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+normalizeSig :: Sig -> Sig+normalizeSig (Sig sig_bs) =+  unsafePerformIO $     useFixedByteString "Sig" 64 sig_bs $ \(sig_in, _) ->       -- The return value only says whether s was high. The output is written       -- in both cases.-      Sig <$> fillOutput 64 (\sig_out -> () <$ ecdsaSignatureNormalize ctx sig_out sig_in)+      Sig <$> fillOutput 64 (\sig_out -> () <$ ecdsaSignatureNormalize globalContext sig_out sig_in)  -- | True when the s component is not greater than n/2. This is the form that -- 'signMsg' produces and the only form that 'verifySig' accepts.-isLowS :: Ctx -> Sig -> Bool-isLowS (Ctx fctx) (Sig sig_bs) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+isLowS :: Sig -> Bool+isLowS (Sig sig_bs) =+  unsafePerformIO $     useFixedByteString "Sig" 64 sig_bs $ \(sig_in, _) -> do       -- With a null output pointer the C function only reports whether s is       -- high: 1 when it is, 0 when it is not.-      was_high <- ecdsaSignatureNormalize ctx nullPtr sig_in+      was_high <- ecdsaSignatureNormalize globalContext nullPtr sig_in       return (not (isSuccess was_high))  -- | True when the r component is lower than 2^255, which makes the DER -- encoding at most 70 bytes. 'signMsgLowR' produces such signatures.-isLowR :: Ctx -> Sig -> Bool-isLowR ctx s = BS.index (exportCompactSig ctx s).get 0 < 0x80+isLowR :: Sig -> Bool+isLowR s = BS.index (exportCompactSig s).get 0 < 0x80  -- | Parse a public key in SEC1 encoding: 33 bytes compressed (prefix 0x02 or -- 0x03), 65 bytes uncompressed (prefix 0x04) or 65 bytes hybrid (prefix 0x06 -- or 0x07). 'Nothing' when the encoding is wrong or the point is not on the -- curve.-importPubKey :: Ctx -> ByteString -> Maybe PubKey-importPubKey (Ctx fctx) bs+importPubKey :: ByteString -> Maybe PubKey+importPubKey bs   | BS.null bs = Nothing   | otherwise =-      unsafePerformIO $ withForeignPtr fctx $ \ctx ->+      unsafePerformIO $         unsafeUseByteString bs $ \(input, len) ->           (fmap . fmap) PubKey . withOutput 64 $ \pub_key ->-            isSuccess <$> ecPubKeyParse ctx pub_key input len+            isSuccess <$> ecPubKeyParse globalContext pub_key input len  -- | Serialize a public key in SEC1 encoding. 'True' for the 33-byte -- compressed form, 'False' for the 65-byte uncompressed form.-exportPubKey :: Ctx -> Bool -> PubKey -> ByteString-exportPubKey (Ctx fctx) compress (PubKey in_bs) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+exportPubKey :: Bool -> PubKey -> ByteString+exportPubKey compress (PubKey in_bs) =+  unsafePerformIO $     useFixedByteString "PubKey" 64 in_bs $ \(in_ptr, _) ->       alloca $ \len_ptr ->         allocaBytes len $ \out_ptr -> do           poke len_ptr $ fromIntegral len-          ret <- ecPubKeySerialize ctx out_ptr len_ptr in_ptr flags+          ret <- ecPubKeySerialize globalContext out_ptr len_ptr in_ptr flags           unless (isSuccess ret) $ error "could not serialize public key"           final_len <- peek len_ptr           packByteString (out_ptr, final_len)@@ -449,12 +487,12 @@     flags = if compress then compressed else uncompressed  -- | Serialize a signature in the compact encoding.-exportCompactSig :: Ctx -> Sig -> CompactSig-exportCompactSig (Ctx fctx) (Sig sig_bs) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+exportCompactSig :: Sig -> CompactSig+exportCompactSig (Sig sig_bs) =+  unsafePerformIO $     useFixedByteString "Sig" 64 sig_bs $ \(sig_ptr, _) -> do       out <- withOutput 64 $ \out_ptr ->-        isSuccess <$> ecdsaSignatureSerializeCompact ctx out_ptr sig_ptr+        isSuccess <$> ecdsaSignatureSerializeCompact globalContext out_ptr sig_ptr       maybe         (error "could not serialize compact signature")         (return . CompactSig)@@ -462,40 +500,40 @@  -- | Parse a signature from the compact encoding. 'Nothing' unless both -- components are in the range 1 to n−1. The signature may be in high-S form.-importCompactSig :: Ctx -> CompactSig -> Maybe Sig-importCompactSig (Ctx fctx) (CompactSig compact) = do+importCompactSig :: CompactSig -> Maybe Sig+importCompactSig (CompactSig compact) = do   guard (hasNonZeroComponents compact)-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+  unsafePerformIO $     useFixedByteString "CompactSig" 64 compact $ \(compact_ptr, _) ->       (fmap . fmap) Sig . withOutput 64 $ \out_sig ->-        isSuccess <$> ecdsaSignatureParseCompact ctx out_sig compact_ptr+        isSuccess <$> ecdsaSignatureParseCompact globalContext out_sig compact_ptr  -- | Parse a signature in strict DER encoding. 'Nothing' when the encoding is -- not strict DER or when a component is outside the range 1 to n−1. The -- signature may be in high-S form.-importSig :: Ctx -> ByteString -> Maybe Sig-importSig ctx@(Ctx fctx) bs+importSig :: ByteString -> Maybe Sig+importSig bs   | BS.null bs = Nothing   | otherwise = do       parsed <--        unsafePerformIO $ withForeignPtr fctx $ \ctx_ptr ->+        unsafePerformIO $           unsafeUseByteString bs $ \(in_ptr, in_len) ->             (fmap . fmap) Sig . withOutput 64 $ \out_sig ->-              isSuccess <$> ecdsaSignatureParseDer ctx_ptr out_sig in_ptr in_len+              isSuccess <$> ecdsaSignatureParseDer globalContext out_sig in_ptr in_len       -- libsecp256k1 parses a component that is not below the curve order as       -- zero and still reports success. Such a signature can never verify.-      guard (hasNonZeroComponents (exportCompactSig ctx parsed).get)+      guard (hasNonZeroComponents (exportCompactSig parsed).get)       return parsed  -- | Serialize a signature in strict DER encoding (8 to 72 bytes).-exportSig :: Ctx -> Sig -> ByteString-exportSig (Ctx fctx) (Sig in_sig) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+exportSig :: Sig -> ByteString+exportSig (Sig in_sig) =+  unsafePerformIO $     useFixedByteString "Sig" 64 in_sig $ \(in_ptr, _) ->       alloca $ \out_len ->         allocaBytes 72 $ \out_ptr -> do           poke out_len 72-          ret <- ecdsaSignatureSerializeDer ctx out_ptr out_len in_ptr+          ret <- ecdsaSignatureSerializeDer globalContext out_ptr out_len in_ptr           unless (isSuccess ret) $ error "could not serialize signature"           final_len <- peek out_len           packByteString (out_ptr, final_len)@@ -509,13 +547,13 @@ -- and therefore its id, without the key. Accepting only one of the two forms -- removes that freedom, which is why libsecp256k1 and Bitcoin's relay rules -- insist on it.-verifySig :: Ctx -> PubKey -> Sig -> Msg -> Bool-verifySig (Ctx fctx) (PubKey pub_key) (Sig sig_bs) (Msg m) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+verifySig :: PubKey -> Sig -> Msg -> Bool+verifySig (PubKey pub_key) (Sig sig_bs) (Msg m) =+  unsafePerformIO $     useFixedByteString "PubKey" 64 pub_key $ \(pub_key_ptr, _) ->       useFixedByteString "Sig" 64 sig_bs $ \(sig_ptr, _) ->         useFixedByteString "Msg" 32 m $ \(msg_ptr, _) ->-          isSuccess <$> ecdsaVerify ctx sig_ptr msg_ptr pub_key_ptr+          isSuccess <$> ecdsaVerify globalContext sig_ptr msg_ptr pub_key_ptr  -- | Sign a message hash. The nonce comes from RFC 6979, so the same key and -- hash always give the same signature. The signature is in lower-S form.@@ -525,16 +563,16 @@ -- even slightly predictable, reveals the secret key. Deriving it from the key -- and the hash, as RFC 6979 does, removes the need for a good random number -- generator at signing time.-signMsg :: Ctx -> SecKey -> Msg -> Sig-signMsg ctx key m = signMsgWith ctx key m Nothing+signMsg :: SecKey -> Msg -> Sig+signMsg key m = signMsgWith key m Nothing  -- | Sign a message hash with RFC 6979 and 32 bytes of extra nonce data (RFC -- 6979 section 3.6), or without extra data for 'Nothing', which is the same as -- 'signMsg'. The data must be exactly 32 bytes long. This is the primitive -- behind 'signMsgLowR'.-signMsgWith :: Ctx -> SecKey -> Msg -> Maybe ByteString -> Sig-signMsgWith (Ctx fctx) (SecKey sec_key) (Msg m) nonce_data =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+signMsgWith :: SecKey -> Msg -> Maybe ByteString -> Sig+signMsgWith (SecKey sec_key) (Msg m) nonce_data =+  unsafePerformIO $     useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) ->       useFixedByteString "Msg" 32 m $ \(msg_ptr, _) ->         withNonceData $ \data_ptr -> do@@ -542,7 +580,7 @@           -- receives the extra data.           out <- withOutput 64 $ \sig_ptr ->             isSuccess-              <$> ecdsaSign ctx sig_ptr msg_ptr sec_key_ptr nullFunPtr data_ptr+              <$> ecdsaSign globalContext sig_ptr msg_ptr sec_key_ptr nullFunPtr data_ptr           maybe (error "could not sign message") (return . Sig) out   where     withNonceData f = case nonce_data of@@ -559,15 +597,15 @@ -- Use it where the size of a signature matters, as in Bitcoin transactions, -- where every byte costs a fee, or where signatures must match Bitcoin Core's -- byte for byte. Use 'signMsg' where the RFC 6979 test vectors must hold.-signMsgLowR :: Ctx -> SecKey -> Msg -> Sig-signMsgLowR ctx key m = go 0 (signMsg ctx key m)+signMsgLowR :: SecKey -> Msg -> Sig+signMsgLowR key m = go 0 (signMsg key m)   where     go :: Word32 -> Sig -> Sig     go counter s-      | isLowR ctx s = s+      | isLowR s = s       | otherwise =           let next = counter + 1-           in go next (signMsgWith ctx key m (Just (counterData next)))+           in go next (signMsgWith key m (Just (counterData next)))     counterData c =       BS.pack (map (fromIntegral . (c `shiftR`)) [0, 8, 16, 24])         <> BS.replicate 28 0@@ -576,12 +614,12 @@ -- -- It is a pure function and cannot fail, because a 'SecKey' is valid by -- construction.-derivePubKey :: Ctx -> SecKey -> PubKey-derivePubKey (Ctx fctx) (SecKey sec_key) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+derivePubKey :: SecKey -> PubKey+derivePubKey (SecKey sec_key) =+  unsafePerformIO $     useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) -> do       out <- withOutput 64 $ \pub_key_ptr ->-        isSuccess <$> ecPubKeyCreate ctx pub_key_ptr sec_key_ptr+        isSuccess <$> ecPubKeyCreate globalContext pub_key_ptr sec_key_ptr       maybe (error "could not compute public key") (return . PubKey) out  -- | Add a tweak to a secret key: @key + tweak mod n@. 'Nothing' when the@@ -592,56 +630,56 @@ -- parent key plus a tweak, and Taproot outputs are an internal key plus a -- tweak. 'tweakAddPubKey' does the same on the public side, which is what lets -- a watch-only wallet derive addresses without any secret.-tweakAddSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey-tweakAddSecKey (Ctx fctx) (SecKey sec_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakAddSecKey :: SecKey -> Tweak -> Maybe SecKey+tweakAddSecKey (SecKey sec_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->       (fmap . fmap) SecKey . withCopy "SecKey" 32 sec_key $ \sec_key_ptr ->-        isSuccess <$> ecSecKeyTweakAdd ctx sec_key_ptr tweak_ptr+        isSuccess <$> ecSecKeyTweakAdd globalContext sec_key_ptr tweak_ptr  -- | Multiply a secret key by a tweak: @key * tweak mod n@. 'Nothing' when the -- tweak is zero.-tweakMulSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey-tweakMulSecKey (Ctx fctx) (SecKey sec_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakMulSecKey :: SecKey -> Tweak -> Maybe SecKey+tweakMulSecKey (SecKey sec_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->       (fmap . fmap) SecKey . withCopy "SecKey" 32 sec_key $ \sec_key_ptr ->-        isSuccess <$> ecSecKeyTweakMul ctx sec_key_ptr tweak_ptr+        isSuccess <$> ecSecKeyTweakMul globalContext sec_key_ptr tweak_ptr  -- | Add a tweak to a public key: @key + tweak * G@. 'Nothing' when the result -- would be the point at infinity, which happens when the tweak is the negation -- of the secret key.-tweakAddPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey-tweakAddPubKey (Ctx fctx) (PubKey pub_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakAddPubKey :: PubKey -> Tweak -> Maybe PubKey+tweakAddPubKey (PubKey pub_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->       (fmap . fmap) PubKey . withCopy "PubKey" 64 pub_key $ \pub_key_ptr ->-        isSuccess <$> ecPubKeyTweakAdd ctx pub_key_ptr tweak_ptr+        isSuccess <$> ecPubKeyTweakAdd globalContext pub_key_ptr tweak_ptr  -- | Multiply a public key by a tweak: @tweak * key@. 'Nothing' when the tweak -- is zero.-tweakMulPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey-tweakMulPubKey (Ctx fctx) (PubKey pub_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakMulPubKey :: PubKey -> Tweak -> Maybe PubKey+tweakMulPubKey (PubKey pub_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->       (fmap . fmap) PubKey . withCopy "PubKey" 64 pub_key $ \pub_key_ptr ->-        isSuccess <$> ecPubKeyTweakMul ctx pub_key_ptr tweak_ptr+        isSuccess <$> ecPubKeyTweakMul globalContext pub_key_ptr tweak_ptr  -- | Add public keys together. 'Nothing' for an empty list, when a key is not -- a valid point, or when the sum is the point at infinity.-combinePubKeys :: Ctx -> [PubKey] -> Maybe PubKey-combinePubKeys _ [] = Nothing-combinePubKeys (Ctx fctx) pubs+combinePubKeys :: [PubKey] -> Maybe PubKey+combinePubKeys [] = Nothing+combinePubKeys pubs   -- @secp256k1_ec_pubkey_combine@ ignores whether each key loads, so an   -- invalid key would be added as if it were a point.   | not (all isValidPoint pubs) = Nothing   | otherwise =-      unsafePerformIO $ withForeignPtr fctx $ \ctx ->+      unsafePerformIO $         withPointers pubs $ \ps ->           allocaArray (length ps) $ \arr -> do             pokeArray arr ps             (fmap . fmap) PubKey . withOutput 64 $ \out ->-              isSuccess <$> ecPubKeyCombine ctx out arr (fromIntegral (length ps))+              isSuccess <$> ecPubKeyCombine globalContext out arr (fromIntegral (length ps))   where     -- A raw key of the wrong length is a programming error, like everywhere     -- else. A raw key of the right length that is not a point gives Nothing.@@ -656,13 +694,13 @@ -- | Negate a tweak modulo the curve order: @n − tweak@, or zero for zero. -- Adding a tweak and then its negation gives the original key back. -- 'Nothing' only for a raw 'Tweak' that is not below the curve order.-tweakNegate :: Ctx -> Tweak -> Maybe Tweak-tweakNegate (Ctx fctx) (Tweak t)+tweakNegate :: Tweak -> Maybe Tweak+tweakNegate (Tweak t)   | t == zero32 = Just (Tweak t)   | otherwise =-      unsafePerformIO $ withForeignPtr fctx $ \ctx ->+      unsafePerformIO $         (fmap . fmap) Tweak . withCopy "Tweak" 32 t $ \out ->-          isSuccess <$> ecTweakNegate ctx out+          isSuccess <$> ecTweakNegate globalContext out  -- * Schnorr signatures (BIP-340) @@ -677,42 +715,42 @@ -- coordinate and drops the parity of y. 'Nothing' if the key does not load -- as a point. withXOnlyPubKey ::-  Ptr LCtx -> ByteString -> (Ptr XOnlyPubKey64 -> IO a) -> IO (Maybe a)-withXOnlyPubKey ctx pub_key f =+  ByteString -> (Ptr XOnlyPubKey64 -> IO a) -> IO (Maybe a)+withXOnlyPubKey pub_key f =   useFixedByteString "PubKey" 64 pub_key $ \(pub_key_ptr, _) ->     allocaBytes 64 $ \xonly_ptr -> do-      ret <- xOnlyPubKeyFromPubKey ctx xonly_ptr nullPtr pub_key_ptr+      ret <- xOnlyPubKeyFromPubKey globalContext xonly_ptr nullPtr pub_key_ptr       if isSuccess ret then Just <$> f xonly_ptr else return Nothing  -- | Run an action with the key pair of a secret key. 'Nothing' if the secret -- key is not valid. The key pair holds the secret key, so its buffer is -- zeroed when the action is done, whether it returns or throws. withKeyPair ::-  Ptr LCtx -> ByteString -> (Ptr KeyPair96 -> IO a) -> IO (Maybe a)-withKeyPair ctx sec_key f =+  ByteString -> (Ptr KeyPair96 -> IO a) -> IO (Maybe a)+withKeyPair sec_key f =   useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) ->     allocaBytes 96 $ \key_pair -> do       let create = do-            ret <- keyPairCreate ctx key_pair sec_key_ptr+            ret <- keyPairCreate globalContext key_pair sec_key_ptr             if isSuccess ret then Just <$> f key_pair else return Nothing       create `finally` fillBytes key_pair 0 96  -- | Import a 32-byte BIP-340 x-only public key: the x coordinate of a point. -- The result is the point with that x coordinate and an even y coordinate, -- as BIP-340 defines. 'Nothing' if no point has that x coordinate.-importXOnlyPubKey :: Ctx -> ByteString -> Maybe PubKey-importXOnlyPubKey ctx bs-  | BS.length bs == 32 = importPubKey ctx (BS.cons 0x02 bs)+importXOnlyPubKey :: ByteString -> Maybe PubKey+importXOnlyPubKey bs+  | BS.length bs == 32 = importPubKey (BS.cons 0x02 bs)   | otherwise = Nothing  -- | Export a public key as a 32-byte BIP-340 x-only public key: its x -- coordinate. A key and its negation have the same x-only form.-exportXOnlyPubKey :: Ctx -> PubKey -> ByteString-exportXOnlyPubKey (Ctx fctx) (PubKey pub_key) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx -> do-    out <- withXOnlyPubKey ctx pub_key $ \xonly_ptr ->+exportXOnlyPubKey :: PubKey -> ByteString+exportXOnlyPubKey (PubKey pub_key) =+  unsafePerformIO $ do+    out <- withXOnlyPubKey pub_key $ \xonly_ptr ->       fillOutput 32 $ \out_ptr -> do-        ret <- xOnlyPubKeySerialize ctx out_ptr xonly_ptr+        ret <- xOnlyPubKeySerialize globalContext out_ptr xonly_ptr         unless (isSuccess ret) $ error "could not serialize x-only public key"     maybe (error "could not serialize x-only public key") return out @@ -724,39 +762,39 @@ -- -- As BIP-340 requires, the signature is verified before it is returned, and -- an error is raised if that fails.-signSchnorr :: Ctx -> SecKey -> Msg -> SchnorrSig-signSchnorr ctx key m = signSchnorrInternal ctx key m Nothing+signSchnorr :: SecKey -> Msg -> SchnorrSig+signSchnorr key m = signSchnorrInternal key m Nothing  -- | Sign a message hash with BIP-340 and the given 32 bytes of auxiliary -- randomness. 'Nothing' if the randomness is not 32 bytes long. The -- signature is verified before it is returned, as in 'signSchnorr'.-signSchnorrWithAux :: Ctx -> SecKey -> Msg -> ByteString -> Maybe SchnorrSig-signSchnorrWithAux ctx key m aux-  | BS.length aux == 32 = Just (signSchnorrInternal ctx key m (Just aux))+signSchnorrWithAux :: SecKey -> Msg -> ByteString -> Maybe SchnorrSig+signSchnorrWithAux key m aux+  | BS.length aux == 32 = Just (signSchnorrInternal key m (Just aux))   | otherwise = Nothing  -- | Sign a message hash with BIP-340 and fresh auxiliary randomness from the -- system, as BIP-340 recommends. The signature is different each time. It is -- verified before it is returned, as in 'signSchnorr'.-signSchnorrIO :: (MonadIO m) => Ctx -> SecKey -> Msg -> m SchnorrSig-signSchnorrIO ctx key m = liftIO $ do+signSchnorrIO :: (MonadIO m) => SecKey -> Msg -> m SchnorrSig+signSchnorrIO key m = liftIO $ do   aux <- getEntropy 32-  evaluate (signSchnorrInternal ctx key m (Just aux))+  evaluate (signSchnorrInternal key m (Just aux))  -- | Sign with optional auxiliary randomness, then verify the signature with -- the key pair that made it. BIP-340 makes that check the last step of -- signing, so that a signature corrupted by a fault in the signer never -- leaves it. Bitcoin Core does the same.-signSchnorrInternal :: Ctx -> SecKey -> Msg -> Maybe ByteString -> SchnorrSig-signSchnorrInternal (Ctx fctx) (SecKey sec_key) (Msg m) aux =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+signSchnorrInternal :: SecKey -> Msg -> Maybe ByteString -> SchnorrSig+signSchnorrInternal (SecKey sec_key) (Msg m) aux =+  unsafePerformIO $     useFixedByteString "Msg" 32 m $ \(msg_ptr, _) ->       withAux $ \aux_ptr -> do-        out <- withKeyPair ctx sec_key $ \key_pair ->+        out <- withKeyPair sec_key $ \key_pair ->           withOutput 64 $ \sig_ptr -> do-            ret <- schnorrSigSign32 ctx sig_ptr msg_ptr key_pair aux_ptr+            ret <- schnorrSigSign32 globalContext sig_ptr msg_ptr key_pair aux_ptr             if isSuccess ret-              then verifyFreshSignature ctx key_pair sig_ptr (castPtr msg_ptr)+              then verifyFreshSignature key_pair sig_ptr (castPtr msg_ptr)               else return False         case out of           Nothing -> error "could not sign message"@@ -770,24 +808,24 @@ -- | Verify a signature that a key pair just made, with the x-only public key -- of that key pair. The message is 32 bytes. verifyFreshSignature ::-  Ptr LCtx -> Ptr KeyPair96 -> Ptr SchnorrSig64 -> Ptr CUChar -> IO Bool-verifyFreshSignature ctx key_pair sig_ptr msg_ptr =+  Ptr KeyPair96 -> Ptr SchnorrSig64 -> Ptr CUChar -> IO Bool+verifyFreshSignature key_pair sig_ptr msg_ptr =   allocaBytes 64 $ \xonly_ptr -> do-    ret <- keyPairXOnlyPub ctx xonly_ptr nullPtr key_pair+    ret <- keyPairXOnlyPub globalContext xonly_ptr nullPtr key_pair     if isSuccess ret-      then isSuccess <$> schnorrSigVerify ctx sig_ptr msg_ptr 32 xonly_ptr+      then isSuccess <$> schnorrSigVerify globalContext sig_ptr msg_ptr 32 xonly_ptr       else return False  -- | Verify a BIP-340 signature of a message hash. Only the x coordinate of -- the public key is used, so a key and its negation verify the same -- signatures. 'True' means that the signature is correct.-verifySchnorr :: Ctx -> PubKey -> SchnorrSig -> Msg -> Bool-verifySchnorr (Ctx fctx) (PubKey pub_key) (SchnorrSig sig_bs) (Msg m) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+verifySchnorr :: PubKey -> SchnorrSig -> Msg -> Bool+verifySchnorr (PubKey pub_key) (SchnorrSig sig_bs) (Msg m) =+  unsafePerformIO $     useFixedByteString "SchnorrSig" 64 sig_bs $ \(sig_ptr, _) ->       useFixedByteString "Msg" 32 m $ \(msg_ptr, msg_len) ->-        fmap (fromMaybe False) . withXOnlyPubKey ctx pub_key $ \xonly_ptr ->-          isSuccess <$> schnorrSigVerify ctx sig_ptr msg_ptr msg_len xonly_ptr+        fmap (fromMaybe False) . withXOnlyPubKey pub_key $ \xonly_ptr ->+          isSuccess <$> schnorrSigVerify globalContext sig_ptr msg_ptr msg_len xonly_ptr  -- | Add a tweak to the x-only form of a public key: @P + t·G@, where @P@ is -- the point with the key's x coordinate and an even y coordinate. This is@@ -796,29 +834,28 @@ -- of its y coordinate goes into the control block of a script path spend. -- 'Nothing' if the result is the point at infinity, or for a raw 'Tweak' that -- is not below the curve order.-tweakAddXOnlyPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey-tweakAddXOnlyPubKey (Ctx fctx) (PubKey pub_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakAddXOnlyPubKey :: PubKey -> Tweak -> Maybe PubKey+tweakAddXOnlyPubKey (PubKey pub_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->-      fmap join . withXOnlyPubKey ctx pub_key $ \xonly_ptr ->+      fmap join . withXOnlyPubKey pub_key $ \xonly_ptr ->         (fmap . fmap) PubKey . withOutput 64 $ \out ->-          isSuccess <$> xOnlyPubKeyTweakAdd ctx out xonly_ptr tweak_ptr+          isSuccess <$> xOnlyPubKeyTweakAdd globalContext out xonly_ptr tweak_ptr  -- | Add a tweak to a secret key the way 'tweakAddXOnlyPubKey' adds it to the -- public key: the secret key is negated first when its public key has an odd -- y coordinate, then the tweak is added. The result signs for the Taproot -- output of 'tweakAddXOnlyPubKey' in a key path spend. 'Nothing' if the -- result is zero, or for a raw 'Tweak' that is not below the curve order.-tweakAddXOnlySecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey-tweakAddXOnlySecKey (Ctx fctx) (SecKey sec_key) (Tweak t) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+tweakAddXOnlySecKey :: SecKey -> Tweak -> Maybe SecKey+tweakAddXOnlySecKey (SecKey sec_key) (Tweak t) =+  unsafePerformIO $     useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->-      fmap join . withKeyPair ctx sec_key $ \key_pair -> do-        ret <- keyPairXOnlyTweakAdd ctx key_pair tweak_ptr+      fmap join . withKeyPair sec_key $ \key_pair -> do+        ret <- keyPairXOnlyTweakAdd globalContext key_pair tweak_ptr         if isSuccess ret-          then-            (fmap . fmap) SecKey . withOutput 32 $ \out ->-              isSuccess <$> keyPairSec ctx out key_pair+          then (fmap . fmap) SecKey . withOutput 32 $ \out ->+            isSuccess <$> keyPairSec globalContext out key_pair           else return Nothing  instance Arbitrary Msg where
src/Crypto/Secp256k1/Internal/BaseOps.hs view
@@ -5,15 +5,19 @@ -- bindings are @safe@ calls: signing and verifying take tens of microseconds, -- and a @safe@ call lets other Haskell threads run meanwhile. Never call these -- directly with unchecked inputs; "Crypto.Secp256k1.Internal.Base" validates--- lengths and contents first. This module is internal and has no API--- stability guarantee.+-- lengths and contents first.+--+-- Every function takes a context pointer, and the package passes its global+-- context. Because of that argument this module is hidden: the package+-- exposes nothing that makes, takes or names a context. Only the package+-- itself and its tests can call these bindings. module Crypto.Secp256k1.Internal.BaseOps where +import Crypto.Secp256k1.Internal.ContextOps (LCtx) import Crypto.Secp256k1.Internal.ForeignTypes   ( AuxRand32,     Compact64,     KeyPair96,-    LCtx,     Msg32,     NonceFun,     PubKey64,
src/Crypto/Secp256k1/Internal/Context.hs view
@@ -1,160 +1,99 @@-{-# LANGUAGE NoFieldSelectors #-}---- | Internal module. Everything is exported and there is no API stability--- guarantee. In particular 'contextDestroy' is here for add-on packages and--- tests that manage raw context pointers. Never call it on the pointer inside--- a 'Ctx', because the garbage collector will destroy that one again.-module Crypto.Secp256k1.Internal.Context where+-- | The one libsecp256k1 context of the process.+--+-- == Purpose+--+-- Every function of libsecp256k1 takes a context: an object that holds the+-- callbacks for errors and the random blinding values that protect secret key+-- operations against side-channel leakage. Earlier versions of this package+-- made the caller create one and pass it to every function. That argument+-- carried no information, since any context gives the same results, yet it+-- ran through every signature of every program built on the package. Now the+-- package keeps a single context here and uses it for everything.+--+-- == Design+--+-- * __Created on first use.__ 'globalContext' is a top-level value, so the+--   runtime evaluates it once, the first time a function needs it, and every+--   later use gets the same pointer. 'unsafePerformIO' takes a lock on the+--   value while it runs (@unsafeDupablePerformIO@ does not), so two threads+--   that arrive together cannot both create a context. The @NOINLINE@ pragma+--   keeps the compiler from copying the definition to its uses, which would+--   make a context per use.+--+-- * __Randomized once, then read-only.__ The context is seeded with 32 bytes+--   from the operating system before anything else can see it, which is what+--   libsecp256k1 recommends. After that nothing writes to it, and the C+--   library allows any number of threads to read one context at once. This is+--   why there is no way to randomize it again: that writes to the context+--   while other threads may be reading it, which is a data race, and guarding+--   against it would put a lock around every operation.+--+-- * __Never aborts.__ The illegal-argument callback is replaced with one that+--   does nothing (see @cbits/illegal_callback.c@), so an invalid argument+--   makes a C function return 0 instead of aborting the process. Two rules+--   follow for every binding that uses the context. The return value of the C+--   function must always be checked, because after a failed check its outputs+--   are undefined. And a C function that ignores the result of an internal+--   check must get validated inputs, as 'Crypto.Secp256k1.combinePubKeys'+--   does for @secp256k1_ec_pubkey_combine@.+--+-- * __Never destroyed.__ The context lives as long as the process, like any+--   other global, so it has no finalizer. The operating system reclaims it at+--   exit.+--+-- * __Hidden.__ This module is not exposed by the package. If the pointer+--   could be reached from outside, any code could randomize or destroy the+--   context, or change its callbacks, under every other user of it. The+--   modules with the raw bindings, which take a context pointer, and the one+--   that creates contexts are hidden as well, so no code outside the package+--   can make, hold or name a context at all.+--+-- == What is given up+--+-- A program can no longer have several contexts, for example one per thread+-- or one per secret, and it can no longer refresh the blinding during a long+-- run. Neither changes any result. The blinding is defence in depth on top+-- of code that is already constant-time, and seeding it once per process is+-- what the C library asks for.+module Crypto.Secp256k1.Internal.Context (globalContext) where -import Control.Exception (mask_)-import Control.Monad (unless)-import Crypto.Secp256k1.Internal.ForeignTypes-  ( CtxFlags,-    LCtx,-    Ret,-    Seed32,-    isSuccess,+import Control.Exception (mask_, onException)+import Control.Monad (unless, when)+import Crypto.Secp256k1.Internal.ContextOps+  ( LCtx,+    contextCreate,+    contextDestroy,+    contextRandomize,+    illegalCallbackFunPtr,+    setIllegalCallback,+    signVerify,   )+import Crypto.Secp256k1.Internal.ForeignTypes (isSuccess) import Crypto.Secp256k1.Internal.Util (withRandomSeed)-import Foreign (FunPtr, Ptr, nullPtr)-import Foreign.C (CInt (..), CString, CUInt (..))-import Foreign.ForeignPtr-  ( ForeignPtr,-    newForeignPtr,-    withForeignPtr,-  )+import Foreign (Ptr, nullPtr) import System.IO.Unsafe (unsafePerformIO) --- | A libsecp256k1 context. It is destroyed by the garbage collector.+-- | The context that every binding of the package uses. It is created,+-- given the illegal-argument callback that does nothing, and randomized the+-- first time it is needed, and it is only read from then on, so any number of+-- threads may use it at once. See the module header for why it is built this+-- way. ----- A context can be shared between threads. Every function in--- "Crypto.Secp256k1" only reads it, except 'randomizeContext', which needs--- exclusive access. See there.-data Ctx = Ctx (ForeignPtr LCtx)---- | Re-seed the blinding values that protect secret key operations against--- side-channel leakage. 'createContext' already does this once, which is what--- libsecp256k1 recommends, so most programs never need to call it.+-- Bindings must only pass it to C functions that take a @const@ context.+-- Never pass it to @secp256k1_context_randomize@,+-- @secp256k1_context_destroy@ or a function that sets a callback. ----- This function modifies the context. Calling it while another thread uses--- the same context, for example by evaluating 'Crypto.Secp256k1.signMsg', is a--- data race in the C library. Either call it before the context is shared, or--- protect every use of the context with a read-write lock.-randomizeContext :: Ctx -> IO ()-randomizeContext (Ctx fctx) = withForeignPtr fctx $ \ctx -> do-  ret <- withRandomSeed $ contextRandomize ctx-  unless (isSuccess ret) $ error "Could not randomize context"---- | Create a context and randomize it.-createContext :: IO Ctx-createContext = do-  ctx <- mask_ $ contextCreate signVerify >>= wrapContext-  randomizeContext ctx+-- If the context cannot be created or randomized, for example because the+-- operating system gives no entropy, the error is raised by the function that+-- needed the context, and again by every later one.+globalContext :: Ptr LCtx+globalContext = unsafePerformIO . mask_ $ do+  ctx <- contextCreate signVerify+  when (ctx == nullPtr) $ error "Could not create secp256k1 context"+  setIllegalCallback ctx illegalCallbackFunPtr nullPtr+  ret <- withRandomSeed (contextRandomize ctx) `onException` contextDestroy ctx+  unless (isSuccess ret) $ do+    contextDestroy ctx+    error "Could not randomize secp256k1 context"   return ctx---- | Copy a context, including its randomization.-cloneContext :: Ctx -> IO Ctx-cloneContext (Ctx fctx) =-  withForeignPtr fctx $ \ctx -> mask_ $ contextClone ctx >>= wrapContext---- | Create a context and pass it to the action. The context is not destroyed--- when the action returns. It stays valid for as long as it is referenced,--- and the garbage collector destroys it afterwards.-withContext :: (Ctx -> IO a) -> IO a-withContext = (createContext >>=)---- | Wrap a raw context pointer. The illegal-argument callback is replaced--- with one that does nothing (see @cbits/illegal_callback.c@), so an invalid--- argument makes the C function return 0 instead of aborting the process.------ Two rules follow for every binding that uses a 'Ctx'. The return value of--- the C function must always be checked, because after a failed check its--- outputs are undefined. And a C function that ignores the result of an--- internal check must get validated inputs, as--- 'Crypto.Secp256k1.combinePubKeys' does for @secp256k1_ec_pubkey_combine@.-wrapContext :: Ptr LCtx -> IO Ctx-wrapContext pctx = do-  setIllegalCallback pctx illegalCallbackFunPtr nullPtr-  Ctx <$> newForeignPtr contextDestroyFunPtr pctx---- | Context used to validate values that are built without a context, such--- as public keys and signatures read from their internal representation or--- from a string. It is only used for parsing and serialization, which do not--- involve secret keys and so do not need randomization. It is never modified--- after creation, so sharing it between threads is safe.-validationContext :: Ctx-validationContext =-  unsafePerformIO . mask_ $ contextCreate none >>= wrapContext-{-# NOINLINE validationContext #-}---- | @SECP256K1_CONTEXT_NONE@. Enough for every operation since libsecp256k1--- 0.2.0, and for parsing and serialization in older versions.-none :: CtxFlags-none = 0x0001---- | @SECP256K1_CONTEXT_VERIFY@. Deprecated upstream since 0.2.0, where it--- means the same as 'none'. Older libraries need it to verify.-verify :: CtxFlags-verify = 0x0101---- | @SECP256K1_CONTEXT_SIGN@. Deprecated upstream since 0.2.0, where it means--- the same as 'none'. Older libraries need it to sign.-sign :: CtxFlags-sign = 0x0201---- | Both 'sign' and 'verify', passed by 'createContext'. The package requires--- libsecp256k1 0.2.0 or later for its Schnorr bindings, and from that version--- on these flags mean the same as 'none'. Passing them is harmless.-signVerify :: CtxFlags-signVerify = 0x0301---- | Binding to @secp256k1_context_create@.-foreign import ccall safe "secp256k1.h secp256k1_context_create"-  contextCreate ::-    CtxFlags ->-    IO (Ptr LCtx)---- | Binding to @secp256k1_context_clone@.-foreign import ccall safe "secp256k1.h secp256k1_context_clone"-  contextClone ::-    Ptr LCtx ->-    IO (Ptr LCtx)---- | Binding to @secp256k1_context_destroy@.-foreign import ccall safe "secp256k1.h secp256k1_context_destroy"-  contextDestroy :: Ptr LCtx -> IO ()---- | Pointer to @secp256k1_context_destroy@, for use as a finalizer or callback.-foreign import ccall safe "secp256k1.h &secp256k1_context_destroy"-  contextDestroyFunPtr :: FunPtr (Ptr LCtx -> IO ())---- | Pointer to @secp256k1_haskell_illegal_callback@, for use as a finalizer or callback.-foreign import ccall safe "&secp256k1_haskell_illegal_callback"-  illegalCallbackFunPtr :: FunPtr (CString -> Ptr a -> IO ())---- | Binding to @secp256k1_context_set_illegal_callback@.-foreign import ccall safe "secp256k1.h secp256k1_context_set_illegal_callback"-  setIllegalCallback ::-    Ptr LCtx ->-    -- | message, data-    FunPtr (CString -> Ptr a -> IO ()) ->-    -- | data-    Ptr a ->-    IO ()---- | Binding to @secp256k1_context_set_error_callback@.-foreign import ccall safe "secp256k1.h secp256k1_context_set_error_callback"-  setErrorCallback ::-    Ptr LCtx ->-    -- | message, data-    FunPtr (CString -> Ptr a -> IO ()) ->-    -- | data-    Ptr a ->-    IO ()---- | Binding to @secp256k1_context_randomize@.-foreign import ccall safe "secp256k1.h secp256k1_context_randomize"-  contextRandomize ::-    Ptr LCtx ->-    Ptr Seed32 ->-    IO Ret+{-# NOINLINE globalContext #-}
+ src/Crypto/Secp256k1/Internal/ContextOps.hs view
@@ -0,0 +1,107 @@+-- | Foreign imports for creating and managing libsecp256k1 contexts, and the+-- flags they take.+--+-- The package needs these only once, to make its global context in+-- "Crypto.Secp256k1.Internal.Context". The tests also use them, to exercise+-- the raw bindings of "Crypto.Secp256k1.Internal.BaseOps" on contexts of+-- their own.+--+-- This module is hidden: the package does not expose it, nor any other+-- module that makes, takes or names a context. The owner's decision is that+-- the one global context is the only context there is, so the library offers+-- no way to create another. The price is that code outside the package can+-- no longer call the raw bindings; it uses the validated functions of+-- "Crypto.Secp256k1" instead.+--+-- 'contextRandomize' and the two callback setters modify a context, so they+-- need exclusive access to it. They must never be given the global context+-- after its creation.+module Crypto.Secp256k1.Internal.ContextOps where++import Crypto.Secp256k1.Internal.ForeignTypes (Ret, Seed32)+import Foreign (FunPtr, Ptr)+import Foreign.C (CInt (..), CString, CUInt (..))++-- | Context (@secp256k1_context@). Only ever used behind a 'Ptr'. It is+-- declared here and not with the other foreign types so that no exposed+-- module can name a context.+data LCtx++-- | Flags passed to @secp256k1_context_create@.+type CtxFlags = CUInt++-- | @SECP256K1_CONTEXT_NONE@. Enough for every operation since libsecp256k1+-- 0.2.0, and for parsing and serialization in older versions.+none :: CtxFlags+none = 0x0001++-- | @SECP256K1_CONTEXT_VERIFY@. Deprecated upstream since 0.2.0, where it+-- means the same as 'none'. Older libraries need it to verify.+verify :: CtxFlags+verify = 0x0101++-- | @SECP256K1_CONTEXT_SIGN@. Deprecated upstream since 0.2.0, where it means+-- the same as 'none'. Older libraries need it to sign.+sign :: CtxFlags+sign = 0x0201++-- | Both 'sign' and 'verify', which the global context of the package is+-- created with. The package requires libsecp256k1 0.2.0 or later for its+-- Schnorr bindings, and from that version on these flags mean the same as+-- 'none'. Passing them is harmless.+signVerify :: CtxFlags+signVerify = 0x0301++-- | Binding to @secp256k1_context_create@.+foreign import ccall safe "secp256k1.h secp256k1_context_create"+  contextCreate ::+    CtxFlags ->+    IO (Ptr LCtx)++-- | Binding to @secp256k1_context_clone@.+foreign import ccall safe "secp256k1.h secp256k1_context_clone"+  contextClone ::+    Ptr LCtx ->+    IO (Ptr LCtx)++-- | Binding to @secp256k1_context_destroy@.+foreign import ccall safe "secp256k1.h secp256k1_context_destroy"+  contextDestroy :: Ptr LCtx -> IO ()++-- | Pointer to @secp256k1_context_destroy@, for use as a finalizer or callback.+foreign import ccall safe "secp256k1.h &secp256k1_context_destroy"+  contextDestroyFunPtr :: FunPtr (Ptr LCtx -> IO ())++-- | Pointer to @secp256k1_haskell_illegal_callback@ (see+-- @cbits/illegal_callback.c@), a callback that does nothing. Set as the+-- illegal-argument callback of a context, it makes a C function that is given+-- an invalid argument return 0 instead of aborting the process.+foreign import ccall safe "&secp256k1_haskell_illegal_callback"+  illegalCallbackFunPtr :: FunPtr (CString -> Ptr a -> IO ())++-- | Binding to @secp256k1_context_set_illegal_callback@.+foreign import ccall safe "secp256k1.h secp256k1_context_set_illegal_callback"+  setIllegalCallback ::+    Ptr LCtx ->+    -- | message, data+    FunPtr (CString -> Ptr a -> IO ()) ->+    -- | data+    Ptr a ->+    IO ()++-- | Binding to @secp256k1_context_set_error_callback@.+foreign import ccall safe "secp256k1.h secp256k1_context_set_error_callback"+  setErrorCallback ::+    Ptr LCtx ->+    -- | message, data+    FunPtr (CString -> Ptr a -> IO ()) ->+    -- | data+    Ptr a ->+    IO ()++-- | Binding to @secp256k1_context_randomize@.+foreign import ccall safe "secp256k1.h secp256k1_context_randomize"+  contextRandomize ::+    Ptr LCtx ->+    Ptr Seed32 ->+    IO Ret
src/Crypto/Secp256k1/Internal/ForeignTypes.hs view
@@ -10,9 +10,6 @@ import Foreign (Ptr) import Foreign.C (CInt (..), CUChar, CUInt (..)) --- | Context (@secp256k1_context@).-data LCtx- -- | Public key (@secp256k1_pubkey@), 64 bytes. data PubKey64 @@ -48,9 +45,6 @@  -- | Auxiliary randomness for BIP-340 signing, 32 bytes. data AuxRand32---- | Flags passed to @secp256k1_context_create@.-type CtxFlags = CUInt  -- | Flags passed to @secp256k1_ec_pubkey_serialize@. type SerFlags = CUInt
src/Crypto/Secp256k1/Internal/Recovery.hs view
@@ -16,6 +16,9 @@ -- does not check the content. A raw 'RecSig' with invalid content makes -- functions return 'Nothing', a value that does not verify, or throw, never -- abort or read outside a buffer.+--+-- As in "Crypto.Secp256k1.Internal.Base", every function uses the global+-- context of the package and none takes one. module Crypto.Secp256k1.Internal.Recovery where  import Control.DeepSeq (NFData)@@ -28,7 +31,7 @@     Sig (..),     hasNonZeroComponents,   )-import Crypto.Secp256k1.Internal.Context (Ctx (..), validationContext)+import Crypto.Secp256k1.Internal.Context (globalContext) import Crypto.Secp256k1.Internal.ForeignTypes (isSuccess) import Crypto.Secp256k1.Internal.RecoveryOps   ( ecdsaRecover,@@ -51,7 +54,7 @@ import Data.Maybe (fromMaybe) import Data.String (IsString (..)) import Data.Word (Word8)-import Foreign (alloca, allocaBytes, nullFunPtr, nullPtr, peek, withForeignPtr)+import Foreign (alloca, allocaBytes, nullFunPtr, nullPtr, peek) import GHC.Generics (Generic) import System.IO.Unsafe (unsafePerformIO) import Text.Read@@ -96,14 +99,14 @@ recSigToEncoding :: RecSig -> ByteString recSigToEncoding rs = compact.get `BS.snoc` rec_id   where-    (compact, rec_id) = exportCompactRecSig validationContext rs+    (compact, rec_id) = exportCompactRecSig rs --- | Parse the 65-byte encoding of 'recSigToEncoding' without a--- caller-provided context. Used by the 'Read' and 'IsString' instances.+-- | Parse the 65-byte encoding of 'recSigToEncoding'. Used by the 'Read' and+-- 'IsString' instances. recSigFromEncoding :: ByteString -> Maybe RecSig recSigFromEncoding bs = do   guard (BS.length bs == 65)-  importCompactRecSig validationContext (CompactSig (BS.take 64 bs)) (BS.last bs)+  importCompactRecSig (CompactSig (BS.take 64 bs)) (BS.last bs)  -- | Import a recoverable signature from the bytes of its internal -- representation, as found in the @get@ field of a 'RecSig' on the same@@ -127,43 +130,40 @@ isCanonicalRecSig bs =   BS.length bs == 65     && unsafePerformIO-      ( withForeignPtr fctx $ \ctx ->-          unsafeUseByteString bs $ \(rec_sig_ptr, _) ->-            allocaBytes 64 $ \compact_ptr ->-              alloca $ \rec_id_ptr -> do-                ret <--                  ecdsaRecoverableSignatureSerializeCompact-                    ctx-                    compact_ptr-                    rec_id_ptr-                    rec_sig_ptr-                if not (isSuccess ret)-                  then return False-                  else do-                    rec_id <- peek rec_id_ptr-                    compact <- packByteString (compact_ptr, 64)-                    parsed <- withOutput 65 $ \out ->-                      isSuccess-                        <$> ecdsaRecoverableSignatureParseCompact ctx out compact_ptr rec_id-                    return (parsed == Just bs && hasNonZeroComponents compact)+      ( unsafeUseByteString bs $ \(rec_sig_ptr, _) ->+          allocaBytes 64 $ \compact_ptr ->+            alloca $ \rec_id_ptr -> do+              ret <-+                ecdsaRecoverableSignatureSerializeCompact+                  globalContext+                  compact_ptr+                  rec_id_ptr+                  rec_sig_ptr+              if not (isSuccess ret)+                then return False+                else do+                  rec_id <- peek rec_id_ptr+                  compact <- packByteString (compact_ptr, 64)+                  parsed <- withOutput 65 $ \out ->+                    isSuccess+                      <$> ecdsaRecoverableSignatureParseCompact globalContext out compact_ptr rec_id+                  return (parsed == Just bs && hasNonZeroComponents compact)       )-  where-    Ctx fctx = validationContext  -- | Sign a message hash and keep the recovery id. The nonce comes from RFC -- 6979, so the same key and hash always give the same signature, and r and s -- are those of 'Crypto.Secp256k1.signMsg', in lower-S form. There is no low-R -- grinding. Bitcoin Core does not grind when it signs a message with -- @SignCompact@ either, so the signatures are the same as Bitcoin Core's.-signRecMsg :: Ctx -> SecKey -> Msg -> RecSig-signRecMsg (Ctx fctx) (SecKey sec_key) (Msg m) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+signRecMsg :: SecKey -> Msg -> RecSig+signRecMsg (SecKey sec_key) (Msg m) =+  unsafePerformIO $     useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) ->       useFixedByteString "Msg" 32 m $ \(msg_ptr, _) -> do         -- A null nonce function selects the RFC 6979 default.         out <- withOutput 65 $ \rec_sig_ptr ->           isSuccess-            <$> ecdsaSignRecoverable ctx rec_sig_ptr msg_ptr sec_key_ptr nullFunPtr nullPtr+            <$> ecdsaSignRecoverable globalContext rec_sig_ptr msg_ptr sec_key_ptr nullFunPtr nullPtr         maybe (error "could not sign message") (return . RecSig) out  -- | The public key that made a signature of a message hash. 'Nothing' when no@@ -176,51 +176,51 @@ -- same key. Bitcoin Core accepts such message signatures too. Where the rule -- matters, check 'Crypto.Secp256k1.isLowS' on 'convertRecSig'. The hash is -- reduced modulo the curve order, as 'Crypto.Secp256k1.verifySig' does.-recover :: Ctx -> RecSig -> Msg -> Maybe PubKey-recover (Ctx fctx) (RecSig rec_sig) (Msg m) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+recover :: RecSig -> Msg -> Maybe PubKey+recover (RecSig rec_sig) (Msg m) =+  unsafePerformIO $     useFixedByteString "RecSig" 65 rec_sig $ \(rec_sig_ptr, _) ->       useFixedByteString "Msg" 32 m $ \(msg_ptr, _) ->         (fmap . fmap) PubKey . withOutput 64 $ \pub_key_ptr ->-          isSuccess <$> ecdsaRecover ctx pub_key_ptr rec_sig_ptr msg_ptr+          isSuccess <$> ecdsaRecover globalContext pub_key_ptr rec_sig_ptr msg_ptr  -- | The signature without its recovery id. For a signature from -- 'signRecMsg', this is the signature that 'Crypto.Secp256k1.signMsg' gives.-convertRecSig :: Ctx -> RecSig -> Sig-convertRecSig (Ctx fctx) (RecSig rec_sig) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+convertRecSig :: RecSig -> Sig+convertRecSig (RecSig rec_sig) =+  unsafePerformIO $     useFixedByteString "RecSig" 65 rec_sig $ \(rec_sig_ptr, _) -> do       out <- withOutput 64 $ \sig_ptr ->-        isSuccess <$> ecdsaRecoverableSignatureConvert ctx sig_ptr rec_sig_ptr+        isSuccess <$> ecdsaRecoverableSignatureConvert globalContext sig_ptr rec_sig_ptr       maybe (error "could not convert recoverable signature") (return . Sig) out  -- | Parse a signature from the compact encoding and its recovery id. -- 'Nothing' unless both components are in the range 1 to n−1 and the id is 0 -- to 3. The signature may be in high-S form.-importCompactRecSig :: Ctx -> CompactSig -> Word8 -> Maybe RecSig-importCompactRecSig (Ctx fctx) (CompactSig compact) rec_id = do+importCompactRecSig :: CompactSig -> Word8 -> Maybe RecSig+importCompactRecSig (CompactSig compact) rec_id = do   guard (rec_id <= 3)   -- libsecp256k1 accepts a zero component here and only refuses it in   -- 'recover'. It is rejected here so that 'convertRecSig' always gives a   -- valid 'Sig', as 'Crypto.Secp256k1.importCompactSig' does.   guard (hasNonZeroComponents compact)-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+  unsafePerformIO $     useFixedByteString "CompactSig" 64 compact $ \(compact_ptr, _) ->       (fmap . fmap) RecSig . withOutput 65 $ \out ->         isSuccess-          <$> ecdsaRecoverableSignatureParseCompact ctx out compact_ptr (fromIntegral rec_id)+          <$> ecdsaRecoverableSignatureParseCompact globalContext out compact_ptr (fromIntegral rec_id)  -- | Serialize a signature to the compact encoding and its recovery id. The -- header byte of a Bitcoin signed message is 27 plus the id, plus 4 for a -- compressed key, which the caller adds.-exportCompactRecSig :: Ctx -> RecSig -> (CompactSig, Word8)-exportCompactRecSig (Ctx fctx) (RecSig rec_sig) =-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->+exportCompactRecSig :: RecSig -> (CompactSig, Word8)+exportCompactRecSig (RecSig rec_sig) =+  unsafePerformIO $     useFixedByteString "RecSig" 65 rec_sig $ \(rec_sig_ptr, _) ->       alloca $ \rec_id_ptr -> do         out <- withOutput 64 $ \compact_ptr ->           isSuccess-            <$> ecdsaRecoverableSignatureSerializeCompact ctx compact_ptr rec_id_ptr rec_sig_ptr+            <$> ecdsaRecoverableSignatureSerializeCompact globalContext compact_ptr rec_id_ptr rec_sig_ptr         case out of           Nothing -> error "could not serialize recoverable signature"           Just compact -> do
src/Crypto/Secp256k1/Internal/RecoveryOps.hs view
@@ -2,11 +2,15 @@ -- library only has when it was built with @--enable-module-recovery@. See -- "Crypto.Secp256k1.Recovery". This module is only built when the @recovery@ -- flag of the package is on.+--+-- Like "Crypto.Secp256k1.Internal.BaseOps", it is hidden, because every+-- binding takes a context pointer and the package exposes nothing that makes,+-- takes or names a context. module Crypto.Secp256k1.Internal.RecoveryOps where +import Crypto.Secp256k1.Internal.ContextOps (LCtx) import Crypto.Secp256k1.Internal.ForeignTypes   ( Compact64,-    LCtx,     Msg32,     NonceFun,     PubKey64,
test/Crypto/Secp256k1/Fixtures.hs view
@@ -13,6 +13,7 @@ import Data.String (fromString)  -- * Fixtures+ -- -- Every expected value is a literal from an independent source: the secp256k1 -- generator, the RFC 6979 vector for key 1 and sha256 "Satoshi Nakamoto",@@ -124,5 +125,5 @@ quoted s = "\"" ++ s ++ "\""  -- The negation of a public key: multiplication by n - 1.-negatePubKey :: Ctx -> PubKey -> PubKey-negatePubKey ctx p = fromJust (tweakMulPubKey ctx p (fromString orderMinusOne))+negatePubKey :: PubKey -> PubKey+negatePubKey p = fromJust (tweakMulPubKey p (fromString orderMinusOne))
test/Crypto/Secp256k1/InternalSpec.hs view
@@ -6,7 +6,7 @@ import Control.Monad import Control.Monad.Trans import Crypto.Secp256k1.Internal.BaseOps-import Crypto.Secp256k1.Internal.Context+import Crypto.Secp256k1.Internal.ContextOps import Crypto.Secp256k1.Internal.ForeignTypes import Crypto.Secp256k1.Internal.Util import Data.Base16.Types (assertBase16)
test/Crypto/Secp256k1/RecoverySpec.hs view
@@ -33,7 +33,7 @@ import Text.Read (readMaybe)  spec :: Spec-spec = around withContext $ describe "public key recovery" $ do+spec = describe "public key recovery" $ do   signingSpec   recoverySpec   formulaSpec@@ -130,161 +130,161 @@  -- * Signing -signingSpec :: SpecWith Ctx+signingSpec :: Spec signingSpec = describe "signing" $ do-  it "produces Bitcoin Core's SignCompact signature of sha256d 'Very deterministic message'" $ \ctx ->-    exportCompactRecSig ctx (signRecMsg ctx coreKey coreMsg)+  it "produces Bitcoin Core's SignCompact signature of sha256d 'Very deterministic message'" $+    exportCompactRecSig (signRecMsg coreKey coreMsg)       `shouldBe` (fromString (coreR ++ coreS), coreRecId)-  it "produces Bitcoin Core's signmessage signature of 'Trust no one'" $ \ctx ->-    exportCompactRecSig ctx (signRecMsg ctx messageKey messageHash)+  it "produces Bitcoin Core's signmessage signature of 'Trust no one'" $+    exportCompactRecSig (signRecMsg messageKey messageHash)       `shouldBe` (fromString (messageR ++ messageS), 1)-  it "produces the RFC 6979 vector with recovery id 1" $ \ctx ->-    exportCompactRecSig ctx (signRecMsg ctx keyOne satoshiMsg)+  it "produces the RFC 6979 vector with recovery id 1" $+    exportCompactRecSig (signRecMsg keyOne satoshiMsg)       `shouldBe` (fromString (satoshiR ++ satoshiS), 1)-  it "keeps a high r, as Bitcoin Core's message signing does" $ \ctx -> do-    exportCompactRecSig ctx (signRecMsg ctx keyOne highRMsg)+  it "keeps a high r, as Bitcoin Core's message signing does" $ do+    exportCompactRecSig (signRecMsg keyOne highRMsg)       `shouldBe` (fromString (highRR ++ highRS), 0)-    convertRecSig ctx (signRecMsg ctx keyOne highRMsg) `shouldNotBe` signMsgLowR ctx keyOne highRMsg-  it "signs with the r and s of signMsg" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> convertRecSig ctx (signRecMsg ctx k m) == signMsg ctx k m-  it "is deterministic" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> signRecMsg ctx k m == signRecMsg ctx k m-  it "gives a recovery id of 0 or 1" $ \ctx ->+    convertRecSig (signRecMsg keyOne highRMsg) `shouldNotBe` signMsgLowR keyOne highRMsg+  it "signs with the r and s of signMsg" $+    property $ \(m :: Msg, k :: SecKey) -> convertRecSig (signRecMsg k m) == signMsg k m+  it "is deterministic" $+    property $ \(m :: Msg, k :: SecKey) -> signRecMsg k m == signRecMsg k m+  it "gives a recovery id of 0 or 1" $     -- The ids 2 and 3 need r below p - n, about one signature in 2^128.     property $ \(m :: Msg, k :: SecKey) ->-      snd (exportCompactRecSig ctx (signRecMsg ctx k m)) `elem` [0, 1]-  it "produces lower-S signatures" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> isLowS ctx (convertRecSig ctx (signRecMsg ctx k m))-  it "signs and recovers in parallel" $ \ctx ->+      snd (exportCompactRecSig (signRecMsg k m)) `elem` [0, 1]+  it "produces lower-S signatures" $+    property $ \(m :: Msg, k :: SecKey) -> isLowS (convertRecSig (signRecMsg k m))+  it "signs and recovers in parallel" $     property $ \(xs :: [(Msg, SecKey)]) -> P.runPar $ do-      results <- mapM (P.spawnP . signsAndRecovers ctx) xs+      results <- mapM (P.spawnP . signsAndRecovers) xs       and <$> mapM P.get results   where-    signsAndRecovers ctx (m, k) =-      recover ctx (signRecMsg ctx k m) m == Just (derivePubKey ctx k)+    signsAndRecovers (m, k) =+      recover (signRecMsg k m) m == Just (derivePubKey k)  -- * Recovery -recoverySpec :: SpecWith Ctx+recoverySpec :: Spec recoverySpec = describe "recovery" $ do-  it "recovers the key of Bitcoin Core's SignCompact vector" $ \ctx ->-    recovered ctx (coreR ++ coreS ++ "01") coreMsg `shouldBe` Just corePub-  it "recovers another key with the other recovery id" $ \ctx ->-    recovered ctx (coreR ++ coreS ++ "00") coreMsg `shouldBe` Just coreOtherPub-  it "recovers the signer of Bitcoin Core's 'Trust no one' message" $ \ctx ->-    recovered ctx (messageR ++ messageS ++ "01") messageHash `shouldBe` Just messagePub-  it "recovers G from the RFC 6979 vector" $ \ctx -> do-    recovered ctx (satoshiR ++ satoshiS ++ "01") satoshiMsg `shouldBe` Just genCompressed-    recovered ctx (satoshiR ++ satoshiS ++ "00") satoshiMsg `shouldBe` Just satoshiOtherPub-  it "recovers the signing key" $ \ctx ->+  it "recovers the key of Bitcoin Core's SignCompact vector" $+    recovered (coreR ++ coreS ++ "01") coreMsg `shouldBe` Just corePub+  it "recovers another key with the other recovery id" $+    recovered (coreR ++ coreS ++ "00") coreMsg `shouldBe` Just coreOtherPub+  it "recovers the signer of Bitcoin Core's 'Trust no one' message" $+    recovered (messageR ++ messageS ++ "01") messageHash `shouldBe` Just messagePub+  it "recovers G from the RFC 6979 vector" $ do+    recovered (satoshiR ++ satoshiS ++ "01") satoshiMsg `shouldBe` Just genCompressed+    recovered (satoshiR ++ satoshiS ++ "00") satoshiMsg `shouldBe` Just satoshiOtherPub+  it "recovers the signing key" $     property $ \(m :: Msg, k :: SecKey) ->-      recover ctx (signRecMsg ctx k m) m == Just (derivePubKey ctx k)-  it "recovers a different key for another message" $ \ctx ->+      recover (signRecMsg k m) m == Just (derivePubKey k)+  it "recovers a different key for another message" $     property $ \(m :: Msg, m' :: Msg, k :: SecKey) ->-      m /= m' ==> recover ctx (signRecMsg ctx k m) m' /= Just (derivePubKey ctx k)-  it "recovers the same key from the high-S form with the parity bit flipped" $ \ctx -> do+      m /= m' ==> recover (signRecMsg k m) m' /= Just (derivePubKey k)+  it "recovers the same key from the high-S form with the parity bit flipped" $ do     -- The RFC 6979 vector with s replaced by n - s and the id 1 turned into 0.-    recovered ctx (satoshiR ++ satoshiHighS ++ "00") satoshiMsg `shouldBe` Just genCompressed-    recovered ctx (satoshiR ++ satoshiHighS ++ "01") satoshiMsg `shouldNotBe` Just genCompressed-  it "does not apply the lower-S rule" $ \ctx ->+    recovered (satoshiR ++ satoshiHighS ++ "00") satoshiMsg `shouldBe` Just genCompressed+    recovered (satoshiR ++ satoshiHighS ++ "01") satoshiMsg `shouldNotBe` Just genCompressed+  it "does not apply the lower-S rule" $     property $ \(m :: Msg, k :: SecKey) ->-      let (compact, i) = exportCompactRecSig ctx (signRecMsg ctx k m)+      let (compact, i) = exportCompactRecSig (signRecMsg k m)           (r, s) = BS.splitAt 32 compact.get           -- n - s, through the negation of a tweak.-          highS = (fromJust (tweakNegate ctx (fromJust (tweak s)))).get-          high = fromJust (importCompactRecSig ctx (fromJust (compactSig (r <> highS))) (i `xor` 1))-       in recover ctx high m == Just (derivePubKey ctx k)+          highS = (fromJust (tweakNegate (fromJust (tweak s)))).get+          high = fromJust (importCompactRecSig (fromJust (compactSig (r <> highS))) (i `xor` 1))+       in recover high m == Just (derivePubKey k)   where-    recovered ctx sigHex m = bytesToHex . exportPubKey ctx True <$> recover ctx (fromString sigHex) m+    recovered sigHex m = bytesToHex . exportPubKey True <$> recover (fromString sigHex) m  -- * The formula -formulaSpec :: SpecWith Ctx+formulaSpec :: Spec formulaSpec = describe "the formula Q = r⁻¹(s·R − e·G)" $ do-  it "gives R itself for r = 1, s = 1 and a zero hash" $ \ctx ->-    recovered ctx (one ++ one ++ "00") zero `shouldBe` Just pointOne-  it "takes the parity of y from the recovery id" $ \ctx ->-    recovered ctx (one ++ one ++ "01") zero `shouldBe` Just ("03" ++ one)-  it "reduces the hash modulo n" $ \ctx ->-    recovered ctx (one ++ one ++ "00") order `shouldBe` Just pointOne-  it "subtracts e·G" $ \ctx ->-    recovered ctx (one ++ one ++ "00") one `shouldBe` Just pointOneMinusG-  it "multiplies by s" $ \ctx -> do-    recovered ctx (one ++ two ++ "00") zero `shouldBe` Just twicePointOne-    recovered ctx (one ++ orderMinusOne ++ "00") zero `shouldBe` Just ("03" ++ one)-  it "divides by r" $ \ctx ->-    recovered ctx (two ++ one ++ "02") zero `shouldBe` Just halfPointOrderPlusTwo-  it "uses r + n as the x coordinate for the ids 2 and 3" $ \ctx -> do-    recovered ctx (two ++ two ++ "02") zero `shouldBe` Just ("02" ++ orderPlusTwo)-    recovered ctx (two ++ two ++ "03") zero `shouldBe` Just ("03" ++ orderPlusTwo)-  it "gives nothing when no point has the x coordinate" $ \ctx -> do-    recovered ctx (five ++ one ++ "00") zero `shouldBe` Nothing-    recovered ctx (one ++ one ++ "02") zero `shouldBe` Nothing-    recovered ctx (fieldMinusOrderMinusOne ++ one ++ "02") zero `shouldBe` Nothing-  it "gives nothing when r + n reaches the field size" $ \ctx ->-    recovered ctx (fieldMinusOrder ++ one ++ "02") zero `shouldBe` Nothing-  it "gives nothing when s·R − e·G is the point at infinity" $ \ctx -> do+  it "gives R itself for r = 1, s = 1 and a zero hash" $+    recovered (one ++ one ++ "00") zero `shouldBe` Just pointOne+  it "takes the parity of y from the recovery id" $+    recovered (one ++ one ++ "01") zero `shouldBe` Just ("03" ++ one)+  it "reduces the hash modulo n" $+    recovered (one ++ one ++ "00") order `shouldBe` Just pointOne+  it "subtracts e·G" $+    recovered (one ++ one ++ "00") one `shouldBe` Just pointOneMinusG+  it "multiplies by s" $ do+    recovered (one ++ two ++ "00") zero `shouldBe` Just twicePointOne+    recovered (one ++ orderMinusOne ++ "00") zero `shouldBe` Just ("03" ++ one)+  it "divides by r" $+    recovered (two ++ one ++ "02") zero `shouldBe` Just halfPointOrderPlusTwo+  it "uses r + n as the x coordinate for the ids 2 and 3" $ do+    recovered (two ++ two ++ "02") zero `shouldBe` Just ("02" ++ orderPlusTwo)+    recovered (two ++ two ++ "03") zero `shouldBe` Just ("03" ++ orderPlusTwo)+  it "gives nothing when no point has the x coordinate" $ do+    recovered (five ++ one ++ "00") zero `shouldBe` Nothing+    recovered (one ++ one ++ "02") zero `shouldBe` Nothing+    recovered (fieldMinusOrderMinusOne ++ one ++ "02") zero `shouldBe` Nothing+  it "gives nothing when r + n reaches the field size" $+    recovered (fieldMinusOrder ++ one ++ "02") zero `shouldBe` Nothing+  it "gives nothing when s·R − e·G is the point at infinity" $ do     -- R = G, s = 1 and e = 1: G - G.-    recovered ctx (genX ++ one ++ "00") one `shouldBe` Nothing+    recovered (genX ++ one ++ "00") one `shouldBe` Nothing     -- With e = 2 instead: (G - 2G) / x = -(x⁻¹)·G.-    recovered ctx (genX ++ one ++ "00") two `shouldBe` Just genNegatedOverX+    recovered (genX ++ one ++ "00") two `shouldBe` Just genNegatedOverX   where-    recovered ctx sigHex msgHex =-      bytesToHex . exportPubKey ctx True <$> recover ctx (fromString sigHex) (fromString msgHex)+    recovered sigHex msgHex =+      bytesToHex . exportPubKey True <$> recover (fromString sigHex) (fromString msgHex)  -- * Compact encoding -compactSpec :: SpecWith Ctx+compactSpec :: Spec compactSpec = describe "compact encoding" $ do-  it "imports and exports back the same signature" $ \ctx ->+  it "imports and exports back the same signature" $     property $ \(m :: Msg, k :: SecKey) ->-      let s = signRecMsg ctx k m-          (compact, i) = exportCompactRecSig ctx s-       in importCompactRecSig ctx compact i == Just s-  it "accepts the recovery ids 0 to 3 and rejects 4 and 255" $ \ctx -> do-    forM_ [0 .. 3] $ \i -> importCompactRecSig ctx (fromString (one ++ one)) i `shouldSatisfy` isJust-    importCompactRecSig ctx (fromString (one ++ one)) 4 `shouldBe` Nothing-    importCompactRecSig ctx (fromString (one ++ one)) 255 `shouldBe` Nothing-  it "accepts components of 1 and n - 1 and rejects 0 and n" $ \ctx -> do-    importCompactRecSig ctx (fromString (one ++ one)) 0 `shouldSatisfy` isJust-    importCompactRecSig ctx (fromString (orderMinusOne ++ orderMinusOne)) 0 `shouldSatisfy` isJust-    importCompactRecSig ctx (fromString (order ++ one)) 0 `shouldBe` Nothing-    importCompactRecSig ctx (fromString (one ++ order)) 0 `shouldBe` Nothing-    importCompactRecSig ctx (fromString (zero ++ one)) 0 `shouldBe` Nothing-    importCompactRecSig ctx (fromString (one ++ zero)) 0 `shouldBe` Nothing-  it "imports a high-S signature" $ \ctx ->-    importCompactRecSig ctx (fromString (satoshiR ++ satoshiHighS)) 0 `shouldSatisfy` isJust-  it "converts to the signature without the id" $ \ctx -> do-    bytesToHex (exportSig ctx (convertRecSig ctx (fromString (coreR ++ coreS ++ "01")))) `shouldBe` coreDer-    convertRecSig ctx (fromString (coreR ++ coreS ++ "00"))-      `shouldBe` convertRecSig ctx (fromString (coreR ++ coreS ++ "01"))-  it "converts to a signature that verifies" $ \ctx ->+      let s = signRecMsg k m+          (compact, i) = exportCompactRecSig s+       in importCompactRecSig compact i == Just s+  it "accepts the recovery ids 0 to 3 and rejects 4 and 255" $ do+    forM_ [0 .. 3] $ \i -> importCompactRecSig (fromString (one ++ one)) i `shouldSatisfy` isJust+    importCompactRecSig (fromString (one ++ one)) 4 `shouldBe` Nothing+    importCompactRecSig (fromString (one ++ one)) 255 `shouldBe` Nothing+  it "accepts components of 1 and n - 1 and rejects 0 and n" $ do+    importCompactRecSig (fromString (one ++ one)) 0 `shouldSatisfy` isJust+    importCompactRecSig (fromString (orderMinusOne ++ orderMinusOne)) 0 `shouldSatisfy` isJust+    importCompactRecSig (fromString (order ++ one)) 0 `shouldBe` Nothing+    importCompactRecSig (fromString (one ++ order)) 0 `shouldBe` Nothing+    importCompactRecSig (fromString (zero ++ one)) 0 `shouldBe` Nothing+    importCompactRecSig (fromString (one ++ zero)) 0 `shouldBe` Nothing+  it "imports a high-S signature" $+    importCompactRecSig (fromString (satoshiR ++ satoshiHighS)) 0 `shouldSatisfy` isJust+  it "converts to the signature without the id" $ do+    bytesToHex (exportSig (convertRecSig (fromString (coreR ++ coreS ++ "01")))) `shouldBe` coreDer+    convertRecSig (fromString (coreR ++ coreS ++ "00"))+      `shouldBe` convertRecSig (fromString (coreR ++ coreS ++ "01"))+  it "converts to a signature that verifies" $     property $ \(m :: Msg, k :: SecKey) ->-      verifySig ctx (derivePubKey ctx k) (convertRecSig ctx (signRecMsg ctx k m)) m+      verifySig (derivePubKey k) (convertRecSig (signRecMsg k m)) m  -- * Signature values -valueSpec :: SpecWith Ctx+valueSpec :: Spec valueSpec = describe "signature values" $ do-  it "rebuild from their internal bytes" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> let s = signRecMsg ctx k m in recSig s.get == Just s-  it "reject internal bytes that are not a signature" $ \_ -> do+  it "rebuild from their internal bytes" $+    property $ \(m :: Msg, k :: SecKey) -> let s = signRecMsg k m in recSig s.get == Just s+  it "reject internal bytes that are not a signature" $ do     recSig (BS.replicate 65 0) `shouldBe` Nothing     recSig (BS.replicate 65 0xff) `shouldBe` Nothing     recSig (BS.replicate 64 1) `shouldBe` Nothing     recSig (BS.replicate 66 1) `shouldBe` Nothing-  it "reject an internal recovery id above 3" $ \ctx -> do+  it "reject an internal recovery id above 3" $ do     -- libsecp256k1 keeps the id in the last byte of the representation.-    let bytes = (signRecMsg ctx keyOne satoshiMsg).get+    let bytes = (signRecMsg keyOne satoshiMsg).get     recSig (BS.init bytes `BS.snoc` 4) `shouldBe` Nothing-  it "show r, s and the recovery id in hex" $ \ctx ->-    show (signRecMsg ctx coreKey coreMsg) `shouldBe` quoted (coreR ++ coreS ++ "01")-  it "read that encoding" $ \ctx -> do-    read (quoted (coreR ++ coreS ++ "01")) `shouldBe` signRecMsg ctx coreKey coreMsg-    (fromString (coreR ++ coreS ++ "01") :: RecSig) `shouldBe` signRecMsg ctx coreKey coreMsg-  it "show and read" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> showRead (signRecMsg ctx k m)-  it "do not read an invalid signature" $ \_ -> do+  it "show r, s and the recovery id in hex" $+    show (signRecMsg coreKey coreMsg) `shouldBe` quoted (coreR ++ coreS ++ "01")+  it "read that encoding" $ do+    read (quoted (coreR ++ coreS ++ "01")) `shouldBe` signRecMsg coreKey coreMsg+    (fromString (coreR ++ coreS ++ "01") :: RecSig) `shouldBe` signRecMsg coreKey coreMsg+  it "show and read" $+    property $ \(m :: Msg, k :: SecKey) -> showRead (signRecMsg k m)+  it "do not read an invalid signature" $ do     (readMaybe (quoted (coreR ++ coreS)) :: Maybe RecSig) `shouldBe` Nothing     (readMaybe (quoted (coreR ++ coreS ++ "04")) :: Maybe RecSig) `shouldBe` Nothing     (readMaybe (quoted (zero ++ coreS ++ "01")) :: Maybe RecSig) `shouldBe` Nothing@@ -294,34 +294,34 @@  -- * Values built with the raw constructors of the Internal modules -rawValueSpec :: SpecWith Ctx+rawValueSpec :: Spec rawValueSpec = describe "raw values from the Internal modules" $ do-  it "a signature of 65 zero bytes recovers nothing, instead of aborting the process" $ \ctx ->-    recover ctx (RecSig (BS.replicate 65 0)) satoshiMsg `shouldBe` Nothing-  it "a zero secret key throws instead of signing" $ \ctx ->-    evaluate (signRecMsg ctx (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall-  it "values of the wrong length throw before reaching the library" $ \ctx -> do-    evaluate (signRecMsg ctx (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (signRecMsg ctx keyOne (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (recover ctx (RecSig "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (recover ctx (signRecMsg ctx keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (convertRecSig ctx (RecSig "a")) `shouldThrow` anyErrorCall-    evaluate (exportCompactRecSig ctx (RecSig "a")) `shouldThrow` anyErrorCall-    evaluate (importCompactRecSig ctx (CompactSig "a") 0) `shouldThrow` anyErrorCall+  it "a signature of 65 zero bytes recovers nothing, instead of aborting the process" $+    recover (RecSig (BS.replicate 65 0)) satoshiMsg `shouldBe` Nothing+  it "a zero secret key throws instead of signing" $+    evaluate (signRecMsg (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall+  it "values of the wrong length throw before reaching the library" $ do+    evaluate (signRecMsg (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (signRecMsg keyOne (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (recover (RecSig "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (recover (signRecMsg keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (convertRecSig (RecSig "a")) `shouldThrow` anyErrorCall+    evaluate (exportCompactRecSig (RecSig "a")) `shouldThrow` anyErrorCall+    evaluate (importCompactRecSig (CompactSig "a") 0) `shouldThrow` anyErrorCall     evaluate (length (show (RecSig "a"))) `shouldThrow` anyErrorCall  -- * Derived instances -instanceSpec :: SpecWith Ctx+instanceSpec :: Spec instanceSpec = describe "derived instances" $ do-  it "equal values hash equally, whichever way they were built" $ \ctx ->+  it "equal values hash equally, whichever way they were built" $     property $ \(m :: Msg, k :: SecKey) ->-      let s = signRecMsg ctx k m-          (compact, i) = exportCompactRecSig ctx s-       in hash s == hash (fromJust (importCompactRecSig ctx compact i))+      let s = signRecMsg k m+          (compact, i) = exportCompactRecSig s+       in hash s == hash (fromJust (importCompactRecSig compact i))             && hash s == hash (fromJust (recSig s.get))-  it "can be fully evaluated" $ \ctx ->-    (signRecMsg ctx keyOne satoshiMsg `deepseq` ()) `shouldBe` ()+  it "can be fully evaluated" $+    (signRecMsg keyOne satoshiMsg `deepseq` ()) `shouldBe` ()  #else 
test/Crypto/Secp256k1Spec.hs view
@@ -9,7 +9,6 @@ import Control.DeepSeq (deepseq) import Control.Exception (evaluate) import Control.Monad.Par qualified as P-import Data.Bits (xor) import Crypto.Secp256k1 import Crypto.Secp256k1.Fixtures import Crypto.Secp256k1.Internal.Base@@ -22,6 +21,7 @@     Tweak (Tweak),     signMsgWith,   )+import Data.Bits (xor) import Data.ByteString qualified as BS import Data.Hashable (hash) import Data.Maybe (fromJust, isJust, isNothing)@@ -31,7 +31,7 @@ import Text.Read (readMaybe)  spec :: Spec-spec = around withContext $ do+spec = do   secretKeySpec   publicKeySpec   messageSpec@@ -44,7 +44,6 @@   schnorrSpec   xOnlySpec   taprootSpec-  contextSpec   rawValueSpec   instanceSpec @@ -313,39 +312,44 @@  -- * Secret keys -secretKeySpec :: SpecWith Ctx+secretKeySpec :: Spec secretKeySpec = describe "secret keys" $ do-  it "accepts 1 and n - 1" $ \_ -> do+  it "accepts 1 and n - 1" $ do     secKey (hexToBytes one) `shouldSatisfy` isJust     secKey (hexToBytes orderMinusOne) `shouldSatisfy` isJust-  it "rejects 0, n, n + 1 and 2^256 - 1" $ \_ -> do+  it "rejects 0, n, n + 1 and 2^256 - 1" $ do     secKey (hexToBytes zero) `shouldBe` Nothing     secKey (hexToBytes order) `shouldBe` Nothing     secKey (hexToBytes orderPlusOne) `shouldBe` Nothing     secKey (hexToBytes allOnes) `shouldBe` Nothing-  it "rejects 31 and 33 bytes" $ \_ -> do+  it "rejects 31 and 33 bytes" $ do     secKey (BS.replicate 31 1) `shouldBe` Nothing     secKey (BS.replicate 33 1) `shouldBe` Nothing-  it "keeps the bytes it was given" $ \_ ->-    property $ \(k :: SecKey) -> secKey k.get == Just k-  it "derives the generator from key 1" $ \ctx -> do-    bytesToHex (exportPubKey ctx True (derivePubKey ctx keyOne))+  it "keeps the bytes it was given" $+    property $+      \(k :: SecKey) -> secKey k.get == Just k+  it "derives the generator from key 1" $ do+    bytesToHex (exportPubKey True (derivePubKey keyOne))       `shouldBe` genCompressed-    bytesToHex (exportPubKey ctx False (derivePubKey ctx keyOne))+    bytesToHex (exportPubKey False (derivePubKey keyOne))       `shouldBe` genUncompressed-  it "derives the negated generator from key n - 1" $ \ctx ->+  it "derives the negated generator from key n - 1" $     -- -G has the same x as G and an odd y, so the prefix is 03.-    bytesToHex (exportPubKey ctx True (derivePubKey ctx (fromString orderMinusOne)))+    bytesToHex (exportPubKey True (derivePubKey (fromString orderMinusOne)))       `shouldBe` "0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"-  it "derives the historical public key" $ \ctx ->-    bytesToHex (exportPubKey ctx False (derivePubKey ctx histKey)) `shouldBe` histPub-  it "shows the key in hex" $ \_ ->-    show keyOne `shouldBe` quoted one-  it "shows and reads" $ \_ ->-    property (showRead :: SecKey -> Bool)-  it "reads from a string" $ \_ ->-    property $ \(k :: SecKey) -> fromString (bytesToHex k.get) == k-  it "does not read an invalid key" $ \_ -> do+  it "derives the historical public key" $+    bytesToHex (exportPubKey False (derivePubKey histKey)) `shouldBe` histPub+  it "shows a placeholder instead of the key" $+    property $+      \(k :: SecKey) -> show k == "SecKey <redacted>"+  it "parenthesizes the placeholder inside a larger value" $+    show (Just keyOne) `shouldBe` "Just (SecKey <redacted>)"+  it "reads the key from hex" $+    read (quoted one) `shouldBe` keyOne+  it "reads from a string" $+    property $+      \(k :: SecKey) -> fromString (bytesToHex k.get) == k+  it "does not read an invalid key" $ do     (readMaybe (quoted zero) :: Maybe SecKey) `shouldBe` Nothing     (readMaybe (quoted order) :: Maybe SecKey) `shouldBe` Nothing     (readMaybe (quoted (drop 1 one)) :: Maybe SecKey) `shouldBe` Nothing@@ -354,83 +358,85 @@  -- * Public keys -publicKeySpec :: SpecWith Ctx+publicKeySpec :: Spec publicKeySpec = describe "public keys" $ do-  it "imports the compressed, uncompressed and hybrid encodings of G" $ \ctx -> do-    let g = derivePubKey ctx keyOne-    importPubKey ctx (hexToBytes genCompressed) `shouldBe` Just g-    importPubKey ctx (hexToBytes genUncompressed) `shouldBe` Just g-    importPubKey ctx (hexToBytes genHybrid) `shouldBe` Just g-  it "rejects malformed encodings" $ \ctx -> do-    importPubKey ctx "" `shouldBe` Nothing+  it "imports the compressed, uncompressed and hybrid encodings of G" $ do+    let g = derivePubKey keyOne+    importPubKey (hexToBytes genCompressed) `shouldBe` Just g+    importPubKey (hexToBytes genUncompressed) `shouldBe` Just g+    importPubKey (hexToBytes genHybrid) `shouldBe` Just g+  it "rejects malformed encodings" $ do+    importPubKey "" `shouldBe` Nothing     -- prefix 05 does not exist-    importPubKey ctx (hexToBytes ("05" ++ drop 2 genCompressed)) `shouldBe` Nothing+    importPubKey (hexToBytes ("05" ++ drop 2 genCompressed)) `shouldBe` Nothing     -- x only, no prefix-    importPubKey ctx (hexToBytes (drop 2 genCompressed)) `shouldBe` Nothing+    importPubKey (hexToBytes (drop 2 genCompressed)) `shouldBe` Nothing     -- x and y without a prefix-    importPubKey ctx (hexToBytes (drop 2 genUncompressed)) `shouldBe` Nothing+    importPubKey (hexToBytes (drop 2 genUncompressed)) `shouldBe` Nothing     -- uncompressed prefix on a compressed length-    importPubKey ctx (hexToBytes ("04" ++ drop 2 genCompressed)) `shouldBe` Nothing+    importPubKey (hexToBytes ("04" ++ drop 2 genCompressed)) `shouldBe` Nothing     -- compressed prefix on an uncompressed length-    importPubKey ctx (hexToBytes ("02" ++ drop 2 genUncompressed)) `shouldBe` Nothing-  it "rejects points that are not on the curve" $ \ctx -> do+    importPubKey (hexToBytes ("02" ++ drop 2 genUncompressed)) `shouldBe` Nothing+  it "rejects points that are not on the curve" $ do     -- x = 5 has no point on secp256k1 (x^3 + 7 is not a square mod p).-    importPubKey ctx (hexToBytes ("02" ++ take 62 zero ++ "05")) `shouldBe` Nothing+    importPubKey (hexToBytes ("02" ++ take 62 zero ++ "05")) `shouldBe` Nothing     -- (1, 1) is not on the curve: 1 /= 1 + 7.-    importPubKey ctx (hexToBytes ("04" ++ take 62 zero ++ "01" ++ take 62 zero ++ "01"))+    importPubKey (hexToBytes ("04" ++ take 62 zero ++ "01" ++ take 62 zero ++ "01"))       `shouldBe` Nothing-  it "exports and imports back the same key" $ \ctx ->+  it "exports and imports back the same key" $     property $ \(k :: SecKey, compress :: Bool) ->-      let p = derivePubKey ctx k-       in importPubKey ctx (exportPubKey ctx compress p) == Just p-  it "exports and imports in parallel" $ \ctx ->+      let p = derivePubKey k+       in importPubKey (exportPubKey compress p) == Just p+  it "exports and imports in parallel" $     property $ \(ks :: [(SecKey, Bool)]) -> P.runPar $ do-      results <- mapM (P.spawnP . roundTrip ctx) ks+      results <- mapM (P.spawnP . roundTrip) ks       and <$> mapM P.get results-  it "rebuilds a key from its internal bytes" $ \ctx ->-    property $ \(k :: SecKey) -> let p = derivePubKey ctx k in pubKey p.get == Just p-  it "rejects internal bytes that are not a point" $ \_ -> do+  it "rebuilds a key from its internal bytes" $+    property $+      \(k :: SecKey) -> let p = derivePubKey k in pubKey p.get == Just p+  it "rejects internal bytes that are not a point" $ do     pubKey (BS.replicate 64 0) `shouldBe` Nothing     pubKey (BS.replicate 64 1) `shouldBe` Nothing     pubKey (BS.replicate 64 0xff) `shouldBe` Nothing     pubKey (BS.pack [1 .. 64]) `shouldBe` Nothing     pubKey (BS.replicate 63 1) `shouldBe` Nothing-  it "shows the compressed encoding" $ \ctx ->-    show (derivePubKey ctx keyOne) `shouldBe` quoted genCompressed-  it "reads any encoding" $ \ctx -> do-    let g = derivePubKey ctx keyOne+  it "shows the compressed encoding" $+    show (derivePubKey keyOne) `shouldBe` quoted genCompressed+  it "reads any encoding" $ do+    let g = derivePubKey keyOne     read (quoted genCompressed) `shouldBe` g     read (quoted genUncompressed) `shouldBe` g     read (quoted genHybrid) `shouldBe` g     (fromString genUncompressed :: PubKey) `shouldBe` g-  it "shows and reads" $ \ctx ->-    property $ \(k :: SecKey) -> showRead (derivePubKey ctx k)-  it "does not read an invalid key" $ \_ -> do+  it "shows and reads" $+    property $+      \(k :: SecKey) -> showRead (derivePubKey k)+  it "does not read an invalid key" $ do     (readMaybe (quoted (zero ++ zero)) :: Maybe PubKey) `shouldBe` Nothing     (readMaybe (quoted ("02" ++ take 62 zero ++ "05")) :: Maybe PubKey) `shouldBe` Nothing     (readMaybe (quoted (drop 2 genCompressed)) :: Maybe PubKey) `shouldBe` Nothing     evaluate (fromString (drop 2 genCompressed) :: PubKey) `shouldThrow` anyErrorCall   where-    roundTrip ctx (k, compress) =-      let p = derivePubKey ctx k-       in importPubKey ctx (exportPubKey ctx compress p) == Just p+    roundTrip (k, compress) =+      let p = derivePubKey k+       in importPubKey (exportPubKey compress p) == Just p  -- * Messages -messageSpec :: SpecWith Ctx+messageSpec :: Spec messageSpec = describe "messages" $ do-  it "accepts 32 bytes and rejects other lengths" $ \_ -> do+  it "accepts 32 bytes and rejects other lengths" $ do     msg (BS.replicate 32 7) `shouldSatisfy` isJust     msg (BS.replicate 31 7) `shouldBe` Nothing     msg (BS.replicate 33 7) `shouldBe` Nothing     msg "" `shouldBe` Nothing-  it "shows and reads" $ \_ ->+  it "shows and reads" $     property (showRead :: Msg -> Bool)-  it "reads from a string, upper or lower case" $ \_ ->+  it "reads from a string, upper or lower case" $     property $ \(m :: Msg) ->       fromString (bytesToHex m.get) == m         && fromString (map toUpperHex (bytesToHex m.get)) == m-  it "does not read an invalid message" $ \_ -> do+  it "does not read an invalid message" $ do     (readMaybe (quoted (drop 1 one)) :: Maybe Msg) `shouldBe` Nothing     -- A non-ASCII character is not a hex digit even when its low byte is one     -- (U+FF41, fullwidth 'a').@@ -441,185 +447,189 @@  -- * Signing -signingSpec :: SpecWith Ctx+signingSpec :: Spec signingSpec = describe "signing" $ do-  it "produces the RFC 6979 vector for key 1 and sha256 'Satoshi Nakamoto'" $ \ctx -> do-    bytesToHex (exportSig ctx (signMsg ctx keyOne satoshiMsg)) `shouldBe` satoshiDer-    bytesToHex (exportCompactSig ctx (signMsg ctx keyOne satoshiMsg)).get+  it "produces the RFC 6979 vector for key 1 and sha256 'Satoshi Nakamoto'" $ do+    bytesToHex (exportSig (signMsg keyOne satoshiMsg)) `shouldBe` satoshiDer+    bytesToHex (exportCompactSig (signMsg keyOne satoshiMsg)).get       `shouldBe` satoshiR ++ satoshiS-  it "produces Bitcoin Core's deterministic signature" $ \ctx -> do-    bytesToHex (exportSig ctx (signMsg ctx coreKey coreMsg)) `shouldBe` coreDer-    bytesToHex (exportSig ctx (signMsgLowR ctx coreKey coreMsg)) `shouldBe` coreDer-  it "is deterministic" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> signMsg ctx k m == signMsg ctx k m-  it "verifies with the matching public key" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> signsAndVerifies ctx (m, k)-  it "verifies in parallel" $ \ctx ->+  it "produces Bitcoin Core's deterministic signature" $ do+    bytesToHex (exportSig (signMsg coreKey coreMsg)) `shouldBe` coreDer+    bytesToHex (exportSig (signMsgLowR coreKey coreMsg)) `shouldBe` coreDer+  it "is deterministic" $+    property $+      \(m :: Msg, k :: SecKey) -> signMsg k m == signMsg k m+  it "verifies with the matching public key" $+    property $+      \(m :: Msg, k :: SecKey) -> signsAndVerifies (m, k)+  it "verifies in parallel" $     property $ \(xs :: [(Msg, SecKey)]) -> P.runPar $ do-      results <- mapM (P.spawnP . signsAndVerifies ctx) xs+      results <- mapM (P.spawnP . signsAndVerifies) xs       and <$> mapM P.get results-  it "produces lower-S signatures" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> isLowS ctx (signMsg ctx k m)+  it "produces lower-S signatures" $+    property $+      \(m :: Msg, k :: SecKey) -> isLowS (signMsg k m)   describe "with low r" $ do-    it "leaves a signature alone when r is already low" $ \ctx -> do-      bytesToHex (exportSig ctx (signMsg ctx keyOne lowRMsg)) `shouldBe` lowRDer-      signMsgLowR ctx keyOne lowRMsg `shouldBe` signMsg ctx keyOne lowRMsg-    it "grinds a high r down the way Bitcoin Core does" $ \ctx -> do-      bytesToHex (exportSig ctx (signMsg ctx keyOne highRMsg)) `shouldBe` highRDer-      bytesToHex (exportSig ctx (signMsgLowR ctx keyOne highRMsg)) `shouldBe` groundDer-    it "always gives low r, lower s, at most 70 DER bytes, and verifies" $ \ctx ->+    it "leaves a signature alone when r is already low" $ do+      bytesToHex (exportSig (signMsg keyOne lowRMsg)) `shouldBe` lowRDer+      signMsgLowR keyOne lowRMsg `shouldBe` signMsg keyOne lowRMsg+    it "grinds a high r down the way Bitcoin Core does" $ do+      bytesToHex (exportSig (signMsg keyOne highRMsg)) `shouldBe` highRDer+      bytesToHex (exportSig (signMsgLowR keyOne highRMsg)) `shouldBe` groundDer+    it "always gives low r, lower s, at most 70 DER bytes, and verifies" $       property $ \(m :: Msg, k :: SecKey) ->-        let s = signMsgLowR ctx k m-         in isLowR ctx s-              && isLowS ctx s-              && BS.length (exportSig ctx s) <= 70-              && verifySig ctx (derivePubKey ctx k) s m-    it "equals plain signing whenever that already has low r" $ \ctx ->+        let s = signMsgLowR k m+         in isLowR s+              && isLowS s+              && BS.length (exportSig s) <= 70+              && verifySig (derivePubKey k) s m+    it "equals plain signing whenever that already has low r" $       property $ \(m :: Msg, k :: SecKey) ->-        let s = signMsg ctx k m-         in isLowR ctx s ==> signMsgLowR ctx k m == s+        let s = signMsg k m+         in isLowR s ==> signMsgLowR k m == s   where-    signsAndVerifies ctx (m, k) =-      verifySig ctx (derivePubKey ctx k) (signMsg ctx k m) m+    signsAndVerifies (m, k) =+      verifySig (derivePubKey k) (signMsg k m) m  -- * Verification -verificationSpec :: SpecWith Ctx+verificationSpec :: Spec verificationSpec = describe "verification" $ do-  it "accepts the RFC 6979 vector from its DER encoding" $ \ctx ->-    verifySig ctx (fromString genCompressed) (fromJust (importSig ctx (hexToBytes satoshiDer))) satoshiMsg+  it "accepts the RFC 6979 vector from its DER encoding" $+    verifySig (fromString genCompressed) (fromJust (importSig (hexToBytes satoshiDer))) satoshiMsg       `shouldBe` True-  it "accepts the historical vector" $ \ctx ->+  it "accepts the historical vector" $     verifySig-      ctx       (fromString histPub)-      ( fromJust . importSig ctx . hexToBytes $+      ( fromJust . importSig . hexToBytes $           "3045022100f502bfa07af43e7ef265618b0d929a7619ee01d6150e37eb6eaaf2c8bd37fb22\           \02206f0415ab0e9a977afd78b2c26ef39b3952096d319fd4b101c768ad6c132e3045"       )       "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"       `shouldBe` True-  it "rejects a signature from another key" $ \ctx ->+  it "rejects a signature from another key" $     property $ \(m :: Msg, k :: SecKey, k' :: SecKey) ->-      k /= k' ==> not (verifySig ctx (derivePubKey ctx k') (signMsg ctx k m) m)-  it "rejects a signature over another message" $ \ctx ->+      k /= k' ==> not (verifySig (derivePubKey k') (signMsg k m) m)+  it "rejects a signature over another message" $     property $ \(m :: Msg, m' :: Msg, k :: SecKey) ->-      m /= m' ==> not (verifySig ctx (derivePubKey ctx k) (signMsg ctx k m) m')-  it "rejects a signature with one bit flipped" $ \ctx ->+      m /= m' ==> not (verifySig (derivePubKey k) (signMsg k m) m')+  it "rejects a signature with one bit flipped" $     property $ \(m :: Msg, k :: SecKey) ->-      let compact = (exportCompactSig ctx (signMsg ctx k m)).get+      let compact = (exportCompactSig (signMsg k m)).get           -- Flipping the lowest bit of a lower-S s keeps it below n.           flipped = BS.init compact `BS.snoc` (BS.last compact `xor` 1)-       in case importCompactSig ctx (fromJust (compactSig flipped)) of+       in case importCompactSig (fromJust (compactSig flipped)) of             Nothing -> False-            Just s -> not (verifySig ctx (derivePubKey ctx k) s m)+            Just s -> not (verifySig (derivePubKey k) s m)   describe "lower-S form" $ do-    it "rejects the high-S form of a valid signature" $ \ctx -> do+    it "rejects the high-S form of a valid signature" $ do       let high = fromString (satoshiR ++ satoshiHighS) :: Sig-      isLowS ctx high `shouldBe` False-      verifySig ctx (fromString genCompressed) high satoshiMsg `shouldBe` False-    it "normalizes the high-S form to the signature that was made" $ \ctx -> do+      isLowS high `shouldBe` False+      verifySig (fromString genCompressed) high satoshiMsg `shouldBe` False+    it "normalizes the high-S form to the signature that was made" $ do       let high = fromString (satoshiR ++ satoshiHighS) :: Sig-          low = normalizeSig ctx high-      low `shouldBe` signMsg ctx keyOne satoshiMsg-      isLowS ctx low `shouldBe` True-      verifySig ctx (fromString genCompressed) low satoshiMsg `shouldBe` True-    it "leaves a lower-S signature unchanged" $ \ctx ->+          low = normalizeSig high+      low `shouldBe` signMsg keyOne satoshiMsg+      isLowS low `shouldBe` True+      verifySig (fromString genCompressed) low satoshiMsg `shouldBe` True+    it "leaves a lower-S signature unchanged" $       property $ \(m :: Msg, k :: SecKey) ->-        let s = signMsg ctx k m in normalizeSig ctx s == s-    it "is idempotent" $ \ctx -> do+        let s = signMsg k m in normalizeSig s == s+    it "is idempotent" $ do       let high = fromString (satoshiR ++ satoshiHighS) :: Sig-      normalizeSig ctx (normalizeSig ctx high) `shouldBe` normalizeSig ctx high+      normalizeSig (normalizeSig high) `shouldBe` normalizeSig high  -- * DER -derSpec :: SpecWith Ctx+derSpec :: Spec derSpec = describe "DER signatures" $ do-  it "exports the RFC 6979 vector and imports it back" $ \ctx -> do-    let s = signMsg ctx keyOne satoshiMsg-    bytesToHex (exportSig ctx s) `shouldBe` satoshiDer-    importSig ctx (hexToBytes satoshiDer) `shouldBe` Just s-  it "exports and imports back the same signature" $ \ctx ->+  it "exports the RFC 6979 vector and imports it back" $ do+    let s = signMsg keyOne satoshiMsg+    bytesToHex (exportSig s) `shouldBe` satoshiDer+    importSig (hexToBytes satoshiDer) `shouldBe` Just s+  it "exports and imports back the same signature" $     property $ \(m :: Msg, k :: SecKey) ->-      let s = signMsg ctx k m in importSig ctx (exportSig ctx s) == Just s-  it "exports and imports in parallel" $ \ctx ->+      let s = signMsg k m in importSig (exportSig s) == Just s+  it "exports and imports in parallel" $     property $ \(xs :: [(Msg, SecKey)]) -> P.runPar $ do-      results <- mapM (P.spawnP . roundTrip ctx) xs+      results <- mapM (P.spawnP . roundTrip) xs       and <$> mapM P.get results-  it "exports 70 bytes for low r and 71 bytes for high r" $ \ctx -> do-    BS.length (exportSig ctx (signMsg ctx keyOne lowRMsg)) `shouldBe` 70-    BS.length (exportSig ctx (signMsg ctx keyOne highRMsg)) `shouldBe` 71-  it "imports a high-S signature" $ \ctx -> do+  it "exports 70 bytes for low r and 71 bytes for high r" $ do+    BS.length (exportSig (signMsg keyOne lowRMsg)) `shouldBe` 70+    BS.length (exportSig (signMsg keyOne highRMsg)) `shouldBe` 71+  it "imports a high-S signature" $ do     let high = fromString (satoshiR ++ satoshiHighS) :: Sig-    importSig ctx (exportSig ctx high) `shouldBe` Just high-  it "rejects an empty input" $ \ctx ->-    importSig ctx "" `shouldBe` Nothing-  it "rejects a component equal to n or zero" $ \ctx -> do+    importSig (exportSig high) `shouldBe` Just high+  it "rejects an empty input" $+    importSig "" `shouldBe` Nothing+  it "rejects a component equal to n or zero" $ do     -- r = n (33 bytes with a zero pad), s = r of the vector.-    importSig ctx (hexToBytes ("3046022100" ++ order ++ "022100" ++ satoshiR)) `shouldBe` Nothing+    importSig (hexToBytes ("3046022100" ++ order ++ "022100" ++ satoshiR)) `shouldBe` Nothing     -- r = 0, s = r of the vector. 3 + 35 = 38 = 0x26 bytes.-    importSig ctx (hexToBytes ("3026020100022100" ++ satoshiR)) `shouldBe` Nothing+    importSig (hexToBytes ("3026020100022100" ++ satoshiR)) `shouldBe` Nothing     -- r of the vector, s = 0.-    importSig ctx (hexToBytes ("3026022100" ++ satoshiR ++ "020100")) `shouldBe` Nothing-  it "rejects encodings that are not strict DER" $ \ctx -> do+    importSig (hexToBytes ("3026022100" ++ satoshiR ++ "020100")) `shouldBe` Nothing+  it "rejects encodings that are not strict DER" $ do     -- Long-form length for a value below 128.-    importSig ctx (hexToBytes ("308145" ++ drop 4 satoshiDer)) `shouldBe` Nothing+    importSig (hexToBytes ("308145" ++ drop 4 satoshiDer)) `shouldBe` Nothing     -- A byte after the sequence.-    importSig ctx (hexToBytes (satoshiDer ++ "00")) `shouldBe` Nothing+    importSig (hexToBytes (satoshiDer ++ "00")) `shouldBe` Nothing     -- A byte missing at the end.-    importSig ctx (hexToBytes (take (length satoshiDer - 2) satoshiDer)) `shouldBe` Nothing+    importSig (hexToBytes (take (length satoshiDer - 2) satoshiDer)) `shouldBe` Nothing     -- Wrong sequence tag.-    importSig ctx (hexToBytes ("31" ++ drop 2 satoshiDer)) `shouldBe` Nothing+    importSig (hexToBytes ("31" ++ drop 2 satoshiDer)) `shouldBe` Nothing     -- Negative r: the zero pad is removed although the first byte is 0x93.-    importSig ctx (hexToBytes ("30440220" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing+    importSig (hexToBytes ("30440220" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing     -- Two zero pad bytes on r.-    importSig ctx (hexToBytes ("3046022200" ++ "00" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing+    importSig (hexToBytes ("3046022200" ++ "00" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing   where-    roundTrip ctx (m, k) = let s = signMsg ctx k m in importSig ctx (exportSig ctx s) == Just s+    roundTrip (m, k) = let s = signMsg k m in importSig (exportSig s) == Just s  -- * Compact signatures -compactSpec :: SpecWith Ctx+compactSpec :: Spec compactSpec = describe "compact signatures" $ do-  it "exports the RFC 6979 vector and imports it back" $ \ctx -> do-    let s = signMsg ctx keyOne satoshiMsg-    bytesToHex (exportCompactSig ctx s).get `shouldBe` satoshiR ++ satoshiS-    importCompactSig ctx (fromString (satoshiR ++ satoshiS)) `shouldBe` Just s-  it "exports and imports back the same signature" $ \ctx ->+  it "exports the RFC 6979 vector and imports it back" $ do+    let s = signMsg keyOne satoshiMsg+    bytesToHex (exportCompactSig s).get `shouldBe` satoshiR ++ satoshiS+    importCompactSig (fromString (satoshiR ++ satoshiS)) `shouldBe` Just s+  it "exports and imports back the same signature" $     property $ \(m :: Msg, k :: SecKey) ->-      let s = signMsg ctx k m in importCompactSig ctx (exportCompactSig ctx s) == Just s-  it "accepts components of 1 and n - 1 and rejects 0 and n" $ \ctx -> do-    importCompactSig ctx (fromString (one ++ one)) `shouldSatisfy` isJust-    importCompactSig ctx (fromString (orderMinusOne ++ orderMinusOne)) `shouldSatisfy` isJust-    importCompactSig ctx (fromString (order ++ one)) `shouldBe` Nothing-    importCompactSig ctx (fromString (one ++ order)) `shouldBe` Nothing-    importCompactSig ctx (fromString (zero ++ one)) `shouldBe` Nothing-    importCompactSig ctx (fromString (one ++ zero)) `shouldBe` Nothing-  it "only accepts 64 bytes as a compact signature" $ \_ -> do+      let s = signMsg k m in importCompactSig (exportCompactSig s) == Just s+  it "accepts components of 1 and n - 1 and rejects 0 and n" $ do+    importCompactSig (fromString (one ++ one)) `shouldSatisfy` isJust+    importCompactSig (fromString (orderMinusOne ++ orderMinusOne)) `shouldSatisfy` isJust+    importCompactSig (fromString (order ++ one)) `shouldBe` Nothing+    importCompactSig (fromString (one ++ order)) `shouldBe` Nothing+    importCompactSig (fromString (zero ++ one)) `shouldBe` Nothing+    importCompactSig (fromString (one ++ zero)) `shouldBe` Nothing+  it "only accepts 64 bytes as a compact signature" $ do     compactSig (BS.replicate 64 1) `shouldSatisfy` isJust     compactSig (BS.replicate 63 1) `shouldBe` Nothing     compactSig (BS.replicate 65 1) `shouldBe` Nothing-  it "shows and reads a compact signature" $ \_ -> do+  it "shows and reads a compact signature" $ do     show (fromString (satoshiR ++ satoshiS) :: CompactSig) `shouldBe` quoted (satoshiR ++ satoshiS)     (readMaybe (quoted (satoshiR ++ satoshiS)) :: Maybe CompactSig)       `shouldBe` Just (fromString (satoshiR ++ satoshiS))     (readMaybe (quoted satoshiR) :: Maybe CompactSig) `shouldBe` Nothing     evaluate (fromString satoshiR :: CompactSig) `shouldThrow` anyErrorCall   describe "signature values" $ do-    it "rebuild from their internal bytes" $ \ctx ->-      property $ \(m :: Msg, k :: SecKey) -> let s = signMsg ctx k m in sig s.get == Just s-    it "reject internal bytes that are not a signature" $ \_ -> do+    it "rebuild from their internal bytes" $+      property $+        \(m :: Msg, k :: SecKey) -> let s = signMsg k m in sig s.get == Just s+    it "reject internal bytes that are not a signature" $ do       sig (BS.replicate 64 0) `shouldBe` Nothing       sig (BS.replicate 64 0xff) `shouldBe` Nothing       sig (BS.replicate 63 1) `shouldBe` Nothing-    it "show the compact encoding" $ \ctx ->-      show (signMsg ctx keyOne satoshiMsg) `shouldBe` quoted (satoshiR ++ satoshiS)-    it "read the compact encoding" $ \ctx -> do-      read (quoted (satoshiR ++ satoshiS)) `shouldBe` signMsg ctx keyOne satoshiMsg-      (fromString (satoshiR ++ satoshiS) :: Sig) `shouldBe` signMsg ctx keyOne satoshiMsg-    it "show and read" $ \ctx ->-      property $ \(m :: Msg, k :: SecKey) -> showRead (signMsg ctx k m)-    it "do not read an invalid signature" $ \_ -> do+    it "show the compact encoding" $+      show (signMsg keyOne satoshiMsg) `shouldBe` quoted (satoshiR ++ satoshiS)+    it "read the compact encoding" $ do+      read (quoted (satoshiR ++ satoshiS)) `shouldBe` signMsg keyOne satoshiMsg+      (fromString (satoshiR ++ satoshiS) :: Sig) `shouldBe` signMsg keyOne satoshiMsg+    it "show and read" $+      property $+        \(m :: Msg, k :: SecKey) -> showRead (signMsg k m)+    it "do not read an invalid signature" $ do       (readMaybe (quoted (zero ++ one)) :: Maybe Sig) `shouldBe` Nothing       (readMaybe (quoted (order ++ one)) :: Maybe Sig) `shouldBe` Nothing       (readMaybe (quoted satoshiDer) :: Maybe Sig) `shouldBe` Nothing@@ -627,87 +637,89 @@  -- * Tweaks -tweakSpec :: SpecWith Ctx+tweakSpec :: Spec tweakSpec = describe "tweaks" $ do-  it "accepts 0 and n - 1 and rejects n and 2^256 - 1" $ \_ -> do+  it "accepts 0 and n - 1 and rejects n and 2^256 - 1" $ do     tweak (hexToBytes zero) `shouldSatisfy` isJust     tweak (hexToBytes orderMinusOne) `shouldSatisfy` isJust     tweak (hexToBytes order) `shouldBe` Nothing     tweak (hexToBytes allOnes) `shouldBe` Nothing     tweak (BS.replicate 31 0) `shouldBe` Nothing-  it "shows and reads" $ \_ ->+  it "shows and reads" $     property (showRead :: Tweak -> Bool)-  it "does not read a tweak of n" $ \_ -> do+  it "does not read a tweak of n" $ do     (readMaybe (quoted order) :: Maybe Tweak) `shouldBe` Nothing     evaluate (fromString order :: Tweak) `shouldThrow` anyErrorCall-  it "reads from a string" $ \_ ->-    property $ \(t :: Tweak) -> fromString (bytesToHex t.get) == t-  it "adds to a secret key" $ \ctx ->+  it "reads from a string" $+    property $+      \(t :: Tweak) -> fromString (bytesToHex t.get) == t+  it "adds to a secret key" $     -- (key + tweak) mod n-    tweakAddSecKey ctx histKey histTweak+    tweakAddSecKey histKey histTweak       `shouldBe` Just "ec1e3ce1cefa18a671d51125e2b249688d934b0e28f5d1665384d9b02f929059"-  it "multiplies a secret key" $ \ctx ->+  it "multiplies a secret key" $     -- (key * tweak) mod n-    tweakMulSecKey ctx histKey histTweak+    tweakMulSecKey histKey histTweak       `shouldBe` Just "a96f5962493acb179f60a86a9785fc7a30e0c39b64c09d24fe064d9aef15e4c0"-  it "adds to a public key" $ \ctx ->+  it "adds to a public key" $     -- P + tweak * G-    fmap (bytesToHex . exportPubKey ctx False) (tweakAddPubKey ctx (fromString histPub) histTweak)+    fmap (bytesToHex . exportPubKey False) (tweakAddPubKey (fromString histPub) histTweak)       `shouldBe` Just         "04441c3982b97576646e0df0c96736063df6b42f2ee566d13b9f6424302d1379e5\         \18fdc87a14c5435bff7a5db4552042cb4120c6b86a4bbd3d0643f3c14ad01368"-  it "multiplies a public key" $ \ctx ->+  it "multiplies a public key" $     -- tweak * P-    fmap (bytesToHex . exportPubKey ctx False) (tweakMulPubKey ctx (fromString histPub) histTweak)+    fmap (bytesToHex . exportPubKey False) (tweakMulPubKey (fromString histPub) histTweak)       `shouldBe` Just         "04f379dc99cdf5c83e433defa267fbb3377d61d6b779c06a0e4ce29ae3ff5353b1\         \2ae49c9d07e7368f2ba5a446c203255ce912322991a2d6a9d5d5761c61ed1845"-  it "tweaks the public key like the secret key" $ \ctx ->+  it "tweaks the public key like the secret key" $     property $ \(k :: SecKey, t :: Tweak) ->-      fmap (derivePubKey ctx) (tweakAddSecKey ctx k t) == tweakAddPubKey ctx (derivePubKey ctx k) t-        && fmap (derivePubKey ctx) (tweakMulSecKey ctx k t) == tweakMulPubKey ctx (derivePubKey ctx k) t-  it "adding zero changes nothing" $ \ctx ->+      fmap (derivePubKey) (tweakAddSecKey k t) == tweakAddPubKey (derivePubKey k) t+        && fmap (derivePubKey) (tweakMulSecKey k t) == tweakMulPubKey (derivePubKey k) t+  it "adding zero changes nothing" $     property $ \(k :: SecKey) ->-      tweakAddSecKey ctx k (fromString zero) == Just k-        && tweakAddPubKey ctx (derivePubKey ctx k) (fromString zero) == Just (derivePubKey ctx k)-  it "multiplying by zero fails" $ \ctx -> do-    tweakMulSecKey ctx keyOne (fromString zero) `shouldBe` Nothing-    tweakMulPubKey ctx (derivePubKey ctx keyOne) (fromString zero) `shouldBe` Nothing-  it "adding the negation of the key fails" $ \ctx -> do+      tweakAddSecKey k (fromString zero) == Just k+        && tweakAddPubKey (derivePubKey k) (fromString zero) == Just (derivePubKey k)+  it "multiplying by zero fails" $ do+    tweakMulSecKey keyOne (fromString zero) `shouldBe` Nothing+    tweakMulPubKey (derivePubKey keyOne) (fromString zero) `shouldBe` Nothing+  it "adding the negation of the key fails" $ do     -- 1 + (n - 1) = 0 mod n-    tweakAddSecKey ctx keyOne (fromString orderMinusOne) `shouldBe` Nothing-    tweakAddPubKey ctx (derivePubKey ctx keyOne) (fromString orderMinusOne) `shouldBe` Nothing-  it "negates modulo n" $ \ctx -> do-    tweakNegate ctx (fromString one) `shouldBe` Just (fromString orderMinusOne)-    tweakNegate ctx (fromString zero) `shouldBe` Just (fromString zero)+    tweakAddSecKey keyOne (fromString orderMinusOne) `shouldBe` Nothing+    tweakAddPubKey (derivePubKey keyOne) (fromString orderMinusOne) `shouldBe` Nothing+  it "negates modulo n" $ do+    tweakNegate (fromString one) `shouldBe` Just (fromString orderMinusOne)+    tweakNegate (fromString zero) `shouldBe` Just (fromString zero)     -- n - histTweak-    tweakNegate ctx histTweak+    tweakNegate histTweak       `shouldBe` Just "0a3418277e7d5b471bff0694f9ed76dd3464c4ce323753b0d77e433663ab7341"-  it "negating twice gives the tweak back" $ \ctx ->-    property $ \(t :: Tweak) -> (tweakNegate ctx t >>= tweakNegate ctx) == Just t-  it "adding a tweak and then its negation gives the key back" $ \ctx ->+  it "negating twice gives the tweak back" $+    property $+      \(t :: Tweak) -> (tweakNegate t >>= tweakNegate) == Just t+  it "adding a tweak and then its negation gives the key back" $     property $ \(k :: SecKey, t :: Tweak) ->-      let minus = fromJust (tweakNegate ctx t)-       in (tweakAddSecKey ctx k t >>= \k' -> tweakAddSecKey ctx k' minus) == Just k-  it "leaves its inputs unchanged" $ \ctx ->+      let minus = fromJust (tweakNegate t)+       in (tweakAddSecKey k t >>= \k' -> tweakAddSecKey k' minus) == Just k+  it "leaves its inputs unchanged" $     property $ \(k :: SecKey, t :: Tweak) ->       let kBytes = BS.copy k.get-          p = derivePubKey ctx k+          p = derivePubKey k           pBytes = BS.copy p.get           tBytes = BS.copy t.get-       in tweakAddSecKey ctx k t `seq`-            tweakMulPubKey ctx p t `seq`-              tweakNegate ctx t `seq`+       in tweakAddSecKey k t `seq`+            tweakMulPubKey p t `seq`+              tweakNegate t `seq`                 (k.get == kBytes && p.get == pBytes && t.get == tBytes)  -- * Combining public keys -combineSpec :: SpecWith Ctx+combineSpec :: Spec combineSpec = describe "combining public keys" $ do-  it "adds three historical keys" $ \ctx ->-    fmap (bytesToHex . exportPubKey ctx False)+  it "adds three historical keys" $+    fmap+      (bytesToHex . exportPubKey False)       ( combinePubKeys-          ctx           [ fromString histPub,             "0487d82042d93447008dfe2af762068a1e53ff394a5bf8f68a045fa642b99ea5d1\             \53f577dd2dba6c7ae4cfd7b6622409d7edd2d76dd13a8092cd3af97b77bd2c77",@@ -718,70 +730,70 @@       `shouldBe` Just         "043d9a7ec70011efc23c33a7e62d2ea73cca87797e3b659d93bea6aa871aebde56\         \c3bc6134ca82e324b0ab9c0e601a6d2933afe7fb5d9f3aae900f5c5dc6e362c8"-  it "adds G to itself" $ \ctx ->+  it "adds G to itself" $     -- 2 * G-    fmap (bytesToHex . exportPubKey ctx True) (combinePubKeys ctx [fromString genCompressed, fromString genCompressed])+    fmap (bytesToHex . exportPubKey True) (combinePubKeys [fromString genCompressed, fromString genCompressed])       `shouldBe` Just "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"-  it "adds like the secret keys add" $ \ctx ->+  it "adds like the secret keys add" $     property $ \(k1 :: SecKey, k2 :: SecKey) ->-      combinePubKeys ctx [derivePubKey ctx k1, derivePubKey ctx k2]-        == fmap (derivePubKey ctx) (tweakAddSecKey ctx k1 (fromString (bytesToHex k2.get)))-  it "returns a single key unchanged" $ \ctx ->-    property $ \(k :: SecKey) -> combinePubKeys ctx [derivePubKey ctx k] == Just (derivePubKey ctx k)-  it "fails for no keys" $ \ctx ->-    combinePubKeys ctx [] `shouldBe` Nothing-  it "fails when the sum is the point at infinity" $ \ctx ->+      combinePubKeys [derivePubKey k1, derivePubKey k2]+        == fmap (derivePubKey) (tweakAddSecKey k1 (fromString (bytesToHex k2.get)))+  it "returns a single key unchanged" $+    property $+      \(k :: SecKey) -> combinePubKeys [derivePubKey k] == Just (derivePubKey k)+  it "fails for no keys" $+    combinePubKeys [] `shouldBe` Nothing+  it "fails when the sum is the point at infinity" $     property $ \(k :: SecKey) ->-      let p = derivePubKey ctx k-          minusP = fromJust (tweakMulPubKey ctx p (fromString orderMinusOne))-       in isNothing (combinePubKeys ctx [p, minusP])---- * Contexts+      let p = derivePubKey k+          minusP = fromJust (tweakMulPubKey p (fromString orderMinusOne))+       in isNothing (combinePubKeys [p, minusP])  -- * Schnorr signatures -schnorrSpec :: SpecWith Ctx+schnorrSpec :: Spec schnorrSpec = describe "Schnorr signatures" $ do   describe "BIP-340 vector" $ mapM_ bip340VectorSpec bip340Vectors-  it "signs vector 0 without auxiliary randomness as with 32 zero bytes" $ \ctx ->-    signSchnorr ctx bip340Key0 (fromString zero) `shouldBe` fromString bip340Sig0-  it "signs without randomness as with 32 zero bytes" $ \ctx ->+  it "signs vector 0 without auxiliary randomness as with 32 zero bytes" $+    signSchnorr bip340Key0 (fromString zero) `shouldBe` fromString bip340Sig0+  it "signs without randomness as with 32 zero bytes" $     property $ \(m :: Msg, k :: SecKey) ->-      signSchnorrWithAux ctx k m (BS.replicate 32 0) == Just (signSchnorr ctx k m)-  it "verifies with the matching public key" $ \ctx ->+      signSchnorrWithAux k m (BS.replicate 32 0) == Just (signSchnorr k m)+  it "verifies with the matching public key" $     property $ \(m :: Msg, k :: SecKey) ->-      verifySchnorr ctx (derivePubKey ctx k) (signSchnorr ctx k m) m-  it "verifies with the negation of the public key" $ \ctx ->+      verifySchnorr (derivePubKey k) (signSchnorr k m) m+  it "verifies with the negation of the public key" $     property $ \(m :: Msg, k :: SecKey) ->-      verifySchnorr ctx (negatePubKey ctx (derivePubKey ctx k)) (signSchnorr ctx k m) m-  it "verifies a signature made with fresh randomness" $ \ctx ->+      verifySchnorr (negatePubKey (derivePubKey k)) (signSchnorr k m) m+  it "verifies a signature made with fresh randomness" $     property $ \(m :: Msg, k :: SecKey) -> ioProperty $ do-      s <- signSchnorrIO ctx k m-      return (verifySchnorr ctx (derivePubKey ctx k) s m)-  it "changes with the auxiliary randomness" $ \ctx ->+      s <- signSchnorrIO k m+      return (verifySchnorr (derivePubKey k) s m)+  it "changes with the auxiliary randomness" $     property $ \(m :: Msg, k :: SecKey) ->-      signSchnorrWithAux ctx k m (BS.replicate 32 1) /= signSchnorrWithAux ctx k m (BS.replicate 32 2)-  it "rejects auxiliary randomness that is not 32 bytes" $ \ctx -> do-    signSchnorrWithAux ctx keyOne satoshiMsg (BS.replicate 31 0) `shouldBe` Nothing-    signSchnorrWithAux ctx keyOne satoshiMsg (BS.replicate 33 0) `shouldBe` Nothing-  it "rejects a signature from another key" $ \ctx ->+      signSchnorrWithAux k m (BS.replicate 32 1) /= signSchnorrWithAux k m (BS.replicate 32 2)+  it "rejects auxiliary randomness that is not 32 bytes" $ do+    signSchnorrWithAux keyOne satoshiMsg (BS.replicate 31 0) `shouldBe` Nothing+    signSchnorrWithAux keyOne satoshiMsg (BS.replicate 33 0) `shouldBe` Nothing+  it "rejects a signature from another key" $     property $ \(m :: Msg, k :: SecKey, k' :: SecKey) ->-      k /= k' ==> not (verifySchnorr ctx (derivePubKey ctx k') (signSchnorr ctx k m) m)-  it "rejects a signature over another message" $ \ctx ->+      k /= k' ==> not (verifySchnorr (derivePubKey k') (signSchnorr k m) m)+  it "rejects a signature over another message" $     property $ \(m :: Msg, m' :: Msg, k :: SecKey) ->-      m /= m' ==> not (verifySchnorr ctx (derivePubKey ctx k) (signSchnorr ctx k m) m')-  it "only accepts 64 bytes as a signature" $ \_ -> do+      m /= m' ==> not (verifySchnorr (derivePubKey k) (signSchnorr k m) m')+  it "only accepts 64 bytes as a signature" $ do     schnorrSig (BS.replicate 64 0) `shouldSatisfy` isJust     schnorrSig (BS.replicate 63 0) `shouldBe` Nothing     schnorrSig (BS.replicate 65 0) `shouldBe` Nothing-  it "shows the signature in hex" $ \_ ->+  it "shows the signature in hex" $     show (fromString bip340Sig0 :: SchnorrSig) `shouldBe` quoted bip340Sig0-  it "shows and reads" $ \ctx ->-    property $ \(m :: Msg, k :: SecKey) -> showRead (signSchnorr ctx k m)-  it "reads from a string" $ \ctx ->+  it "shows and reads" $+    property $+      \(m :: Msg, k :: SecKey) -> showRead (signSchnorr k m)+  it "reads from a string" $     property $ \(m :: Msg, k :: SecKey) ->-      let s = signSchnorr ctx k m in fromString (bytesToHex s.get) == s-  it "does not read a signature of the wrong length" $ \_ -> do+      let s = signSchnorr k m in fromString (bytesToHex s.get) == s+  it "does not read a signature of the wrong length" $ do     (readMaybe (quoted (replicate 126 '0')) :: Maybe SchnorrSig) `shouldBe` Nothing     evaluate (fromString (replicate 126 '0') :: SchnorrSig) `shouldThrow` anyErrorCall @@ -789,207 +801,193 @@ -- with the given auxiliary randomness gives the signature. For every vector: -- verification gives the expected result, where a public key that does not -- import counts as a failed verification.-bip340VectorSpec :: BIP340Vector -> SpecWith Ctx-bip340VectorSpec v = it (show v.index ++ " " ++ v.comment) $ \ctx -> do+bip340VectorSpec :: BIP340Vector -> Spec+bip340VectorSpec v = it (show v.index ++ " " ++ v.comment) $ do   let m = fromString v.message :: Msg       s = fromString v.signature :: SchnorrSig   case (v.secretKey, v.auxRand) of     (Just key, Just aux) -> do       let k = fromString key :: SecKey-      bytesToHex (exportXOnlyPubKey ctx (derivePubKey ctx k)) `shouldBe` v.publicKey-      signSchnorrWithAux ctx k m (hexToBytes aux) `shouldBe` Just s+      bytesToHex (exportXOnlyPubKey (derivePubKey k)) `shouldBe` v.publicKey+      signSchnorrWithAux k m (hexToBytes aux) `shouldBe` Just s     _ -> return ()-  maybe False (\p -> verifySchnorr ctx p s m) (importXOnlyPubKey ctx (hexToBytes v.publicKey))+  maybe False (\p -> verifySchnorr p s m) (importXOnlyPubKey (hexToBytes v.publicKey))     `shouldBe` v.result  -- * X-only public keys -xOnlySpec :: SpecWith Ctx+xOnlySpec :: Spec xOnlySpec = describe "x-only public keys" $ do-  it "exports the x coordinate of G" $ \ctx ->+  it "exports the x coordinate of G" $     -- the compressed encoding of G without its 02 prefix-    bytesToHex (exportXOnlyPubKey ctx (derivePubKey ctx keyOne)) `shouldBe` drop 2 genCompressed-  it "exports the public key of BIP-340 vector 0" $ \ctx ->-    bytesToHex (exportXOnlyPubKey ctx (derivePubKey ctx bip340Key0)) `shouldBe` bip340Pub0-  it "exports the x coordinate of any key" $ \ctx ->+    bytesToHex (exportXOnlyPubKey (derivePubKey keyOne)) `shouldBe` drop 2 genCompressed+  it "exports the public key of BIP-340 vector 0" $+    bytesToHex (exportXOnlyPubKey (derivePubKey bip340Key0)) `shouldBe` bip340Pub0+  it "exports the x coordinate of any key" $     property $ \(k :: SecKey) ->-      let p = derivePubKey ctx k-       in exportXOnlyPubKey ctx p == BS.drop 1 (exportPubKey ctx True p)-  it "exports a key and its negation the same way" $ \ctx ->+      let p = derivePubKey k+       in exportXOnlyPubKey p == BS.drop 1 (exportPubKey True p)+  it "exports a key and its negation the same way" $     property $ \(k :: SecKey) ->-      let p = derivePubKey ctx k-       in exportXOnlyPubKey ctx p == exportXOnlyPubKey ctx (negatePubKey ctx p)-  it "imports G from its x coordinate" $ \ctx ->-    fmap (bytesToHex . exportPubKey ctx True) (importXOnlyPubKey ctx (hexToBytes (drop 2 genCompressed)))+      let p = derivePubKey k+       in exportXOnlyPubKey p == exportXOnlyPubKey (negatePubKey p)+  it "imports G from its x coordinate" $+    fmap (bytesToHex . exportPubKey True) (importXOnlyPubKey (hexToBytes (drop 2 genCompressed)))       `shouldBe` Just genCompressed-  it "imports the point with an even y coordinate" $ \ctx ->+  it "imports the point with an even y coordinate" $     property $ \(k :: SecKey) ->-      let x = exportXOnlyPubKey ctx (derivePubKey ctx k)-       in fmap (exportPubKey ctx True) (importXOnlyPubKey ctx x) == Just (BS.cons 0x02 x)-  it "rejects an x coordinate that is not on the curve" $ \ctx -> do-    importXOnlyPubKey ctx (hexToBytes fieldSize) `shouldBe` Nothing+      let x = exportXOnlyPubKey (derivePubKey k)+       in fmap (exportPubKey True) (importXOnlyPubKey x) == Just (BS.cons 0x02 x)+  it "rejects an x coordinate that is not on the curve" $ do+    importXOnlyPubKey (hexToBytes fieldSize) `shouldBe` Nothing     -- BIP-340 vector 5-    importXOnlyPubKey ctx (hexToBytes "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34")+    importXOnlyPubKey (hexToBytes "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34")       `shouldBe` Nothing-  it "rejects 31 and 33 bytes" $ \ctx -> do-    importXOnlyPubKey ctx (BS.replicate 31 1) `shouldBe` Nothing-    importXOnlyPubKey ctx (BS.replicate 33 1) `shouldBe` Nothing+  it "rejects 31 and 33 bytes" $ do+    importXOnlyPubKey (BS.replicate 31 1) `shouldBe` Nothing+    importXOnlyPubKey (BS.replicate 33 1) `shouldBe` Nothing  -- * Taproot tweaks -taprootSpec :: SpecWith Ctx+taprootSpec :: Spec taprootSpec = describe "Taproot tweaks" $ do   describe "BIP-341 key path input" $ mapM_ (uncurry bip341VectorSpec) (zip [0 :: Int ..] bip341Vectors)-  it "tweaks the public key like the secret key" $ \ctx ->+  it "tweaks the public key like the secret key" $     property $ \(k :: SecKey, t :: Tweak) ->-      fmap (derivePubKey ctx) (tweakAddXOnlySecKey ctx k t) == tweakAddXOnlyPubKey ctx (derivePubKey ctx k) t-  it "tweaks a key and its negation alike" $ \ctx ->+      fmap (derivePubKey) (tweakAddXOnlySecKey k t) == tweakAddXOnlyPubKey (derivePubKey k) t+  it "tweaks a key and its negation alike" $     property $ \(k :: SecKey, t :: Tweak) ->-      let p = derivePubKey ctx k-       in tweakAddXOnlyPubKey ctx p t == tweakAddXOnlyPubKey ctx (negatePubKey ctx p) t-  it "signs for the tweaked output key with the tweaked secret key" $ \ctx ->+      let p = derivePubKey k+       in tweakAddXOnlyPubKey p t == tweakAddXOnlyPubKey (negatePubKey p) t+  it "signs for the tweaked output key with the tweaked secret key" $     property $ \(m :: Msg, k :: SecKey, t :: Tweak) ->-      let k' = fromJust (tweakAddXOnlySecKey ctx k t)-          p' = fromJust (tweakAddXOnlyPubKey ctx (derivePubKey ctx k) t)-       in verifySchnorr ctx p' (signSchnorr ctx k' m) m-  it "adding zero gives the point with an even y coordinate" $ \ctx ->+      let k' = fromJust (tweakAddXOnlySecKey k t)+          p' = fromJust (tweakAddXOnlyPubKey (derivePubKey k) t)+       in verifySchnorr p' (signSchnorr k' m) m+  it "adding zero gives the point with an even y coordinate" $     property $ \(k :: SecKey) ->-      let p = derivePubKey ctx k-       in fmap (exportPubKey ctx True) (tweakAddXOnlyPubKey ctx p (fromString zero))-            == Just (BS.cons 0x02 (exportXOnlyPubKey ctx p))-  it "negates a secret key whose public key has an odd y coordinate" $ \ctx ->+      let p = derivePubKey k+       in fmap (exportPubKey True) (tweakAddXOnlyPubKey p (fromString zero))+            == Just (BS.cons 0x02 (exportXOnlyPubKey p))+  it "negates a secret key whose public key has an odd y coordinate" $     -- Key n - 1 has the public key -G, whose y coordinate is odd, so the key     -- is negated to 1 before the zero tweak is added.-    tweakAddXOnlySecKey ctx (fromString orderMinusOne) (fromString zero) `shouldBe` Just keyOne-  it "fails when the result would be zero" $ \ctx -> do+    tweakAddXOnlySecKey (fromString orderMinusOne) (fromString zero) `shouldBe` Just keyOne+  it "fails when the result would be zero" $ do     -- G has an even y coordinate, so key 1 is not negated: 1 + (n - 1) = 0.-    tweakAddXOnlySecKey ctx keyOne (fromString orderMinusOne) `shouldBe` Nothing-    tweakAddXOnlyPubKey ctx (derivePubKey ctx keyOne) (fromString orderMinusOne) `shouldBe` Nothing+    tweakAddXOnlySecKey keyOne (fromString orderMinusOne) `shouldBe` Nothing+    tweakAddXOnlyPubKey (derivePubKey keyOne) (fromString orderMinusOne) `shouldBe` Nothing     -- Key n - 1 is negated to 1 first, with the same result.-    tweakAddXOnlySecKey ctx (fromString orderMinusOne) (fromString orderMinusOne) `shouldBe` Nothing-    tweakAddXOnlyPubKey ctx (derivePubKey ctx (fromString orderMinusOne)) (fromString orderMinusOne)+    tweakAddXOnlySecKey (fromString orderMinusOne) (fromString orderMinusOne) `shouldBe` Nothing+    tweakAddXOnlyPubKey (derivePubKey (fromString orderMinusOne)) (fromString orderMinusOne)       `shouldBe` Nothing  -- The internal key gives the internal public key. The tweak gives the tweaked -- secret key and the output key, and they match. The tweaked key signs the -- signature hash to the signature in the witness, which verifies against the -- output key.-bip341VectorSpec :: Int -> BIP341Vector -> SpecWith Ctx-bip341VectorSpec i v = it (show i) $ \ctx -> do+bip341VectorSpec :: Int -> BIP341Vector -> Spec+bip341VectorSpec i v = it (show i) $ do   let k = fromString v.internalKey :: SecKey       t = fromString v.tapTweak :: Tweak       k' = fromString v.tweakedKey :: SecKey       m = fromString v.sigHash :: Msg       s = fromString v.keyPathSig :: SchnorrSig-  bytesToHex (exportXOnlyPubKey ctx (derivePubKey ctx k)) `shouldBe` v.internalPub-  tweakAddXOnlySecKey ctx k t `shouldBe` Just k'-  fmap (bytesToHex . exportXOnlyPubKey ctx) (tweakAddXOnlyPubKey ctx (derivePubKey ctx k) t)+  bytesToHex (exportXOnlyPubKey (derivePubKey k)) `shouldBe` v.internalPub+  tweakAddXOnlySecKey k t `shouldBe` Just k'+  fmap (bytesToHex . exportXOnlyPubKey) (tweakAddXOnlyPubKey (derivePubKey k) t)     `shouldBe` Just v.outputKey-  signSchnorr ctx k' m `shouldBe` s-  verifySchnorr ctx (fromJust (importXOnlyPubKey ctx (hexToBytes v.outputKey))) s m `shouldBe` True--contextSpec :: SpecWith Ctx-contextSpec = describe "contexts" $ do-  it "a clone signs and verifies like the original" $ \ctx -> do-    clone <- cloneContext ctx-    signMsg clone keyOne satoshiMsg `shouldBe` signMsg ctx keyOne satoshiMsg-    verifySig clone (derivePubKey ctx keyOne) (signMsg ctx keyOne satoshiMsg) satoshiMsg `shouldBe` True-  it "randomizing does not change signatures" $ \ctx -> do-    let original = signMsg ctx keyOne satoshiMsg-    randomizeContext ctx-    signMsg ctx keyOne satoshiMsg `shouldBe` original-  it "withContext gives a working context" $ \_ ->-    withContext $ \ctx ->-      bytesToHex (exportSig ctx (signMsg ctx keyOne satoshiMsg)) `shouldBe` satoshiDer+  signSchnorr k' m `shouldBe` s+  verifySchnorr (fromJust (importXOnlyPubKey (hexToBytes v.outputKey))) s m `shouldBe` True  -- * Values built with the raw constructors of the Internal module -rawValueSpec :: SpecWith Ctx+rawValueSpec :: Spec rawValueSpec = describe "raw values from the Internal module" $ do   describe "a public key with a zero x coordinate" $ do-    it "does not verify, instead of aborting the process" $ \ctx ->+    it "does not verify, instead of aborting the process" $       property $ \(m :: Msg, k :: SecKey) ->-        not (verifySig ctx zeroKey (signMsg ctx k m) m)-    it "throws on export" $ \ctx ->-      evaluate (exportPubKey ctx True zeroKey) `shouldThrow` anyErrorCall-    it "throws on show" $ \_ ->+        not (verifySig zeroKey (signMsg k m) m)+    it "throws on export" $+      evaluate (exportPubKey True zeroKey) `shouldThrow` anyErrorCall+    it "throws on show" $       evaluate (length (show zeroKey)) `shouldThrow` anyErrorCall-    it "fails to tweak" $ \ctx -> do-      tweakAddPubKey ctx zeroKey (fromString one) `shouldBe` Nothing-      tweakMulPubKey ctx zeroKey (fromString one) `shouldBe` Nothing-    it "fails to combine" $ \ctx ->-      combinePubKeys ctx [derivePubKey ctx keyOne, zeroKey] `shouldBe` Nothing-    it "does not verify a Schnorr signature" $ \ctx ->-      verifySchnorr ctx zeroKey (signSchnorr ctx keyOne satoshiMsg) satoshiMsg `shouldBe` False-    it "throws on x-only export" $ \ctx ->-      evaluate (exportXOnlyPubKey ctx zeroKey) `shouldThrow` anyErrorCall-    it "fails to tweak as an x-only key" $ \ctx ->-      tweakAddXOnlyPubKey ctx zeroKey (fromString one) `shouldBe` Nothing-  it "a public key off the curve fails to combine" $ \ctx ->-    combinePubKeys ctx [derivePubKey ctx keyOne, PubKey (BS.replicate 64 1)] `shouldBe` Nothing-  it "a zero secret key throws instead of signing" $ \ctx -> do-    evaluate (signMsg ctx (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (derivePubKey ctx (SecKey (BS.replicate 32 0))) `shouldThrow` anyErrorCall-    evaluate (signSchnorr ctx (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall-  it "a zero secret key fails to tweak as an x-only key" $ \ctx ->-    tweakAddXOnlySecKey ctx (SecKey (BS.replicate 32 0)) (fromString one) `shouldBe` Nothing-  it "a tweak of n fails" $ \ctx -> do-    tweakAddSecKey ctx keyOne (Tweak (hexToBytes order)) `shouldBe` Nothing-    tweakNegate ctx (Tweak (hexToBytes order)) `shouldBe` Nothing-    tweakAddXOnlySecKey ctx keyOne (Tweak (hexToBytes order)) `shouldBe` Nothing-    tweakAddXOnlyPubKey ctx (derivePubKey ctx keyOne) (Tweak (hexToBytes order)) `shouldBe` Nothing-  it "values of the wrong length throw before reaching the library" $ \ctx -> do-    evaluate (derivePubKey ctx (SecKey "a")) `shouldThrow` anyErrorCall-    evaluate (signMsg ctx (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (signMsg ctx keyOne (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (verifySig ctx (derivePubKey ctx keyOne) (Sig "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (verifySig ctx (PubKey "a") (signMsg ctx keyOne satoshiMsg) satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (verifySig ctx (derivePubKey ctx keyOne) (signMsg ctx keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (exportSig ctx (Sig "a")) `shouldThrow` anyErrorCall-    evaluate (exportCompactSig ctx (Sig "a")) `shouldThrow` anyErrorCall-    evaluate (importCompactSig ctx (CompactSig "a")) `shouldThrow` anyErrorCall-    evaluate (normalizeSig ctx (Sig "a")) `shouldThrow` anyErrorCall-    evaluate (isLowS ctx (Sig "a")) `shouldThrow` anyErrorCall-    evaluate (exportPubKey ctx True (PubKey "a")) `shouldThrow` anyErrorCall-    evaluate (tweakAddSecKey ctx keyOne (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (tweakMulSecKey ctx (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (tweakAddPubKey ctx (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (tweakMulPubKey ctx (derivePubKey ctx keyOne) (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (tweakNegate ctx (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (combinePubKeys ctx [derivePubKey ctx keyOne, PubKey "a"]) `shouldThrow` anyErrorCall-    evaluate (tweakAddSecKey ctx (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (tweakMulSecKey ctx keyOne (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (tweakAddPubKey ctx (derivePubKey ctx keyOne) (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (tweakMulPubKey ctx (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (signMsgWith ctx keyOne satoshiMsg (Just "a")) `shouldThrow` anyErrorCall-    evaluate (signSchnorr ctx (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (signSchnorr ctx keyOne (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (verifySchnorr ctx (derivePubKey ctx keyOne) (SchnorrSig "a") satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (verifySchnorr ctx (PubKey "a") (signSchnorr ctx keyOne satoshiMsg) satoshiMsg) `shouldThrow` anyErrorCall-    evaluate (verifySchnorr ctx (derivePubKey ctx keyOne) (signSchnorr ctx keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall-    evaluate (exportXOnlyPubKey ctx (PubKey "a")) `shouldThrow` anyErrorCall-    evaluate (tweakAddXOnlyPubKey ctx (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (tweakAddXOnlyPubKey ctx (derivePubKey ctx keyOne) (Tweak "a")) `shouldThrow` anyErrorCall-    evaluate (tweakAddXOnlySecKey ctx (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall-    evaluate (tweakAddXOnlySecKey ctx keyOne (Tweak "a")) `shouldThrow` anyErrorCall+    it "fails to tweak" $ do+      tweakAddPubKey zeroKey (fromString one) `shouldBe` Nothing+      tweakMulPubKey zeroKey (fromString one) `shouldBe` Nothing+    it "fails to combine" $+      combinePubKeys [derivePubKey keyOne, zeroKey] `shouldBe` Nothing+    it "does not verify a Schnorr signature" $+      verifySchnorr zeroKey (signSchnorr keyOne satoshiMsg) satoshiMsg `shouldBe` False+    it "throws on x-only export" $+      evaluate (exportXOnlyPubKey zeroKey) `shouldThrow` anyErrorCall+    it "fails to tweak as an x-only key" $+      tweakAddXOnlyPubKey zeroKey (fromString one) `shouldBe` Nothing+  it "a public key off the curve fails to combine" $+    combinePubKeys [derivePubKey keyOne, PubKey (BS.replicate 64 1)] `shouldBe` Nothing+  it "a zero secret key throws instead of signing" $ do+    evaluate (signMsg (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (derivePubKey (SecKey (BS.replicate 32 0))) `shouldThrow` anyErrorCall+    evaluate (signSchnorr (SecKey (BS.replicate 32 0)) satoshiMsg) `shouldThrow` anyErrorCall+  it "a zero secret key fails to tweak as an x-only key" $+    tweakAddXOnlySecKey (SecKey (BS.replicate 32 0)) (fromString one) `shouldBe` Nothing+  it "a tweak of n fails" $ do+    tweakAddSecKey keyOne (Tweak (hexToBytes order)) `shouldBe` Nothing+    tweakNegate (Tweak (hexToBytes order)) `shouldBe` Nothing+    tweakAddXOnlySecKey keyOne (Tweak (hexToBytes order)) `shouldBe` Nothing+    tweakAddXOnlyPubKey (derivePubKey keyOne) (Tweak (hexToBytes order)) `shouldBe` Nothing+  it "values of the wrong length throw before reaching the library" $ do+    evaluate (derivePubKey (SecKey "a")) `shouldThrow` anyErrorCall+    evaluate (signMsg (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (signMsg keyOne (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (verifySig (derivePubKey keyOne) (Sig "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (verifySig (PubKey "a") (signMsg keyOne satoshiMsg) satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (verifySig (derivePubKey keyOne) (signMsg keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (exportSig (Sig "a")) `shouldThrow` anyErrorCall+    evaluate (exportCompactSig (Sig "a")) `shouldThrow` anyErrorCall+    evaluate (importCompactSig (CompactSig "a")) `shouldThrow` anyErrorCall+    evaluate (normalizeSig (Sig "a")) `shouldThrow` anyErrorCall+    evaluate (isLowS (Sig "a")) `shouldThrow` anyErrorCall+    evaluate (exportPubKey True (PubKey "a")) `shouldThrow` anyErrorCall+    evaluate (tweakAddSecKey keyOne (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (tweakMulSecKey (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (tweakAddPubKey (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (tweakMulPubKey (derivePubKey keyOne) (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (tweakNegate (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (combinePubKeys [derivePubKey keyOne, PubKey "a"]) `shouldThrow` anyErrorCall+    evaluate (tweakAddSecKey (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (tweakMulSecKey keyOne (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (tweakAddPubKey (derivePubKey keyOne) (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (tweakMulPubKey (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (signMsgWith keyOne satoshiMsg (Just "a")) `shouldThrow` anyErrorCall+    evaluate (signSchnorr (SecKey "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (signSchnorr keyOne (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (verifySchnorr (derivePubKey keyOne) (SchnorrSig "a") satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (verifySchnorr (PubKey "a") (signSchnorr keyOne satoshiMsg) satoshiMsg) `shouldThrow` anyErrorCall+    evaluate (verifySchnorr (derivePubKey keyOne) (signSchnorr keyOne satoshiMsg) (Msg "a")) `shouldThrow` anyErrorCall+    evaluate (exportXOnlyPubKey (PubKey "a")) `shouldThrow` anyErrorCall+    evaluate (tweakAddXOnlyPubKey (PubKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (tweakAddXOnlyPubKey (derivePubKey keyOne) (Tweak "a")) `shouldThrow` anyErrorCall+    evaluate (tweakAddXOnlySecKey (SecKey "a") (fromString one)) `shouldThrow` anyErrorCall+    evaluate (tweakAddXOnlySecKey keyOne (Tweak "a")) `shouldThrow` anyErrorCall   where     zeroKey = PubKey (BS.replicate 64 0)  -- * Derived instances -instanceSpec :: SpecWith Ctx+instanceSpec :: Spec instanceSpec = describe "derived instances" $ do-  it "equal values hash equally, whichever way they were built" $ \ctx ->+  it "equal values hash equally, whichever way they were built" $     property $ \(m :: Msg, k :: SecKey) ->-      let p = derivePubKey ctx k-          s = signMsg ctx k m-          sc = signSchnorr ctx k m-       in hash p == hash (fromJust (importPubKey ctx (exportPubKey ctx False p)))-            && hash s == hash (fromJust (importSig ctx (exportSig ctx s)))+      let p = derivePubKey k+          s = signMsg k m+          sc = signSchnorr k m+       in hash p == hash (fromJust (importPubKey (exportPubKey False p)))+            && hash s == hash (fromJust (importSig (exportSig s)))             && hash k == hash (fromJust (secKey k.get))             && hash sc == hash (fromJust (schnorrSig sc.get))-  it "can be fully evaluated" $ \ctx -> do-    let p = derivePubKey ctx keyOne-        s = signMsg ctx keyOne satoshiMsg-    ((p, s, keyOne, satoshiMsg, histTweak, exportCompactSig ctx s, signSchnorr ctx keyOne satoshiMsg) `deepseq` ())+  it "can be fully evaluated" $ do+    let p = derivePubKey keyOne+        s = signMsg keyOne satoshiMsg+    ((p, s, keyOne, satoshiMsg, histTweak, exportCompactSig s, signSchnorr keyOne satoshiMsg) `deepseq` ())       `shouldBe` ()