diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,271 @@
 All notable changes to this project will be documented in this file.
 
 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).
+and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/),
+in which the first two numbers together are the major version.
+
+## [3.1.1] - 2026-12-02
+
+### Changed
+- Every dependency of the library has an upper bound, below its next major
+  version as the Package Versioning Policy counts it, so that a release of a
+  dependency that breaks its API cannot be picked by a solver unchecked.
+  Cabal's check asked for them.
+- `CHANGELOG.md` and `README.md` are in `extra-doc-files`, where Cabal wants
+  documentation, instead of `extra-source-files`.
+- The Haddock links to `PubKey`, `Sig`, `SecKey`, `Msg`, `Tweak`,
+  `CompactSig`, `SchnorrSig`, `RecSig` and `EllSwift` name the type
+  (`t'PubKey'`): each type has a constructor of the same name in the
+  internal modules, which made every such link ambiguous.
+
+## [3.1.0] - 2026-12-02
+
+### Added
+- `Crypto.Secp256k1.EllSwift`: the ElligatorSwift encoding of public keys
+  (`EllSwift`, `ellSwift`, `ellSwiftCreate`, `ellSwiftCreateIO`,
+  `ellSwiftEncode`, `ellSwiftDecode`) and the x-only Diffie-Hellman exchange
+  of BIP 324 (`Party`, `ellSwiftXdhBip324`), through the `ellswift` module of
+  libsecp256k1, for the encrypted transport of the Bitcoin network. The
+  internal module `Crypto.Secp256k1.Internal.EllSwift` has the raw
+  constructor.
+- The flag `ellswift`, on by default: the module needs libsecp256k1 0.4.0 or
+  later, which the package then asks pkg-config for, so that an older
+  library stops the build at the configure step with its version. Ubuntu
+  24.04 ships 0.2.0, without it; turn the flag off there.
+- Tests with every vector of BIP 324 that the API can reach: the 76 of
+  `ellswift_decode_test_vectors.csv`, the 98 values of t of
+  `xswiftec_inv_test_vectors.csv` (decoded back to x: the inverse map itself
+  is not in the API of libsecp256k1), and the keys and shared secrets of the
+  7 rows of `packet_encoding_test_vectors.csv`, copied into `test/data`.
+
+This release breaks the API: a record update of a value of the package no
+longer compiles. It needs a major version: 3.1 is one under the Package
+Versioning Policy.
+
+### Changed
+- `Msg`, `SecKey`, `PubKey`, `Sig`, `CompactSig`, `Tweak`, `SchnorrSig` and
+  `RecSig` have no field `get`. `x.get` still gives the bytes, through an
+  instance of `HasField` in `Crypto.Secp256k1.Internal.Base` and
+  `Crypto.Secp256k1.Internal.Recovery`. The constructors were hidden so
+  that every value is checked, but the field was exported, and a record
+  update such as `key {get = bytes}` replaced the bytes with no check: a
+  secret key of zeros, or a `PubKey` that is no point of the curve. Only an
+  update, or an import list that names `SecKey (get)`, has to change:
+  import the type alone.
+- CI runs through the workflow that the Haskell packages of jprupp share in
+  [jprupp/tools](https://github.com/jprupp/tools), with the check of
+  `stack.yaml` for local paths (`check-stack-paths`) and the cache of the
+  Nix build kept per release of nixpkgs.
+- `scripts/format` is gone: `haskell-format`, from jprupp/tools, formats
+  every Haskell file.
+
+## [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
+
+- Documentation: the README explains the purpose and design of the bindings,
+  with installation steps for every platform, a tutorial, a usage guide, the
+  differences from Bitcoin Core and security notes. Every module, including
+  the foreign imports, has Haddock, and the main module and key functions say
+  why they work the way they do.
+- CI builds, tests and documents the package with Stack, against the
+  libsecp256k1 of Ubuntu and with `stack --nix`.
+- Build with Stackage nightly-2026-11-07.
+
+## [2.0.0] - 2026-11-03
+
+This release follows a review of the bindings, including the changes of
+1.8.0. The raw constructors are hidden, the text instances use standard
+encodings, and more values are validated when they are built. Several
+changes are breaking; see Changed.
+
+### Changed
+
+- The raw constructors of `SecKey`, `PubKey`, `Sig`, `CompactSig`,
+  `SchnorrSig`, `Msg` and `Tweak`, and the `Ctx` constructor, are no longer
+  exported from `Crypto.Secp256k1`. Build values with `secKey`, `pubKey`,
+  `sig`, `compactSig`, `schnorrSig`, `msg`, `tweak` or the import functions.
+  The `get` field is still exported. The constructors remain available from
+  `Crypto.Secp256k1.Internal.Base`, without validation.
+- `tweak` rejects numbers not below the curve order. `sig` rejects a zero
+  component. `Read` and `IsString` follow.
+- `Show`, `Read` and `IsString` for `PubKey` use the compressed SEC1 encoding
+  in hex; `Read` and `IsString` also accept the uncompressed and hybrid
+  encodings. The same instances for `Sig` use the compact encoding in hex.
+  Before, they used the internal representation of libsecp256k1, which is not
+  portable between platforms or library versions.
+- `normalizeSig` is total: `Ctx -> Sig -> Sig`. It returns the lower-S form of
+  any signature. Before, it returned `Nothing` for a signature that was
+  already in that form.
+- `importSig` and `importCompactSig` return `Nothing` for a signature with a
+  zero component. libsecp256k1 parses a DER component that is not below the
+  curve order as zero while reporting success, and such a signature can never
+  verify.
+- `tweakNegate` returns `Just` zero for a zero tweak.
+- `combinePubKeys` raises an error for a raw key of the wrong length, as every
+  other function does, instead of returning `Nothing`.
+- `signSchnorr`, `signSchnorrWithAux` and `signSchnorrIO` verify the signature
+  before returning it, as BIP-340 requires, and raise an error if that fails.
+- The package requires libsecp256k1 0.2.0 or later through `pkg-config`. The
+  Schnorr bindings of 1.8.0 already needed that version to link.
+
+### Added
+
+- ECDSA public key recovery, in the new module `Crypto.Secp256k1.Recovery`:
+  `RecSig`, `recSig`, `signRecMsg`, `recover`, `convertRecSig`,
+  `importCompactRecSig` and `exportCompactRecSig`, bound to the `recovery`
+  module of libsecp256k1. `signRecMsg` gives the signatures of Bitcoin Core's
+  message signing, and `recover` is what its message verification does. The
+  package flag `recovery`, on by default, builds the module; turn it off for a
+  libsecp256k1 built without `--enable-module-recovery`.
+- `signMsgLowR` grinds the nonce until r is below 2^255, with the same extra
+  nonce data as Bitcoin Core, so DER signatures are at most 70 bytes and are
+  byte-for-byte the same as Bitcoin Core's.
+- `isLowS` and `isLowR`.
+- `Show`, `Read` and `IsString` instances for `CompactSig`.
+- `Arbitrary` instance for `Tweak`.
+- Documentation of the thread-safety rule of `randomizeContext`, of what
+  `Show` prints for a `SecKey`, of the memory handling of secret keys, of the
+  lower-S requirement of `verifySig`, of the x-only representation of BIP-340
+  keys, and of the differences from Bitcoin Core.
+
+### Fixed
+
+- `importPubKey` and `exportPubKey` were documented as DER. The format is
+  SEC1.
+- `tweakMulPubKey` was documented as adding a multiple of the generator.
+- Removed the unused `unliftio-core` dependency and unused imports. The
+  library and the tests build with `-Wall` without warnings.
+
+## [1.8.0] - 2026-11-03
+
+### Added
+
+- BIP-340 Schnorr signatures, built on the `schnorrsig` and `extrakeys`
+  modules of libsecp256k1, which it enables by default since version 0.2.0:
+  `SchnorrSig`, `schnorrSig`, `signSchnorr`, `signSchnorrWithAux`,
+  `signSchnorrIO` and `verifySchnorr`. No build flag is needed.
+- `importXOnlyPubKey` and `exportXOnlyPubKey` convert between `PubKey` and
+  32-byte BIP-340 x-only public keys.
+- `tweakAddXOnlyPubKey` and `tweakAddXOnlySecKey` add a BIP-341 Taproot tweak
+  to a public key and to its secret key.
+
+### Fixed
+
+- `secKey` rejects zero and numbers not lower than the curve order, as
+  `secp256k1_ec_seckey_verify` does. `Read` and `IsString` for `SecKey` follow.
+- `pubKey` and `sig` reject bytes that are not a canonical internal
+  representation of a point on the curve or of a signature with both
+  components below the order. `Read` and `IsString` follow.
+- An illegal argument no longer aborts the program. Contexts get a callback
+  that makes libsecp256k1 return failure, so a zero `PubKey` built with the
+  raw constructor gives `False`, `Nothing` or an exception.
+- Functions raise an error for a `SecKey`, `PubKey`, `Sig`, `CompactSig`,
+  `Msg` or `Tweak` of the wrong length built with the raw constructor, instead
+  of letting libsecp256k1 read past the end of the buffer.
+- `combinePubKeys` passes the key count as `size_t`, as the C function expects,
+  and returns `Nothing` when a key is not a valid point, since
+  `secp256k1_ec_pubkey_combine` does not check.
+- Tweak functions write to a fresh buffer instead of mutating a `ByteString`
+  in place.
+
+## [1.7.0] - 2026-10-31
+
+### Added
+
+- Reinstaded some functions removed by accident.
+
+## [1.6.0] - 2026-10-31
+
+### Removed
+
+- No longer does this module expose the destroyContext function.
+  Context is now only destroyed safely by the garbage collector.
+
+## [1.5.1] - 2026-10-31
+
+### Fixed
+
+- This package is now compatible with base16 version 2.0.
+
+## [1.5.0] - 2026-08-12
+
+### Fixed
+
+- Use seckey instead of privkey aliases.
 
 ## [1.4.6] - 2025-05-09
 
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,516 @@
+# secp256k1-haskell
+
+[![Hackage](https://img.shields.io/hackage/v/secp256k1-haskell.svg)](https://hackage.haskell.org/package/secp256k1-haskell)
+[![CI](https://github.com/jprupp/secp256k1-haskell/actions/workflows/ci.yml/badge.svg)](https://github.com/jprupp/secp256k1-haskell/actions/workflows/ci.yml)
+[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jprupp/secp256k1-haskell/blob/master/LICENSE)
+
+Haskell bindings to [libsecp256k1](https://github.com/bitcoin-core/secp256k1),
+the library that Bitcoin Core uses for elliptic curve cryptography on the
+secp256k1 curve. It covers ECDSA signatures, BIP-340 Schnorr signatures,
+BIP-341 Taproot tweaks, key tweaking for BIP-32 derivation, and ECDSA public
+key recovery for Bitcoin signed messages.
+
+- [API documentation](https://hackage.haskell.org/package/secp256k1-haskell)
+- [Changelog](https://github.com/jprupp/secp256k1-haskell/blob/master/CHANGELOG.md)
+- [Report a bug](https://github.com/jprupp/secp256k1-haskell/issues)
+
+## Contents
+
+- [Why secp256k1-haskell](#why-secp256k1-haskell)
+- [Design principles](#design-principles)
+- [Features](#features)
+- [Installation](#installation)
+- [Quick start](#quick-start)
+- [Tutorial: sign, verify and serialize](#tutorial-sign-verify-and-serialize)
+- [Concepts](#concepts)
+- [Usage guide](#usage-guide)
+- [Differences from Bitcoin Core](#differences-from-bitcoin-core)
+- [Module overview](#module-overview)
+- [Security notes](#security-notes)
+- [Development](#development)
+- [Related projects](#related-projects)
+- [License](#license)
+
+## Why secp256k1-haskell
+
+Elliptic curve cryptography is easy to write and very hard to get right. A
+signing routine whose running time depends on the secret key leaks it through
+timing. A nonce that repeats once reveals the key outright. An edge case in
+point arithmetic accepts a forged signature. These are not theoretical: each has
+cost real users real money.
+
+libsecp256k1 is the answer the Bitcoin community converged on. It is
+constant-time wherever secrets are involved, blinds secret key operations
+against side channels, is tested exhaustively, and has been reviewed for over a
+decade. It is what Bitcoin Core runs.
+
+This package lets a Haskell program use that library instead of reimplementing
+it, and wraps it in types that make the usual mistakes hard to make. It is the
+cryptographic foundation of [haskoin-core](https://github.com/jprupp/haskoin-core)
+and, through it, of the rest of the Haskoin libraries.
+
+## Design principles
+
+- **Valid by construction.** Every key, signature, hash and tweak goes through
+  a smart constructor or an import function that checks it. A `PubKey` is
+  always a point on the curve; a `Sig` always has both components in range.
+  Invalid input is refused where it enters the program, not deep inside a
+  computation.
+- **Never abort the process.** By default libsecp256k1 calls `abort()` on an
+  illegal argument, which kills the whole Haskell program and cannot be caught.
+  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`.
+- **Standard encodings at the edges.** `Show`, `Read` and `IsString` use SEC1,
+  compact or plain hex, never libsecp256k1's internal memory layout, which
+  differs between platforms and library versions.
+- **Explicit about Bitcoin Core.** Where Bitcoin Core goes beyond the
+  standards, such as grinding signatures to a low R value or accepting high-S
+  signatures from old blocks, this package offers the behaviour as a separate,
+  documented function instead of silently picking one.
+- **Thin.** Hashing, address encoding, BIP-32 paths and transaction formats
+  belong in higher-level libraries such as haskoin-core.
+
+## Features
+
+| Area                 | What you get                                                                                   |
+| -------------------- | ---------------------------------------------------------------------------------------------- |
+| ECDSA                | Deterministic RFC 6979 signing, Bitcoin Core's low-R grinding, verification, lower-S normalization |
+| Encodings            | SEC1 public keys (33 or 65 bytes), DER and compact signatures, hex `Show`/`Read`/`IsString`    |
+| Schnorr (BIP-340)    | Signing (deterministic, with given or fresh auxiliary randomness), verification, x-only keys    |
+| 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           |
+| ElligatorSwift       | Public keys encoded as 64 random-looking bytes, and the x-only Diffie-Hellman exchange of BIP 324 |
+| 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
+
+- No hashing. Pass a 32-byte hash you computed with a hash library, such as
+  `cryptohash-sha256` or haskoin-core.
+- No plain ECDH, MuSig2 or adaptor signatures, although libsecp256k1 or its
+  forks offer some of them. The one Diffie-Hellman exchange bound is that of
+  BIP 324, on ElligatorSwift encodings.
+- No secure erasure of secret keys from memory. See [Security notes](#security-notes).
+
+## Installation
+
+### System library
+
+The package needs [libsecp256k1](https://github.com/bitcoin-core/secp256k1)
+**0.2.0 or later** and `pkg-config` to find it. Public key recovery also needs
+the library's recovery module, which the packages below include.
+
+```sh
+# Debian and Ubuntu (24.04 ships 0.2.0)
+sudo apt-get install libsecp256k1-dev pkg-config
+
+# Fedora
+sudo dnf install libsecp256k1-devel pkgconf
+
+# macOS with Homebrew
+brew install secp256k1 pkg-config
+
+# Nix
+nix-shell -p secp256k1 pkg-config
+```
+
+Check what you have:
+
+```sh
+pkg-config --modversion libsecp256k1   # must print 0.2.0 or later
+```
+
+Older distributions, such as Debian 11, ship an earlier version. Build the
+library from source then:
+
+```sh
+git clone https://github.com/bitcoin-core/secp256k1.git
+cd secp256k1
+./autogen.sh
+./configure --enable-module-recovery
+make && sudo make install
+```
+
+If your library was built without the recovery module, build this package with
+the `recovery` flag off: `stack build --flag secp256k1-haskell:-recovery`, or
+`cabal build -f -recovery`. Everything except `Crypto.Secp256k1.Recovery` still
+works.
+
+ElligatorSwift (`Crypto.Secp256k1.EllSwift`) needs libsecp256k1 **0.4.0 or
+later**, built with its `ellswift` module, which is on by default. Ubuntu 24.04
+ships 0.2.0, which does not have it; Ubuntu 26.04, Fedora, Homebrew and Nixpkgs
+ship versions that do. With an older library, build this package with the
+`ellswift` flag off: `stack build --flag secp256k1-haskell:-ellswift`, or
+`cabal build -f -ellswift`.
+
+### Step by step with Stack
+
+1. Install [Stack](https://docs.haskellstack.org/) and the library above.
+2. Create a project:
+
+   ```sh
+   stack new sig-demo simple
+   cd sig-demo
+   ```
+
+3. Add `secp256k1-haskell` and `bytestring` to `build-depends` in
+   `sig-demo.cabal`.
+4. If your resolver does not include the package, add it to `stack.yaml`:
+
+   ```yaml
+   extra-deps:
+     - secp256k1-haskell-3.1.1
+     - base16-2.0
+   ```
+
+5. Put the [quick start](#quick-start) program in `src/Main.hs` and run it with
+   `stack run`. It prints `True` three times.
+
+### With Cabal
+
+```cabal
+build-depends:
+    base
+  , bytestring
+  , secp256k1-haskell
+```
+
+Run `cabal update` first, then `cabal build`.
+
+## Quick start
+
+```haskell
+{-# LANGUAGE OverloadedStrings #-}
+
+import Crypto.Secp256k1
+
+main :: IO ()
+main = do
+  -- Hex literals go through IsString, which validates them.
+  let key = "c7e5a2b4f4c5d7e8a9b0c1d2e3f405162738495a6b7c8d9e0f1a2b3c4d5e6f70" :: SecKey
+      hash = "4b688df40bcedbe641ddb16ff0a1842d9c67ea1c3bf63f3e0471baa664531d1a" :: Msg
+      pub = derivePubKey key
+
+  -- ECDSA
+  let s = signMsg key hash
+  print (verifySig pub s hash)
+
+  -- BIP-340 Schnorr, with fresh auxiliary randomness
+  schnorr <- signSchnorrIO key hash
+  print (verifySchnorr pub schnorr hash)
+
+  -- Round trip through the standard encodings
+  let Just pub' = importPubKey (exportPubKey True pub)
+  print (pub == pub')
+```
+
+## Tutorial: sign, verify and serialize
+
+This walks through what a wallet or a protocol implementation typically does,
+and why each step looks the way it does.
+
+### 1. Nothing to set up
+
+```haskell
+import Crypto.Secp256k1
+```
+
+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
+
+```haskell
+case secKey keyBytes of
+  Nothing -> fail "not a valid secret key"
+  Just key -> ...
+```
+
+`secKey` refuses 0 and numbers not below the curve order, so a `SecKey` is
+always usable. In practice, keys come from a wallet: from a BIP-39 mnemonic and
+BIP-32 derivation in haskoin-core, or from 32 bytes of the operating system's
+secure randomness (`getEntropy 32` from the `entropy` package).
+
+### 3. Hash, then sign
+
+The library signs 32-byte hashes, not messages. Which hash to use is part of
+the protocol: Bitcoin transactions use double SHA-256 of a specific
+serialization, BIP-340 uses tagged hashes. Build the `Msg` from your hash:
+
+```haskell
+let Just m = msg hashBytes
+    s = signMsgLowR key m -- or signMsg for plain RFC 6979
+```
+
+Signing is deterministic: the same key and hash give the same signature, so
+there is no random number generator to get wrong.
+
+### 4. Serialize for the wire
+
+Never send the `get` bytes of a `PubKey` or `Sig`: they are libsecp256k1's
+internal layout. Use the standard encodings:
+
+```haskell
+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 pubBytes
+  s <- importSig derBytes
+  m <- msg hashBytes
+  return (verifySig pub (normalizeSig s) m)
+```
+
+Every import returns `Maybe`, so malformed input is handled in one place.
+`normalizeSig` is there because `verifySig` only accepts lower-S signatures;
+apply it when the signature may come from software that does not produce them,
+such as old Bitcoin transactions. Leave it out when your protocol requires
+lower-S, as Bitcoin's relay rules do.
+
+### 6. Move to Schnorr where the protocol allows
+
+```haskell
+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
+uses. `signSchnorrIO` mixes fresh randomness into the nonce, as BIP-340
+recommends, to protect against fault attacks.
+
+## Concepts
+
+### Values
+
+| Type         | What it holds                                            | Built with                              |
+| ------------ | -------------------------------------------------------- | --------------------------------------- |
+| `SecKey`     | 32-byte number from 1 to n − 1                           | `secKey`, `IsString`                    |
+| `PubKey`     | A point on the curve                                     | `importPubKey`, `derivePubKey`          |
+| `Msg`        | 32-byte hash                                             | `msg`                                   |
+| `Sig`        | ECDSA signature with both components from 1 to n − 1    | `signMsg`, `importSig`, `importCompactSig` |
+| `CompactSig` | 64 bytes, r ‖ s                                          | `exportCompactSig`, `compactSig`        |
+| `SchnorrSig` | 64-byte BIP-340 signature                                | `signSchnorr`, `schnorrSig`             |
+| `Tweak`      | 32-byte number from 0 to n − 1                           | `tweak`                                 |
+| `RecSig`     | ECDSA signature with its recovery id                     | `signRecMsg`, `importCompactRecSig`     |
+
+Here n is the order of the curve. The raw constructors are hidden, so these
+are the only ways to build values. `x.get` gives the bytes of a value, with
+`OverloadedRecordDot`. It is not a field, so a record update such as
+`key {get = bytes}` does not compile: an update would replace the bytes
+without the checks.
+`Show` prints hex, except for `SecKey`, which it redacts. See
+[Security notes](#security-notes).
+
+### Contexts
+
+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
+invalid result, such as a tweak that cancels a key, returns `Maybe`. Pure
+operations on valid values, such as signing, cannot fail and return their
+result directly. Programming errors, such as a value of the wrong length built
+with an internal constructor, raise an exception.
+
+## Usage guide
+
+### Lower-S and low-R
+
+```haskell
+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 parentKey t
+    Just childPub = tweakAddPubKey parentPub t
+-- derivePubKey childKey == childPub
+```
+
+This is the operation behind BIP-32 derivation; the tweak itself comes from an
+HMAC of the chain code, computed by haskoin-core. `tweakMulSecKey`,
+`tweakMulPubKey`, `tweakNegate` and `combinePubKeys` cover the other group
+operations.
+
+### Taproot
+
+```haskell
+let Just t = tweak taprootTweakBytes -- tagged hash of key and script tree
+    Just outputKey = tweakAddXOnlyPubKey internalKey t
+    Just outputSecKey = tweakAddXOnlySecKey internalSecKey t
+```
+
+Computing the tweak, a BIP-341 tagged hash, is left to the caller.
+
+### Bitcoin signed messages
+
+```haskell
+import Crypto.Secp256k1.Recovery
+
+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 r m -- Just the signer's PubKey
+```
+
+### ElligatorSwift and BIP 324
+
+```haskell
+import Crypto.Secp256k1.EllSwift
+
+-- each side makes its encoded key with fresh randomness and sends the 64 bytes
+ours <- ellSwiftCreateIO key
+-- the initiator of the connection is party A, the responder party B
+let secret = ellSwiftXdhBip324 ours theirs key PartyA -- 32 bytes
+ellSwiftDecode theirs -- the PubKey behind an encoding, if one needs it
+```
+
+The exchange is unauthenticated: it stops a passive observer, not a man in the
+middle. See the module header.
+
+### Testing with QuickCheck
+
+`SecKey`, `Msg` and `Tweak` have `Arbitrary` instances, so properties can
+range over them directly:
+
+```haskell
+prop_roundTrip :: SecKey -> Msg -> Bool
+prop_roundTrip key m =
+  verifySig (derivePubKey key) (signMsg key m) m
+```
+
+## Differences from Bitcoin Core
+
+| Topic                      | This package                                     | Bitcoin Core                          |
+| -------------------------- | ------------------------------------------------ | ------------------------------------- |
+| ECDSA nonce                | `signMsg`: plain RFC 6979                        | Grinds for low R                      |
+| Low-R signatures           | `signMsgLowR`: same grinding, same signatures    | Default since 0.17                    |
+| High-S signatures          | `verifySig` refuses them; use `normalizeSig`     | Normalizes before verifying           |
+| Verify after ECDSA signing | No                                               | Yes, as a precaution                  |
+| Taproot tweak when signing | Separate step: `tweakAddXOnlySecKey`             | Built into Schnorr signing            |
+| Message signatures         | `signRecMsg`, no grinding                        | Same, so signatures are identical     |
+
+## Module overview
+
+| Module                                  | Contents                                                  |
+| --------------------------------------- | --------------------------------------------------------- |
+| `Crypto.Secp256k1`                      | The public API: keys, ECDSA, Schnorr, tweaks              |
+| `Crypto.Secp256k1.Recovery`             | Recoverable signatures and public key recovery            |
+| `Crypto.Secp256k1.EllSwift`             | ElligatorSwift encodings and the BIP 324 key exchange     |
+| `Crypto.Secp256k1.Internal.*`           | Raw constructors and helpers; no stability promise        |
+
+The exposed internal modules are `Base`, `Recovery`, `EllSwift`, `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`, `EllSwiftOps`), 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` 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.
+- **Use fresh randomness for Schnorr when you can.** `signSchnorrIO` protects
+  against fault attacks that deterministic signing does not.
+- **Keep libsecp256k1 up to date.** Security fixes land in the C library;
+  this package only binds it.
+
+## Development
+
+```sh
+git clone https://github.com/jprupp/secp256k1-haskell.git
+cd secp256k1-haskell
+
+stack build                        # build against the system library
+stack --nix build                  # or take GHC and libsecp256k1 from nixpkgs
+stack test                         # run the tests
+stack haddock --no-haddock-deps    # build the API documentation
+```
+
+`package.yaml` is the source of the package description. Change it rather than
+`secp256k1-haskell.cabal`, which [hpack](https://github.com/sol/hpack)
+generates.
+
+The tests are in `test/` and use [hspec](https://hspec.github.io/) and
+QuickCheck, with published test vectors from RFC 6979, Bitcoin Core and
+BIP-340. CI runs them with the system library and
+with `stack --nix`.
+
+### Contributing
+
+Pull requests are welcome.
+
+- Add tests for the behaviour you change, with published test vectors where
+  they exist.
+- Keep the documentation in step with the code, as `CLAUDE.md` describes.
+- Describe the change in `CHANGELOG.md`, which follows
+  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
+
+## Related projects
+
+- [haskoin-core](https://github.com/jprupp/haskoin-core) builds Bitcoin keys,
+  addresses, transactions and PSBTs on this package.
+- [libsecp256k1](https://github.com/bitcoin-core/secp256k1) is the C library
+  underneath.
+
+## License
+
+secp256k1-haskell is released under the
+[MIT License](https://github.com/jprupp/secp256k1-haskell/blob/master/LICENSE).
diff --git a/Setup.hs b/Setup.hs
--- a/Setup.hs
+++ b/Setup.hs
@@ -1,2 +1,3 @@
 import Distribution.Simple
+
 main = defaultMain
diff --git a/cbits/illegal_callback.c b/cbits/illegal_callback.c
new file mode 100644
--- /dev/null
+++ b/cbits/illegal_callback.c
@@ -0,0 +1,17 @@
+/*
+ * Illegal-argument callback installed on every context this package creates.
+ *
+ * The default callback of libsecp256k1 prints the message to stderr and calls
+ * abort(). That kills the whole Haskell process and cannot be caught. With
+ * this callback installed, the C function that received the illegal argument
+ * returns 0 instead, and the Haskell side turns that into Nothing, False or
+ * an ErrorCall exception.
+ *
+ * The error callback, which reports internal consistency failures of the
+ * library itself, keeps its default. Those indicate a broken build and
+ * should still abort.
+ */
+void secp256k1_haskell_illegal_callback(const char *message, void *data) {
+  (void)message;
+  (void)data;
+}
diff --git a/secp256k1-haskell.cabal b/secp256k1-haskell.cabal
--- a/secp256k1-haskell.cabal
+++ b/secp256k1-haskell.cabal
@@ -1,11 +1,11 @@
 cabal-version: 2.0
 
--- This file has been generated from package.yaml by hpack version 0.38.0.
+-- This file has been generated from package.yaml by hpack version 0.39.6.
 --
 -- see: https://github.com/sol/hpack
 
 name:           secp256k1-haskell
-version:        1.4.6
+version:        3.1.1
 synopsis:       Bindings for secp256k1
 description:    Sign and verify signatures using the secp256k1 library.
 category:       Crypto
@@ -17,65 +17,125 @@
 license-file:   LICENSE
 build-type:     Simple
 extra-source-files:
+    test/data/ellswift_decode_test_vectors.csv
+    test/data/packet_encoding_test_vectors.csv
+    test/data/xswiftec_inv_test_vectors.csv
+extra-doc-files:
     CHANGELOG.md
+    README.md
 
 source-repository head
   type: git
   location: https://github.com/jprupp/secp256k1-haskell
 
+flag ellswift
+  description: Bind the ElligatorSwift module of libsecp256k1, which BIP 324 uses. The library must be version 0.4.0 or later, built with the module, which is the default; Ubuntu 24.04 ships 0.2.0, without it. Turn the flag off for a library without it.
+  manual: True
+  default: True
+
+flag recovery
+  description: Bind the ECDSA public key recovery module of libsecp256k1. The library must have been built with it (--enable-module-recovery), as the packages of the Linux distributions, Homebrew and Nixpkgs are. Turn the flag off for a library built without it.
+  manual: True
+  default: True
+
 library
   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:
       src
+  ghc-options: -Wall
+  c-sources:
+      cbits/illegal_callback.c
   pkgconfig-depends:
-      libsecp256k1
+      libsecp256k1 >= 0.2.0
   build-depends:
-      QuickCheck >=2.9.2
+      QuickCheck >=2.9.2 && <2.18
     , base >=4.9 && <5
-    , base16 >=1.0
-    , bytestring >=0.10.8
-    , deepseq >=1.4.2
-    , entropy >=0.3.8
-    , hashable >=1.2.6
-    , string-conversions >=0.4
-    , unliftio-core >=0.1.0
+    , base16 ==2.0.*
+    , bytestring >=0.10.8 && <0.13
+    , deepseq >=1.4.2 && <1.6
+    , entropy >=0.3.8 && <0.5
+    , hashable >=1.2.6 && <1.6
+    , string-conversions ==0.4.*
   default-language: Haskell2010
+  if flag(recovery)
+    exposed-modules:
+        Crypto.Secp256k1.Internal.Recovery
+        Crypto.Secp256k1.Recovery
+    other-modules:
+        Crypto.Secp256k1.Internal.RecoveryOps
+  if flag(ellswift)
+    exposed-modules:
+        Crypto.Secp256k1.EllSwift
+        Crypto.Secp256k1.Internal.EllSwift
+    other-modules:
+        Crypto.Secp256k1.Internal.EllSwiftOps
+    pkgconfig-depends:
+        libsecp256k1 >= 0.4.0
 
 test-suite spec
   type: exitcode-stdio-1.0
   main-is: Spec.hs
   other-modules:
+      Crypto.Secp256k1.EllSwiftSpec
+      Crypto.Secp256k1.Fixtures
       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
-  ghc-options: -threaded -rtsopts -with-rtsopts=-N
+      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
+    , QuickCheck >=2.9.2 && <2.18
     , base >=4.9 && <5
-    , base16 >=1.0
-    , bytestring >=0.10.8
-    , deepseq >=1.4.2
-    , entropy >=0.3.8
-    , hashable >=1.2.6
+    , base16 ==2.0.*
+    , bytestring >=0.10.8 && <0.13
+    , deepseq >=1.4.2 && <1.6
+    , entropy >=0.3.8 && <0.5
+    , hashable >=1.2.6 && <1.6
     , hspec
     , monad-par
     , mtl
-    , secp256k1-haskell
-    , string-conversions >=0.4
-    , unliftio-core >=0.1.0
+    , 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
+  if flag(ellswift)
+    other-modules:
+        Crypto.Secp256k1.EllSwift
+        Crypto.Secp256k1.Internal.EllSwift
+        Crypto.Secp256k1.Internal.EllSwiftOps
+    cpp-options: -DELLSWIFT
+    pkgconfig-depends:
+        libsecp256k1 >= 0.4.0
   build-tool-depends: hspec-discover:hspec-discover
diff --git a/src/Crypto/Secp256k1.hs b/src/Crypto/Secp256k1.hs
--- a/src/Crypto/Secp256k1.hs
+++ b/src/Crypto/Secp256k1.hs
@@ -1,47 +1,193 @@
 {-# LANGUAGE DuplicateRecordFields #-}
-module Crypto.Secp256k1
-  ( -- * Context
-    Ctx (..),
-    withContext,
-    randomizeContext,
-    createContext,
-    cloneContext,
-    destroyContext,
 
-    -- * Messages
-    Msg (..),
+-- | ECDSA and BIP-340 Schnorr signatures on the secp256k1 curve, through
+-- <https://github.com/bitcoin-core/secp256k1 libsecp256k1>.
+--
+-- == Purpose
+--
+-- secp256k1 is the elliptic curve of Bitcoin, and libsecp256k1 is the C
+-- library Bitcoin Core uses for it: constant-time where secrets are involved,
+-- hardened against side channels, exhaustively tested and reviewed. Getting
+-- elliptic curve cryptography right is hard enough that a Haskell program
+-- should not reimplement it. This package gives Haskell the same library, with
+-- types that make the common mistakes hard to make.
+--
+-- == Design
+--
+-- * __Valid by construction.__ Every value goes through a smart constructor or
+--   an import function that checks it. Code that holds a t'PubKey' or a t'Sig'
+--   never has to wonder whether it is a point on the curve or a well-formed
+--   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. 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',
+--   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
+--   library's internal memory layout, which differs between platforms.
+--
+-- * __Bitcoin Core compatibility is explicit.__ Where Bitcoin Core does
+--   something beyond the standards, such as low-R grinding or accepting high-S
+--   signatures from old blocks, this package offers it as a separate function
+--   and documents the difference, rather than silently picking one behaviour.
+--
+-- == Values
+--
+-- Every value is built through a smart constructor or an import function
+-- that validates it, so a value of one of these types is always well formed:
+--
+-- * t'SecKey': a 32-byte big-endian number in the range 1 to n−1, where n is
+--   the order of the curve ('secKey').
+-- * t'PubKey': a point on the curve ('importPubKey' for the SEC1 encoding).
+-- * t'Sig': a signature whose components are both in the range 1 to n−1
+--   ('importSig' for DER, 'importCompactSig' for the compact encoding).
+-- * t'Msg': a 32-byte hash ('msg').
+-- * t'Tweak': a 32-byte big-endian number in the range 0 to n−1 ('tweak').
+-- * t'SchnorrSig': a 64-byte BIP-340 signature ('schnorrSig' checks the
+--   length, 'verifySchnorr' the values).
+--
+-- @x.get@ gives the bytes of a value, with @OverloadedRecordDot@. For
+-- t'SecKey', t'Msg', t'Tweak', t'CompactSig' and t'SchnorrSig' these are the
+-- standard big-endian bytes. For t'PubKey' and t'Sig' they are the internal
+-- representation of libsecp256k1, which is opaque and not portable. Use
+-- 'exportPubKey', 'exportSig' and 'exportCompactSig' to serialize those.
+-- @get@ is not a field, so a record update cannot replace the bytes of a
+-- value without the checks: see the instances of
+-- "Crypto.Secp256k1.Internal.Base".
+--
+-- 'Show', 'Read' and 'Data.String.IsString' use hex of a standard encoding: compressed
+-- SEC1 for t'PubKey', compact for t'Sig', and the plain bytes for the others.
+-- The one exception is 'Show' for t'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 t'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.
+--
+-- == Schnorr signatures
+--
+-- BIP-340 public keys are x-only: the 32-byte x coordinate of a point whose
+-- y coordinate is even. This module keeps them as t'PubKey' and converts with
+-- 'importXOnlyPubKey' and 'exportXOnlyPubKey'. 'verifySchnorr' uses only the
+-- x coordinate, so a key and its negation verify the same signatures.
+-- 'tweakAddXOnlyPubKey' and 'tweakAddXOnlySecKey' apply a BIP-341 Taproot
+-- tweak. Computing the tweak itself, a tagged hash of the internal key and
+-- the script tree, is left to the caller.
+--
+-- 'signSchnorr' is deterministic. BIP-340 recommends fresh auxiliary
+-- randomness for every signature, which 'signSchnorrIO' provides. Every
+-- Schnorr signing function verifies the signature before returning it, as
+-- BIP-340 requires.
+--
+-- == Contexts
+--
+-- 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.
+-- Bitcoin Core also grinds the nonce until r is below 2^255, which keeps DER
+-- signatures at 70 bytes. 'signMsgLowR' does the same and gives the same
+-- signatures as Bitcoin Core.
+--
+-- 'verifySig' only accepts lower-S signatures, as libsecp256k1 does. Bitcoin
+-- Core normalizes a signature before verifying it, because high-S signatures
+-- exist in old blocks. Use 'normalizeSig' before 'verifySig' for that.
+--
+-- Bitcoin Core verifies every ECDSA signature it makes, as a precaution
+-- against a corrupted signature. 'signMsg' does not. The Schnorr signing
+-- functions do, because BIP-340 requires it.
+--
+-- Bitcoin Core's Schnorr signing applies the Taproot tweak itself when it is
+-- given a Merkle root. Here 'tweakAddXOnlySecKey' does that step separately.
+--
+-- == Public key recovery
+--
+-- ECDSA public key recovery, which Bitcoin signed messages use, is in the
+-- module @Crypto.Secp256k1.Recovery@. It is built when the @recovery@ flag of
+-- the package is on, which is the default.
+module Crypto.Secp256k1
+  ( -- * Messages
+    Msg,
     msg,
 
     -- * Secret Keys
-    SecKey (..),
+    SecKey,
     secKey,
     derivePubKey,
 
     -- * Public Keys
-    PubKey (..),
+    PubKey,
     pubKey,
     importPubKey,
     exportPubKey,
 
     -- * Signatures
-    Sig (..),
+    Sig,
     sig,
     signMsg,
+    signMsgLowR,
     verifySig,
     normalizeSig,
+    isLowS,
+    isLowR,
 
     -- ** DER
     importSig,
     exportSig,
 
     -- ** Compact
-    CompactSig (..),
+    CompactSig,
     compactSig,
     exportCompactSig,
     importCompactSig,
 
     -- * Addition & Multiplication
-    Tweak (..),
+    Tweak,
     tweak,
     tweakAddSecKey,
     tweakMulSecKey,
@@ -49,8 +195,23 @@
     tweakMulPubKey,
     combinePubKeys,
     tweakNegate,
+
+    -- * Schnorr Signatures (BIP-340)
+    SchnorrSig,
+    schnorrSig,
+    signSchnorr,
+    signSchnorrWithAux,
+    signSchnorrIO,
+    verifySchnorr,
+
+    -- ** X-Only Public Keys
+    importXOnlyPubKey,
+    exportXOnlyPubKey,
+
+    -- ** Taproot Tweaks (BIP-341)
+    tweakAddXOnlyPubKey,
+    tweakAddXOnlySecKey,
   )
 where
 
 import Crypto.Secp256k1.Internal.Base
-import Crypto.Secp256k1.Internal.Context
diff --git a/src/Crypto/Secp256k1/EllSwift.hs b/src/Crypto/Secp256k1/EllSwift.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/EllSwift.hs
@@ -0,0 +1,67 @@
+-- | ElligatorSwift encoding of public keys and the x-only Diffie-Hellman
+-- exchange of BIP 324, through the @ellswift@ module of
+-- <https://github.com/bitcoin-core/secp256k1 libsecp256k1>.
+--
+-- == What it is for
+--
+-- A public key on the wire is easy to spot: an x coordinate is a field
+-- element for which a square root exists, and a compressed key starts with 2
+-- or 3. A censor that looks for such bytes can tell an encrypted Bitcoin
+-- connection from other traffic. ElligatorSwift (Chávez-Saab,
+-- Rodríguez-Henríquez and Tibouchi, <https://eprint.iacr.org/2022/759>)
+-- encodes a point as 64 bytes that are indistinguishable from uniformly
+-- random bytes. The encoding is not unique: it is chosen at random among the
+-- many that decode to the point. BIP 324, the encrypted transport of the
+-- Bitcoin network, sends each side's key this way.
+--
+-- 'ellSwiftCreate' makes the encoded public key of a secret key,
+-- 'ellSwiftEncode' encodes a public key one already has, and
+-- 'ellSwiftDecode' gives back the point. 'ellSwiftXdhBip324' is the
+-- Diffie-Hellman exchange of BIP 324 on two encodings, which is all a
+-- transport needs: it never has to decode a key.
+--
+-- == What it does not do
+--
+-- The encoding hides that a key is a key; it does not say whose key it is.
+-- A Diffie-Hellman exchange on keys that nobody vouches for is
+-- unauthenticated: a man in the middle can run one exchange with each side.
+-- BIP 324 accepts that and says so; it only makes passive observation
+-- impossible and active interception detectable afterwards, by comparing the
+-- session ids out of band.
+--
+-- == The ellswift module of libsecp256k1
+--
+-- The module is in libsecp256k1 from version 0.4.0 on, and the build turns
+-- it on by default. Ubuntu 24.04 ships 0.2.0, which does not have it; Fedora,
+-- Arch, Homebrew, Nixpkgs and Ubuntu 26.04 ship versions that do. This
+-- package binds it when its @ellswift@ flag is on, which is the default,
+-- and then asks pkg-config for libsecp256k1 0.4.0 or later: with an older
+-- library the build stops at the configure step and names the version it
+-- found. Build the package with @-f -ellswift@ then, and this module is not
+-- available. A library of 0.4.0 or later built without the module (it is
+-- on by default) fails later, at the link, with an undefined reference to
+-- @secp256k1_ellswift_create@.
+--
+-- == Values
+--
+-- t'EllSwift' holds the 64 bytes of an encoding, which are standard and
+-- portable, unlike the @get@ field of a 'Crypto.Secp256k1.PubKey'. Any 64
+-- bytes are valid, so 'ellSwift' only checks the length. The raw constructor
+-- is in "Crypto.Secp256k1.Internal.EllSwift", which has no API stability
+-- guarantee.
+module Crypto.Secp256k1.EllSwift
+  ( -- * Encodings
+    EllSwift (get),
+    ellSwift,
+    ellSwiftCreate,
+    ellSwiftCreateIO,
+    ellSwiftEncode,
+    ellSwiftDecode,
+
+    -- * Diffie-Hellman exchange of BIP 324
+    Party (..),
+    ellSwiftXdhBip324,
+  )
+where
+
+import Crypto.Secp256k1.Internal.EllSwift
diff --git a/src/Crypto/Secp256k1/Internal/Base.hs b/src/Crypto/Secp256k1/Internal/Base.hs
--- a/src/Crypto/Secp256k1/Internal/Base.hs
+++ b/src/Crypto/Secp256k1/Internal/Base.hs
@@ -1,16 +1,33 @@
+{-# LANGUAGE DataKinds #-}
 {-# LANGUAGE DeriveGeneric #-}
 {-# LANGUAGE DuplicateRecordFields #-}
-{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
 {-# LANGUAGE ImportQualifiedPost #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE OverloadedRecordDot #-}
 {-# LANGUAGE NoFieldSelectors #-}
+
+-- | Internal module. Everything is exported, including the raw constructors
+-- that "Crypto.Secp256k1" hides, and there is no API stability guarantee.
+--
+-- A value built with a raw constructor skips validation. Every function here
+-- still checks the length of its bytes before calling the C library and
+-- raises an 'Control.Exception.ErrorCall' when the length is wrong, but it does not check the
+-- content. A raw t'PubKey' or t'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)
-import Control.Exception (bracket)
-import Control.Monad (replicateM, unless, (<=<))
+import Control.Exception (evaluate, finally)
+import Control.Monad (guard, join, replicateM, unless, (<=<))
+import Control.Monad.IO.Class (MonadIO, liftIO)
 import Crypto.Secp256k1.Internal.BaseOps
   ( ecPubKeyCombine,
     ecPubKeyCreate,
@@ -28,42 +45,60 @@
     ecdsaSignatureSerializeCompact,
     ecdsaSignatureSerializeDer,
     ecdsaVerify,
+    keyPairCreate,
+    keyPairSec,
+    keyPairXOnlyPub,
+    keyPairXOnlyTweakAdd,
+    schnorrSigSign32,
+    schnorrSigVerify,
+    xOnlyPubKeyFromPubKey,
+    xOnlyPubKeySerialize,
+    xOnlyPubKeyTweakAdd,
   )
-import Crypto.Secp256k1.Internal.Context (Ctx (..))
+import Crypto.Secp256k1.Internal.Context (globalContext)
 import Crypto.Secp256k1.Internal.ForeignTypes
-  ( LCtx,
+  ( KeyPair96,
+    SchnorrSig64,
+    XOnlyPubKey64,
     compressed,
     isSuccess,
     uncompressed,
   )
 import Crypto.Secp256k1.Internal.Util
   ( decodeHex,
+    fillOutput,
     packByteString,
     showsHex,
-    unsafePackByteString,
     unsafeUseByteString,
+    useFixedByteString,
+    withCopy,
+    withOutput,
+    wrongLength,
   )
+import Data.Bits (shiftR)
 import Data.ByteString (ByteString)
 import Data.ByteString qualified as BS
 import Data.Hashable (Hashable (..))
 import Data.Maybe (fromJust, fromMaybe, isJust)
 import Data.String (IsString (..))
+import Data.Word (Word32)
 import Foreign
-  ( Bits (bitSize),
-    Ptr,
+  ( Ptr,
     alloca,
     allocaArray,
     allocaBytes,
-    free,
-    mallocBytes,
+    castPtr,
+    fillBytes,
     nullFunPtr,
     nullPtr,
     peek,
     poke,
     pokeArray,
-    withForeignPtr,
   )
+import Foreign.C (CUChar)
 import GHC.Generics (Generic)
+import GHC.Records (HasField (..))
+import System.Entropy (getEntropy)
 import System.IO.Unsafe (unsafePerformIO)
 import Test.QuickCheck
   ( Arbitrary (..),
@@ -78,36 +113,113 @@
     readPrec,
   )
 
-newtype PubKey = PubKey {get :: ByteString}
+-- | Public key in the internal representation of libsecp256k1 (64 bytes).
+--
+-- The bytes in @get@ are opaque. They are not a standard encoding, and they
+-- are not portable between platforms or library versions. Use 'exportPubKey'
+-- to serialize a key and 'importPubKey' to parse one. 'pubKey' only exists to
+-- rebuild a key from the bytes of @get@ on the same platform.
+--
+-- 'Show', 'Read' and 'IsString' use the compressed SEC1 encoding in hex.
+-- 'Read' and 'IsString' also accept the uncompressed and hybrid encodings.
+newtype PubKey = PubKey ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
-newtype Msg = Msg {get :: ByteString}
+-- | 32-byte message hash to sign or verify.
+--
+-- This must be the output of a cryptographic hash function chosen by the
+-- verifier. Verifying a value that an attacker can choose makes it easy to
+-- produce a signature that verifies without knowing the secret key.
+--
+-- 'Show', 'Read' and 'IsString' use hex.
+newtype Msg = Msg ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
-newtype Sig = Sig {get :: ByteString}
+-- | ECDSA signature in the internal representation of libsecp256k1 (64
+-- bytes). Both components of a valid t'Sig' are in the range 1 to n−1, where n
+-- is the order of the curve.
+--
+-- The bytes in @get@ are opaque and not portable. Use 'exportSig' (DER) or
+-- 'exportCompactSig' (64-byte r‖s) to serialize. 'sig' only exists to rebuild
+-- a signature from the bytes of @get@ on the same platform.
+--
+-- 'Show', 'Read' and 'IsString' use the compact encoding in hex: r and s as
+-- 32-byte big-endian numbers.
+newtype Sig = Sig ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
-newtype SecKey = SecKey {get :: ByteString}
+-- | 32-byte secret key as a big-endian number in the range 1 to n−1, where n
+-- is the order of the curve.
+--
+-- '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 ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
-newtype Tweak = Tweak {get :: ByteString}
+-- | 32-byte scalar as a big-endian number in the range 0 to n−1, to add to or
+-- multiply with a key. 'Show', 'Read' and 'IsString' use hex.
+newtype Tweak = Tweak ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
-newtype CompactSig = CompactSig {get :: ByteString}
+-- | Compact signature encoding: r and s as 32-byte big-endian numbers.
+-- 'compactSig' only checks the length. 'importCompactSig' checks the values.
+-- 'Show', 'Read' and 'IsString' use hex.
+newtype CompactSig = CompactSig ByteString
   deriving (Eq, Generic, Hashable, NFData)
 
+-- | BIP-340 Schnorr signature. Unlike t'Sig', the 64 bytes in @get@ are the
+-- serialized form that BIP-340 defines, r‖s as 32-byte big-endian numbers,
+-- which is the same on every platform. 'schnorrSig' only checks the length.
+-- 'verifySchnorr' checks the values. 'Show', 'Read' and 'IsString' use hex.
+newtype SchnorrSig = SchnorrSig ByteString
+  deriving (Eq, Generic, Hashable, NFData)
+
+-- | The bytes of a value, read as @x.get@ with @OverloadedRecordDot@.
+--
+-- @get@ is not a field, on purpose. A field that a module exports reads the
+-- bytes, but it also lets a record update replace them, as in
+-- @key {get = bytes}@, even where the constructor is hidden, and an update
+-- checks nothing. A t'PubKey' that is no point of the curve would then reach
+-- the functions of the package, and an address made of it could never be
+-- spent. These instances give the reading without the update. The one way
+-- around the checks left is @to@ of 'GHC.Generics.Generic', which no
+-- program calls by accident, and the constructors of this module.
+instance HasField "get" PubKey ByteString where
+  getField (PubKey bytes) = bytes
+
+instance HasField "get" Msg ByteString where
+  getField (Msg bytes) = bytes
+
+instance HasField "get" Sig ByteString where
+  getField (Sig bytes) = bytes
+
+instance HasField "get" SecKey ByteString where
+  getField (SecKey bytes) = bytes
+
+instance HasField "get" Tweak ByteString where
+  getField (Tweak bytes) = bytes
+
+instance HasField "get" CompactSig ByteString where
+  getField (CompactSig bytes) = bytes
+
+instance HasField "get" SchnorrSig ByteString where
+  getField (SchnorrSig bytes) = bytes
+
 instance Read PubKey where
   readPrec = parens $ do
     String str <- lexP
-    maybe pfail return $ pubKey =<< decodeHex str
+    maybe pfail return $ importPubKey =<< decodeHex str
 
 instance IsString PubKey where
-  fromString = fromMaybe e . (pubKey <=< decodeHex)
+  fromString = fromMaybe e . (importPubKey <=< decodeHex)
     where
       e = error "Could not decode public key from hex string"
 
 instance Show PubKey where
-  showsPrec _ = showsHex . (.get)
+  showsPrec _ = showsHex . exportPubKey True
 
 instance Read Msg where
   readPrec = parens $ do
@@ -125,15 +237,15 @@
 instance Read Sig where
   readPrec = parens $ do
     String str <- lexP
-    maybe pfail return $ sig =<< decodeHex str
+    maybe pfail return $ sigFromCompactBytes =<< decodeHex str
 
 instance IsString Sig where
-  fromString = fromMaybe e . (sig <=< decodeHex)
+  fromString = fromMaybe e . (sigFromCompactBytes <=< decodeHex)
     where
       e = error "Could not decode signature from hex string"
 
 instance Show Sig where
-  showsPrec _ = showsHex . (.get)
+  showsPrec _ = showsHex . (.get) . exportCompactSig
 
 instance Read SecKey where
   readPrec = parens $ do
@@ -143,10 +255,21 @@
 instance IsString SecKey where
   fromString = fromMaybe e . (secKey <=< decodeHex)
     where
-      e = error "Colud not decode secret key from hex string"
+      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
@@ -161,275 +284,626 @@
 instance Show Tweak where
   showsPrec _ = showsHex . (.get)
 
--- | Import 64-byte 'ByteString' as 'Sig'.
+instance Read CompactSig where
+  readPrec = parens $ do
+    String str <- lexP
+    maybe pfail return $ compactSig =<< decodeHex str
+
+instance IsString CompactSig where
+  fromString = fromMaybe e . (compactSig <=< decodeHex)
+    where
+      e = error "Could not decode compact signature from hex string"
+
+instance Show CompactSig where
+  showsPrec _ = showsHex . (.get)
+
+instance Read SchnorrSig where
+  readPrec = parens $ do
+    String str <- lexP
+    maybe pfail return $ schnorrSig =<< decodeHex str
+
+instance IsString SchnorrSig where
+  fromString = fromMaybe e . (schnorrSig <=< decodeHex)
+    where
+      e = error "Could not decode Schnorr signature from hex string"
+
+instance Show SchnorrSig where
+  showsPrec _ = showsHex . (.get)
+
+-- | Parse the 64-byte compact encoding into a t'Sig'. Used by the 'Read' and
+-- 'IsString' instances.
+sigFromCompactBytes :: ByteString -> Maybe Sig
+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
+    ]
+
+-- | Thirty-two zero bytes.
+zero32 :: ByteString
+zero32 = BS.replicate 32 0
+
+-- | True when the bytes are a 32-byte big-endian number lower than the curve
+-- order. 'ByteString' comparison is lexicographic, which for two strings of
+-- the same length is the numeric order of the big-endian numbers.
+belowCurveOrder :: ByteString -> Bool
+belowCurveOrder bs = BS.length bs == 32 && bs < curveOrder
+
+-- | Import a signature from the bytes of its internal representation, as
+-- found in the @get@ field of a t'Sig' on the same platform. 'Nothing' unless
+-- the bytes are the canonical representation of a signature whose components
+-- are both in the range 1 to n−1. Signatures from other sources go through
+-- 'importSig' or 'importCompactSig'.
 sig :: ByteString -> Maybe Sig
 sig bs
-  | BS.length bs == 64 = Just (Sig bs)
+  | isCanonicalSig bs = Just (Sig bs)
   | otherwise = Nothing
 
--- | Import 64-byte 'ByteString' as 'PubKey'.
+-- | Serialize the internal bytes to the compact encoding, parse that back and
+-- compare. Parsing checks that both components are below the curve order.
+-- Comparing the bytes rejects non-canonical forms, so that each signature has
+-- one representation and 'Eq' is meaningful. Zero components are rejected
+-- too, because such a signature can never verify.
+isCanonicalSig :: ByteString -> Bool
+isCanonicalSig bs =
+  BS.length bs == 64
+    && unsafePerformIO
+      ( 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)
+      )
+
+-- | True when neither r nor s of a compact-encoded signature is zero.
+hasNonZeroComponents :: ByteString -> Bool
+hasNonZeroComponents compact =
+  BS.take 32 compact /= zero32 && BS.drop 32 compact /= zero32
+
+-- | Import a public key from the bytes of its internal representation, as
+-- found in the @get@ field of a t'PubKey' on the same platform. 'Nothing'
+-- unless the bytes are the canonical representation of a point on the curve.
+-- Keys from other sources go through 'importPubKey'.
 pubKey :: ByteString -> Maybe PubKey
 pubKey bs
-  | BS.length bs == 64 = Just (PubKey bs)
+  | isCanonicalPubKey bs = Just (PubKey bs)
   | otherwise = Nothing
 
--- | Import 32-byte 'ByteString' as 'Msg'.
+-- | Serialize the internal bytes as an uncompressed key, parse that back and
+-- compare. Parsing checks that the point is on the curve. Comparing the bytes
+-- rejects non-canonical forms, so that each point has one representation and
+-- 'Eq' is meaningful.
+--
+-- The serialization must be uncompressed. A compressed serialization drops
+-- the y coordinate, so invalid bytes with a valid x would be accepted as a
+-- different point.
+isCanonicalPubKey :: ByteString -> Bool
+isCanonicalPubKey bs =
+  BS.length bs == 64
+    && unsafePerformIO
+      ( 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)
+      )
+
+-- | Import a 32-byte message hash.
 msg :: ByteString -> Maybe Msg
 msg bs
   | BS.length bs == 32 = Just (Msg bs)
   | otherwise = Nothing
 
--- | Import 32-byte 'ByteString' as 'SecKey'.
+-- | Import a 32-byte big-endian secret key. 'Nothing' unless the number is in
+-- the range 1 to n−1, which is what @secp256k1_ec_seckey_verify@ requires.
 secKey :: ByteString -> Maybe SecKey
 secKey bs
-  | BS.length bs == 32 = Just (SecKey bs)
+  | belowCurveOrder bs && bs /= zero32 = Just (SecKey bs)
   | otherwise = Nothing
 
+-- | Import a 32-byte big-endian tweak. 'Nothing' unless the number is in the
+-- range 0 to n−1. Zero is allowed because adding it is harmless, but
+-- multiplying by it fails.
+tweak :: ByteString -> Maybe Tweak
+tweak bs
+  | belowCurveOrder bs = Just (Tweak bs)
+  | otherwise = Nothing
+
+-- | Import a 64-byte compact signature encoding. Only the length is checked.
+-- 'importCompactSig' checks the values.
 compactSig :: ByteString -> Maybe CompactSig
 compactSig bs
   | BS.length bs == 64 = Just (CompactSig bs)
   | otherwise = Nothing
 
--- | Convert signature to a normalized lower-S form. 'Nothing' indicates that it
--- was already normal.
-normalizeSig :: Ctx -> Sig -> Maybe Sig
-normalizeSig (Ctx fctx) (Sig sig) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString sig $ \(sig_in, _) -> do
-      sig_out <- mallocBytes 64
-      ret <- ecdsaSignatureNormalize ctx sig_out sig_in
-      if isSuccess ret
-        then do
-          bs <- unsafePackByteString (sig_out, 64)
-          return (Just (Sig bs))
-        else do
-          free sig_out
-          return Nothing
+-- | Convert a signature to its lower-S form. A signature that is already in
+-- 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 :: 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 globalContext sig_out sig_in)
 
--- | 32-Byte 'ByteString' as 'Tweak'.
-tweak :: ByteString -> Maybe Tweak
-tweak bs
-  | BS.length bs == 32 = Just (Tweak bs)
-  | otherwise = Nothing
+-- | 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 :: 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 globalContext nullPtr sig_in
+      return (not (isSuccess was_high))
 
--- | Import DER-encoded public key.
-importPubKey :: Ctx -> ByteString -> Maybe PubKey
-importPubKey (Ctx fctx) bs
+-- | True when the r component is lower than 2^255, which makes the DER
+-- encoding at most 70 bytes. 'signMsgLowR' produces such signatures.
+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 :: ByteString -> Maybe PubKey
+importPubKey bs
   | BS.null bs = Nothing
   | otherwise =
-      unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-        unsafeUseByteString bs $ \(input, len) -> do
-          pub_key <- mallocBytes 64
-          ret <- ecPubKeyParse ctx pub_key input len
-          if isSuccess ret
-            then do
-              out <- unsafePackByteString (pub_key, 64)
-              return (Just (PubKey out))
-            else do
-              free pub_key
-              return Nothing
+      unsafePerformIO $
+        unsafeUseByteString bs $ \(input, len) ->
+          (fmap . fmap) PubKey . withOutput 64 $ \pub_key ->
+            isSuccess <$> ecPubKeyParse globalContext pub_key input len
 
--- | Encode public key as DER. First argument 'True' for compressed output.
-exportPubKey :: Ctx -> Bool -> PubKey -> ByteString
-exportPubKey (Ctx fctx) compress (PubKey in_bs) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString in_bs $ \(in_ptr, _) ->
+-- | Serialize a public key in SEC1 encoding. 'True' for the 33-byte
+-- compressed form, 'False' for the 65-byte uncompressed form.
+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)
   where
-    len = if compress then 33 else 65
+    len = if compress then 33 else 65 :: Int
     flags = if compress then compressed else uncompressed
 
-exportCompactSig :: Ctx -> Sig -> CompactSig
-exportCompactSig (Ctx fctx) (Sig sig_bs) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString sig_bs $ \(sig_ptr, _) -> do
-      out_ptr <- mallocBytes 64
-      ret <- ecdsaSignatureSerializeCompact ctx out_ptr sig_ptr
-      unless (isSuccess ret) $ do
-        free out_ptr
-        error "Could not obtain compact signature"
-      out_bs <- unsafePackByteString (out_ptr, 64)
-      return $ CompactSig out_bs
+-- | Serialize a signature in the compact encoding.
+exportCompactSig :: Sig -> CompactSig
+exportCompactSig (Sig sig_bs) =
+  unsafePerformIO $
+    useFixedByteString "Sig" 64 sig_bs $ \(sig_ptr, _) -> do
+      out <- withOutput 64 $ \out_ptr ->
+        isSuccess <$> ecdsaSignatureSerializeCompact globalContext out_ptr sig_ptr
+      maybe
+        (error "could not serialize compact signature")
+        (return . CompactSig)
+        out
 
-importCompactSig :: Ctx -> CompactSig -> Maybe Sig
-importCompactSig (Ctx fctx) (CompactSig compact_sig) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString compact_sig $ \(compact_ptr, _) -> do
-      out_sig <- mallocBytes 64
-      ret <- ecdsaSignatureParseCompact ctx out_sig compact_ptr
-      if isSuccess ret
-        then do
-          out_bs <- unsafePackByteString (out_sig, 64)
-          return (Just (Sig out_bs))
-        else do
-          free out_sig
-          return Nothing
+-- | 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 :: CompactSig -> Maybe Sig
+importCompactSig (CompactSig compact) = do
+  guard (hasNonZeroComponents compact)
+  unsafePerformIO $
+    useFixedByteString "CompactSig" 64 compact $ \(compact_ptr, _) ->
+      (fmap . fmap) Sig . withOutput 64 $ \out_sig ->
+        isSuccess <$> ecdsaSignatureParseCompact globalContext out_sig compact_ptr
 
--- | Import DER-encoded signature.
-importSig :: Ctx -> ByteString -> Maybe Sig
-importSig (Ctx fctx) bs
+-- | 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 :: ByteString -> Maybe Sig
+importSig bs
   | BS.null bs = Nothing
-  | otherwise =
-      unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-        unsafeUseByteString bs $ \(in_ptr, in_len) -> do
-          out_sig <- mallocBytes 64
-          ret <- ecdsaSignatureParseDer ctx out_sig in_ptr in_len
-          if isSuccess ret
-            then do
-              out_bs <- unsafePackByteString (out_sig, 64)
-              return (Just (Sig out_bs))
-            else do
-              free out_sig
-              return Nothing
+  | otherwise = do
+      parsed <-
+        unsafePerformIO $
+          unsafeUseByteString bs $ \(in_ptr, in_len) ->
+            (fmap . fmap) Sig . withOutput 64 $ \out_sig ->
+              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 parsed).get)
+      return parsed
 
--- | Encode signature as strict DER.
-exportSig :: Ctx -> Sig -> ByteString
-exportSig (Ctx fctx) (Sig in_sig) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString in_sig $ \(in_ptr, _) ->
+-- | Serialize a signature in strict DER encoding (8 to 72 bytes).
+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)
 
--- | Verify message signature. 'True' means that the signature is correct.
-verifySig :: Ctx -> PubKey -> Sig -> Msg -> Bool
-verifySig (Ctx fctx) (PubKey pub_key) (Sig sig) (Msg m) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString pub_key $ \(pub_key_ptr, _) ->
-      unsafeUseByteString sig $ \(sig_ptr, _) ->
-        unsafeUseByteString m $ \(msg_ptr, _) ->
-          isSuccess <$> ecdsaVerify ctx sig_ptr msg_ptr pub_key_ptr
-
-signMsg :: Ctx -> SecKey -> Msg -> Sig
-signMsg (Ctx fctx) (SecKey sec_key) (Msg m) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString sec_key $ \(sec_key_ptr, _) ->
-      unsafeUseByteString m $ \(msg_ptr, _) -> do
-        sig_ptr <- mallocBytes 64
-        ret <- ecdsaSign ctx sig_ptr msg_ptr sec_key_ptr nullFunPtr nullPtr
-        unless (isSuccess ret) $ do
-          free sig_ptr
-          error "could not sign message"
-        Sig <$> unsafePackByteString (sig_ptr, 64)
+-- | Verify a signature over a message hash. 'True' means the signature is
+-- valid for the key and the hash and is in lower-S form. A valid signature
+-- in high-S form gives 'False'. Apply 'normalizeSig' first to accept it.
+--
+-- The lower-S rule exists because ECDSA signatures are malleable: if (r, s)
+-- is valid, so is (r, n − s). Anyone could change a transaction's signature,
+-- 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 :: 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 globalContext sig_ptr msg_ptr pub_key_ptr
 
-derivePubKey :: Ctx -> SecKey -> PubKey
-derivePubKey (Ctx fctx) (SecKey sec_key) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString sec_key $ \(sec_key_ptr, _) -> do
-      pub_key_ptr <- mallocBytes 64
-      ret <- ecPubKeyCreate ctx pub_key_ptr sec_key_ptr
-      unless (isSuccess ret) $ do
-        free pub_key_ptr
-        error "could not compute public key"
-      PubKey <$> unsafePackByteString (pub_key_ptr, 64)
+-- | 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.
+--
+-- Deterministic nonces are the reason this is a pure function, and they are a
+-- safety feature, not a convenience: an ECDSA nonce that repeats, or that is
+-- 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 :: SecKey -> Msg -> Sig
+signMsg key m = signMsgWith key m Nothing
 
--- | Add tweak to secret key.
-tweakAddSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
-tweakAddSecKey (Ctx fctx) (SecKey sec_key) (Tweak t) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString new_bs $ \(sec_key_ptr, _) ->
-      unsafeUseByteString t $ \(tweak_ptr, _) -> do
-        ret <- ecSecKeyTweakAdd ctx sec_key_ptr tweak_ptr
-        if isSuccess ret
-          then return (Just (SecKey new_bs))
-          else return 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 :: 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
+          -- A null nonce function selects the RFC 6979 default, which still
+          -- receives the extra data.
+          out <- withOutput 64 $ \sig_ptr ->
+            isSuccess
+              <$> ecdsaSign globalContext sig_ptr msg_ptr sec_key_ptr nullFunPtr data_ptr
+          maybe (error "could not sign message") (return . Sig) out
   where
-    new_bs = BS.copy sec_key
+    withNonceData f = case nonce_data of
+      Nothing -> f nullPtr
+      Just d -> useFixedByteString "nonce data" 32 d $ \(p, _) -> f p
 
--- | Multiply secret key by tweak.
-tweakMulSecKey :: Ctx -> SecKey -> Tweak -> Maybe SecKey
-tweakMulSecKey (Ctx fctx) (SecKey sec_key) (Tweak t) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString new_bs $ \(sec_key_ptr, _) ->
-      unsafeUseByteString t $ \(tweak_ptr, _) -> do
-        ret <- ecSecKeyTweakMul ctx sec_key_ptr tweak_ptr
-        if isSuccess ret
-          then return (Just (SecKey new_bs))
-          else return Nothing
+-- | Sign like 'signMsg', then retry with extra nonce data until the r
+-- component is lower than 2^255, so that the DER encoding is at most 70
+-- bytes. This is what Bitcoin Core does since version 0.17, with the same
+-- nonce data (a 32-bit little-endian counter padded to 32 bytes), so the
+-- signatures are the same as Bitcoin Core's. On average it takes two
+-- attempts. The result is still deterministic.
+--
+-- 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 :: SecKey -> Msg -> Sig
+signMsgLowR key m = go 0 (signMsg key m)
   where
-    new_bs = BS.copy sec_key
+    go :: Word32 -> Sig -> Sig
+    go counter s
+      | isLowR s = s
+      | otherwise =
+          let next = counter + 1
+           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
 
--- | Add tweak to public key. Tweak is multiplied first by G to obtain a point.
-tweakAddPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
-tweakAddPubKey (Ctx fctx) (PubKey pub_key) (Tweak t) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString new_bs $ \(pub_key_ptr, _) ->
-      unsafeUseByteString t $ \(tweak_ptr, _) -> do
-        ret <- ecPubKeyTweakAdd ctx pub_key_ptr tweak_ptr
-        if isSuccess ret
-          then return (Just (PubKey new_bs))
-          else return Nothing
-  where
-    new_bs = BS.copy pub_key
+-- | Compute the public key of a secret key.
+--
+-- It is a pure function and cannot fail, because a t'SecKey' is valid by
+-- construction.
+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 globalContext pub_key_ptr sec_key_ptr
+      maybe (error "could not compute public key") (return . PubKey) out
 
--- | Multiply public key by tweak. Tweak is multiplied first by G to obtain a
--- point.
-tweakMulPubKey :: Ctx -> PubKey -> Tweak -> Maybe PubKey
-tweakMulPubKey (Ctx fctx) (PubKey pub_key) (Tweak t) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString new_bs $ \(pub_key_ptr, _) ->
-      unsafeUseByteString t $ \(tweak_ptr, _) -> do
-        ret <- ecPubKeyTweakMul ctx pub_key_ptr tweak_ptr
-        if isSuccess ret
-          then return (Just (PubKey new_bs))
-          else return Nothing
-  where
-    new_bs = BS.copy pub_key
+-- | Add a tweak to a secret key: @key + tweak mod n@. 'Nothing' when the
+-- result would be zero, which happens when the tweak is the negation of the
+-- key.
+--
+-- Tweaks are the building block of key derivation: BIP-32 child keys are a
+-- 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 :: 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 globalContext sec_key_ptr tweak_ptr
 
--- | Add multiple public keys together.
-combinePubKeys :: Ctx -> [PubKey] -> Maybe PubKey
-combinePubKeys _ [] = Nothing
-combinePubKeys (Ctx fctx) pubs =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    pointers [] pubs $ \ps ->
-      allocaArray (length ps) $ \a -> do
-        out <- mallocBytes 64
-        pokeArray a ps
-        ret <- ecPubKeyCombine ctx out a (fromIntegral $ length ps)
-        if isSuccess ret
-          then do
-            bs <- unsafePackByteString (out, 64)
-            return (Just (PubKey bs))
-          else do
-            free out
-            return Nothing
+-- | Multiply a secret key by a tweak: @key * tweak mod n@. 'Nothing' when the
+-- tweak is zero.
+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 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 :: 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 globalContext pub_key_ptr tweak_ptr
+
+-- | Multiply a public key by a tweak: @tweak * key@. 'Nothing' when the tweak
+-- is zero.
+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 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 :: [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 $
+        withPointers pubs $ \ps ->
+          allocaArray (length ps) $ \arr -> do
+            pokeArray arr ps
+            (fmap . fmap) PubKey . withOutput 64 $ \out ->
+              isSuccess <$> ecPubKeyCombine globalContext out arr (fromIntegral (length ps))
   where
-    pointers ps [] f = f ps
-    pointers ps (PubKey pub_key : pub_keys) f =
-      unsafeUseByteString pub_key $ \(p, _) ->
-        pointers (p : ps) pub_keys f
+    -- 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.
+    isValidPoint (PubKey bs)
+      | BS.length bs /= 64 = wrongLength "PubKey" 64 bs
+      | otherwise = isCanonicalPubKey bs
+    withPointers [] f = f []
+    withPointers (PubKey pub_key : rest) f =
+      useFixedByteString "PubKey" 64 pub_key $ \(p, _) ->
+        withPointers rest $ \ps -> f (p : ps)
 
-tweakNegate :: Ctx -> Tweak -> Maybe Tweak
-tweakNegate (Ctx fctx) (Tweak t) =
-  unsafePerformIO $ withForeignPtr fctx $ \ctx ->
-    unsafeUseByteString new $ \(out, _) -> do
-      ret <- ecTweakNegate ctx out
-      if isSuccess ret
-        then return (Just (Tweak new))
-        else return Nothing
+-- | 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 t'Tweak' that is not below the curve order.
+tweakNegate :: Tweak -> Maybe Tweak
+tweakNegate (Tweak t)
+  | t == zero32 = Just (Tweak t)
+  | otherwise =
+      unsafePerformIO $
+        (fmap . fmap) Tweak . withCopy "Tweak" 32 t $ \out ->
+          isSuccess <$> ecTweakNegate globalContext out
+
+-- * Schnorr signatures (BIP-340)
+
+-- | Import a 64-byte BIP-340 Schnorr signature. Only the length is checked.
+-- 'verifySchnorr' rejects a signature whose components are out of range.
+schnorrSig :: ByteString -> Maybe SchnorrSig
+schnorrSig bs
+  | BS.length bs == 64 = Just (SchnorrSig bs)
+  | otherwise = Nothing
+
+-- | Run an action with the x-only form of a public key, which keeps the x
+-- coordinate and drops the parity of y. 'Nothing' if the key does not load
+-- as a point.
+withXOnlyPubKey ::
+  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 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 ::
+  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 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 :: 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 :: PubKey -> ByteString
+exportXOnlyPubKey (PubKey pub_key) =
+  unsafePerformIO $ do
+    out <- withXOnlyPubKey pub_key $ \xonly_ptr ->
+      fillOutput 32 $ \out_ptr -> do
+        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
+
+-- | Sign a message hash with BIP-340 and no auxiliary randomness. The
+-- signature is deterministic, and the same as with 32 zero bytes of auxiliary
+-- randomness. BIP-340 recommends fresh randomness for every signature, which
+-- protects the key against side-channel and fault attacks; 'signSchnorrIO'
+-- provides it.
+--
+-- As BIP-340 requires, the signature is verified before it is returned, and
+-- an error is raised if that fails.
+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 :: 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) => SecKey -> Msg -> m SchnorrSig
+signSchnorrIO key m = liftIO $ do
+  aux <- getEntropy 32
+  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 :: 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 sec_key $ \key_pair ->
+          withOutput 64 $ \sig_ptr -> do
+            ret <- schnorrSigSign32 globalContext sig_ptr msg_ptr key_pair aux_ptr
+            if isSuccess ret
+              then verifyFreshSignature key_pair sig_ptr (castPtr msg_ptr)
+              else return False
+        case out of
+          Nothing -> error "could not sign message"
+          Just Nothing -> error "could not sign message: the signature does not verify"
+          Just (Just s) -> return (SchnorrSig s)
   where
-    new = BS.copy t
+    withAux f = case aux of
+      Nothing -> f nullPtr
+      Just bs -> useFixedByteString "auxiliary randomness" 32 bs $ \(p, _) -> f p
 
+-- | 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 KeyPair96 -> Ptr SchnorrSig64 -> Ptr CUChar -> IO Bool
+verifyFreshSignature key_pair sig_ptr msg_ptr =
+  allocaBytes 64 $ \xonly_ptr -> do
+    ret <- keyPairXOnlyPub globalContext xonly_ptr nullPtr key_pair
+    if isSuccess ret
+      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 :: 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 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
+-- how BIP-341 derives a Taproot output key from an internal key. The result
+-- is a full point: its x coordinate is the tweaked x-only key, and the parity
+-- 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 t'Tweak' that
+-- is not below the curve order.
+tweakAddXOnlyPubKey :: PubKey -> Tweak -> Maybe PubKey
+tweakAddXOnlyPubKey (PubKey pub_key) (Tweak t) =
+  unsafePerformIO $
+    useFixedByteString "Tweak" 32 t $ \(tweak_ptr, _) ->
+      fmap join . withXOnlyPubKey pub_key $ \xonly_ptr ->
+        (fmap . fmap) PubKey . withOutput 64 $ \out ->
+          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 t'Tweak' that is not below the curve order.
+tweakAddXOnlySecKey :: SecKey -> Tweak -> Maybe SecKey
+tweakAddXOnlySecKey (SecKey sec_key) (Tweak t) =
+  unsafePerformIO $
+    useFixedByteString "Tweak" 32 t $ \(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 globalContext out key_pair
+          else return Nothing
+
 instance Arbitrary Msg where
-  arbitrary = gen_msg
+  arbitrary = fromJust <$> (gen `suchThat` isJust)
     where
-      valid_bs = bs_gen `suchThat` isJust
-      bs_gen = msg . BS.pack <$> replicateM 32 arbitraryBoundedRandom
-      gen_msg = fromJust <$> valid_bs
+      gen = msg . BS.pack <$> replicateM 32 arbitraryBoundedRandom
 
 instance Arbitrary SecKey where
-  arbitrary = gen_key
+  arbitrary = fromJust <$> (gen `suchThat` isJust)
     where
-      valid_bs = bs_gen `suchThat` isJust
-      bs_gen = secKey . BS.pack <$> replicateM 32 arbitraryBoundedRandom
-      gen_key = fromJust <$> valid_bs
+      gen = secKey . BS.pack <$> replicateM 32 arbitraryBoundedRandom
+
+instance Arbitrary Tweak where
+  arbitrary = fromJust <$> (gen `suchThat` isJust)
+    where
+      gen = tweak . BS.pack <$> replicateM 32 arbitraryBoundedRandom
diff --git a/src/Crypto/Secp256k1/Internal/BaseOps.hs b/src/Crypto/Secp256k1/Internal/BaseOps.hs
--- a/src/Crypto/Secp256k1/Internal/BaseOps.hs
+++ b/src/Crypto/Secp256k1/Internal/BaseOps.hs
@@ -1,17 +1,33 @@
+-- | Foreign imports of the core, @extrakeys@ and @schnorrsig@ modules of libsecp256k1.
+--
+-- Each function is a direct binding to the C function of the same name in
+-- @secp256k1.h@, @secp256k1_extrakeys.h@ or @secp256k1_schnorrsig.h@. The
+-- 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.
+--
+-- 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
-  ( Compact64,
-    LCtx,
+  ( AuxRand32,
+    Compact64,
+    KeyPair96,
     Msg32,
     NonceFun,
     PubKey64,
     Ret,
+    SchnorrSig64,
     SecKey32,
-    Seed32,
     SerFlags,
     Sig64,
     Tweak32,
+    XOnlyPubKey64,
   )
 import Foreign (FunPtr, Ptr)
 import Foreign.C
@@ -21,6 +37,7 @@
     CUInt (..),
   )
 
+-- | Binding to @secp256k1_ec_pubkey_parse@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_parse"
   ecPubKeyParse ::
     Ptr LCtx ->
@@ -31,6 +48,7 @@
     CSize ->
     IO Ret
 
+-- | Binding to @secp256k1_ec_pubkey_serialize@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_serialize"
   ecPubKeySerialize ::
     Ptr LCtx ->
@@ -42,6 +60,7 @@
     SerFlags ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_signature_parse_compact@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_signature_parse_compact"
   ecdsaSignatureParseCompact ::
     Ptr LCtx ->
@@ -49,6 +68,7 @@
     Ptr Compact64 ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_signature_parse_der@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_signature_parse_der"
   ecdsaSignatureParseDer ::
     Ptr LCtx ->
@@ -59,6 +79,7 @@
     CSize ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_signature_serialize_der@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_signature_serialize_der"
   ecdsaSignatureSerializeDer ::
     Ptr LCtx ->
@@ -69,6 +90,7 @@
     Ptr Sig64 ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_signature_serialize_compact@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_signature_serialize_compact"
   ecdsaSignatureSerializeCompact ::
     Ptr LCtx ->
@@ -76,6 +98,7 @@
     Ptr Sig64 ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_verify@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_verify"
   ecdsaVerify ::
     Ptr LCtx ->
@@ -84,6 +107,7 @@
     Ptr PubKey64 ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_signature_normalize@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_signature_normalize"
   ecdsaSignatureNormalize ::
     Ptr LCtx ->
@@ -93,6 +117,7 @@
     Ptr Sig64 ->
     IO Ret
 
+-- | Binding to @secp256k1_ecdsa_sign@.
 foreign import ccall safe "secp256k1.h secp256k1_ecdsa_sign"
   ecdsaSign ::
     Ptr LCtx ->
@@ -104,12 +129,14 @@
     Ptr a ->
     IO Ret
 
+-- | Binding to @secp256k1_ec_seckey_verify@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_seckey_verify"
   ecSecKeyVerify ::
     Ptr LCtx ->
     Ptr SecKey32 ->
     IO Ret
 
+-- | Binding to @secp256k1_ec_pubkey_create@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_create"
   ecPubKeyCreate ::
     Ptr LCtx ->
@@ -117,33 +144,38 @@
     Ptr SecKey32 ->
     IO Ret
 
-foreign import ccall safe "secp256k1.h secp256k1_ec_privkey_tweak_add"
+-- | Binding to @secp256k1_ec_seckey_tweak_add@.
+foreign import ccall safe "secp256k1.h secp256k1_ec_seckey_tweak_add"
   ecSecKeyTweakAdd ::
     Ptr LCtx ->
     Ptr SecKey32 ->
     Ptr Tweak32 ->
     IO Ret
 
-foreign import ccall safe "secp256k1.h secp256k1_ec_privkey_negate"
+-- | Binding to @secp256k1_ec_seckey_negate@.
+foreign import ccall safe "secp256k1.h secp256k1_ec_seckey_negate"
   ecTweakNegate ::
     Ptr LCtx ->
     Ptr Tweak32 ->
     IO Ret
 
-foreign import ccall unsafe "secp256k1.h secp256k1_ec_pubkey_tweak_add"
+-- | Binding to @secp256k1_ec_pubkey_tweak_add@.
+foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_tweak_add"
   ecPubKeyTweakAdd ::
     Ptr LCtx ->
     Ptr PubKey64 ->
     Ptr Tweak32 ->
     IO Ret
 
-foreign import ccall safe "secp256k1.h secp256k1_ec_privkey_tweak_mul"
+-- | Binding to @secp256k1_ec_seckey_tweak_mul@.
+foreign import ccall safe "secp256k1.h secp256k1_ec_seckey_tweak_mul"
   ecSecKeyTweakMul ::
     Ptr LCtx ->
     Ptr SecKey32 ->
     Ptr Tweak32 ->
     IO Ret
 
+-- | Binding to @secp256k1_ec_pubkey_tweak_mul@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_tweak_mul"
   ecPubKeyTweakMul ::
     Ptr LCtx ->
@@ -151,6 +183,7 @@
     Ptr Tweak32 ->
     IO Ret
 
+-- | Binding to @secp256k1_ec_pubkey_combine@.
 foreign import ccall safe "secp256k1.h secp256k1_ec_pubkey_combine"
   ecPubKeyCombine ::
     Ptr LCtx ->
@@ -159,5 +192,94 @@
     -- | pointer to array of public keys
     Ptr (Ptr PubKey64) ->
     -- | number of public keys
-    CInt ->
+    CSize ->
+    IO Ret
+
+-- The following functions belong to the @extrakeys@ and @schnorrsig@ modules
+-- of libsecp256k1, enabled by default since version 0.2.0.
+
+-- | Binding to @secp256k1_xonly_pubkey_from_pubkey@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_xonly_pubkey_from_pubkey"
+  xOnlyPubKeyFromPubKey ::
+    Ptr LCtx ->
+    Ptr XOnlyPubKey64 ->
+    -- | parity of the public key, 1 if odd; may be NULL
+    Ptr CInt ->
+    Ptr PubKey64 ->
+    IO Ret
+
+-- | Binding to @secp256k1_xonly_pubkey_serialize@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_xonly_pubkey_serialize"
+  xOnlyPubKeySerialize ::
+    Ptr LCtx ->
+    -- | 32-byte output
+    Ptr CUChar ->
+    Ptr XOnlyPubKey64 ->
+    IO Ret
+
+-- | Binding to @secp256k1_xonly_pubkey_tweak_add@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_xonly_pubkey_tweak_add"
+  xOnlyPubKeyTweakAdd ::
+    Ptr LCtx ->
+    -- | tweaked public key
+    Ptr PubKey64 ->
+    Ptr XOnlyPubKey64 ->
+    Ptr Tweak32 ->
+    IO Ret
+
+-- | Binding to @secp256k1_keypair_create@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_keypair_create"
+  keyPairCreate ::
+    Ptr LCtx ->
+    Ptr KeyPair96 ->
+    Ptr SecKey32 ->
+    IO Ret
+
+-- | Binding to @secp256k1_keypair_sec@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_keypair_sec"
+  keyPairSec ::
+    Ptr LCtx ->
+    Ptr SecKey32 ->
+    Ptr KeyPair96 ->
+    IO Ret
+
+-- | Binding to @secp256k1_keypair_xonly_pub@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_keypair_xonly_pub"
+  keyPairXOnlyPub ::
+    Ptr LCtx ->
+    Ptr XOnlyPubKey64 ->
+    -- | parity of the public key, 1 if odd; may be NULL
+    Ptr CInt ->
+    Ptr KeyPair96 ->
+    IO Ret
+
+-- | Binding to @secp256k1_keypair_xonly_tweak_add@.
+foreign import ccall safe "secp256k1_extrakeys.h secp256k1_keypair_xonly_tweak_add"
+  keyPairXOnlyTweakAdd ::
+    Ptr LCtx ->
+    Ptr KeyPair96 ->
+    Ptr Tweak32 ->
+    IO Ret
+
+-- | Binding to @secp256k1_schnorrsig_sign32@.
+foreign import ccall safe "secp256k1_schnorrsig.h secp256k1_schnorrsig_sign32"
+  schnorrSigSign32 ::
+    Ptr LCtx ->
+    Ptr SchnorrSig64 ->
+    Ptr Msg32 ->
+    Ptr KeyPair96 ->
+    -- | auxiliary randomness; may be NULL
+    Ptr AuxRand32 ->
+    IO Ret
+
+-- | Binding to @secp256k1_schnorrsig_verify@.
+foreign import ccall safe "secp256k1_schnorrsig.h secp256k1_schnorrsig_verify"
+  schnorrSigVerify ::
+    Ptr LCtx ->
+    Ptr SchnorrSig64 ->
+    -- | message
+    Ptr CUChar ->
+    -- | message length
+    CSize ->
+    Ptr XOnlyPubKey64 ->
     IO Ret
diff --git a/src/Crypto/Secp256k1/Internal/Context.hs b/src/Crypto/Secp256k1/Internal/Context.hs
--- a/src/Crypto/Secp256k1/Internal/Context.hs
+++ b/src/Crypto/Secp256k1/Internal/Context.hs
@@ -1,100 +1,99 @@
-{-# LANGUAGE NoFieldSelectors #-}
-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 (bracket, 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)
-import Foreign.C (CInt (..), CString, CUInt (..))
-import Foreign.ForeignPtr
-  ( FinalizerPtr,
-    ForeignPtr,
-    finalizeForeignPtr,
-    newForeignPtr,
-    withForeignPtr,
-  )
-import GHC.Conc (writeTVar)
+import Foreign (Ptr, nullPtr)
 import System.IO.Unsafe (unsafePerformIO)
 
-newtype Ctx = Ctx {get :: ForeignPtr LCtx}
-
-randomizeContext :: Ctx -> IO ()
-randomizeContext (Ctx fctx) = withForeignPtr fctx $ \ctx -> do
-  ret <- withRandomSeed $ contextRandomize ctx
-  unless (isSuccess ret) $ error "Could not randomize context"
-
-createContext :: IO Ctx
-createContext = do
-  ctx <- mask_ $ do
-    pctx <- contextCreate signVerify
-    Ctx <$> newForeignPtr contextDestroyFunPtr pctx
-  randomizeContext ctx
+-- | 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.
+--
+-- 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.
+--
+-- 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
-
-cloneContext :: Ctx -> IO Ctx
-cloneContext (Ctx fctx) =
-  withForeignPtr fctx $ \ctx -> mask_ $ do
-    ctx' <- contextClone ctx
-    Ctx <$> newForeignPtr contextDestroyFunPtr ctx'
-
-destroyContext :: Ctx -> IO ()
-destroyContext (Ctx fctx)= finalizeForeignPtr fctx
-
-withContext :: (Ctx -> IO a) -> IO a
-withContext = (createContext >>=)
-
-verify :: CtxFlags
-verify = 0x0101
-
-sign :: CtxFlags
-sign = 0x0201
-
-signVerify :: CtxFlags
-signVerify = 0x0301
-
-foreign import ccall safe "secp256k1.h secp256k1_context_create"
-  contextCreate ::
-    CtxFlags ->
-    IO (Ptr LCtx)
-
-foreign import ccall safe "secp256k1.h secp256k1_context_clone"
-  contextClone ::
-    Ptr LCtx ->
-    IO (Ptr LCtx)
-
-foreign import ccall safe "secp256k1.h secp256k1_context_destroy"
-  contextDestroy :: Ptr LCtx -> IO ()
-
-foreign import ccall safe "secp256k1.h &secp256k1_context_destroy"
-  contextDestroyFunPtr :: FunPtr (Ptr LCtx -> IO ())
-
-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 ()
-
-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 ()
-
-foreign import ccall safe "secp256k1.h secp256k1_context_randomize"
-  contextRandomize ::
-    Ptr LCtx ->
-    Ptr Seed32 ->
-    IO Ret
+{-# NOINLINE globalContext #-}
diff --git a/src/Crypto/Secp256k1/Internal/ContextOps.hs b/src/Crypto/Secp256k1/Internal/ContextOps.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Internal/ContextOps.hs
@@ -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
diff --git a/src/Crypto/Secp256k1/Internal/EllSwift.hs b/src/Crypto/Secp256k1/Internal/EllSwift.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Internal/EllSwift.hs
@@ -0,0 +1,190 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- | Internal module. Everything is exported, including the raw v'EllSwift'
+-- constructor that "Crypto.Secp256k1.EllSwift" hides, and there is no API
+-- stability guarantee. This module is only built when the @ellswift@ flag of
+-- the package is on.
+--
+-- Every 64 bytes are the encoding of some point, so the only thing the raw
+-- constructor can get wrong is the length. Every function here checks it
+-- before calling the C library and raises an 'Control.Exception.ErrorCall'
+-- when it is wrong.
+--
+-- As in "Crypto.Secp256k1.Internal.Base", every function uses the global
+-- context of the package and none takes one.
+module Crypto.Secp256k1.Internal.EllSwift where
+
+import Control.DeepSeq (NFData)
+import Control.Exception (evaluate)
+import Control.Monad.IO.Class (MonadIO (..))
+import Crypto.Secp256k1.Internal.Base (PubKey (..), SecKey (..))
+import Crypto.Secp256k1.Internal.Context (globalContext)
+import Crypto.Secp256k1.Internal.EllSwiftOps qualified as Ops
+import Crypto.Secp256k1.Internal.ForeignTypes (isSuccess)
+import Crypto.Secp256k1.Internal.Util
+  ( decodeHex,
+    showsHex,
+    useFixedByteString,
+    withOutput,
+  )
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Hashable (Hashable)
+import Data.Maybe (fromMaybe)
+import Data.String (IsString (..))
+import Foreign (castPtr, nullPtr, peek)
+import GHC.Generics (Generic)
+import System.Entropy (getEntropy)
+import System.IO.Unsafe (unsafePerformIO)
+import Text.Read
+  ( Lexeme (String),
+    lexP,
+    parens,
+    pfail,
+    readPrec,
+  )
+
+-- | ElligatorSwift encoding of a public key: 64 bytes, two field elements u
+-- and t as 32-byte big-endian numbers. Unlike the @get@ field of a t'PubKey',
+-- these bytes are a standard encoding, the same on every platform, and they
+-- are what BIP 324 sends on the wire.
+--
+-- Any 64 bytes are a valid encoding: each decodes to a point of the curve,
+-- including values of u or t at or above the field size, which are taken
+-- modulo p. A point has many encodings, chosen at random when it is encoded,
+-- so 'Eq' compares encodings, not points.
+--
+-- 'Show', 'Read' and 'IsString' use hex.
+newtype EllSwift = EllSwift {get :: ByteString}
+  deriving (Eq, Ord, Generic, Hashable, NFData)
+
+instance Read EllSwift where
+  readPrec = parens $ do
+    String str <- lexP
+    maybe pfail return $ ellSwift =<< decodeHex str
+
+instance IsString EllSwift where
+  fromString = fromMaybe e . (ellSwift =<<) . decodeHex
+    where
+      e = error "Could not decode ElligatorSwift encoding from hex string"
+
+instance Show EllSwift where
+  showsPrec _ (EllSwift bs) = showsHex bs
+
+-- | Which side of an x-only Diffie-Hellman exchange a party is. The two
+-- encodings are hashed in the order A then B, so both sides must agree on
+-- who is who. In BIP 324 the initiator of the connection is A and the
+-- responder is B.
+data Party = PartyA | PartyB
+  deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)
+
+instance NFData Party
+
+-- | An encoding from its 64 bytes. 'Nothing' only for another length: every
+-- 64 bytes encode a point.
+ellSwift :: ByteString -> Maybe EllSwift
+ellSwift bs
+  | BS.length bs == 64 = Just (EllSwift bs)
+  | otherwise = Nothing
+
+-- | Encode a public key with 32 bytes of randomness. 'Nothing' unless the
+-- randomness is 32 bytes long.
+--
+-- The randomness picks one of the many encodings of the point. It should be
+-- uniformly random and unknown to anyone who tries to tell the encoding from
+-- random bytes, and it must not be a function of the public key alone. The
+-- encoding of a given key and randomness may change between versions of
+-- libsecp256k1. Runs in variable time, which is harmless for a public key.
+-- Prefer 'ellSwiftCreate' when the secret key is at hand.
+ellSwiftEncode :: PubKey -> ByteString -> Maybe EllSwift
+ellSwiftEncode (PubKey pub_key) rnd
+  | BS.length rnd /= 32 = Nothing
+  | otherwise =
+      Just . unsafePerformIO $
+        useFixedByteString "PubKey" 64 pub_key $ \(pub_key_ptr, _) ->
+          useFixedByteString "randomness" 32 rnd $ \(rnd_ptr, _) -> do
+            out <- withOutput 64 $ \ell_ptr ->
+              isSuccess <$> Ops.ellSwiftEncode globalContext ell_ptr pub_key_ptr rnd_ptr
+            -- libsecp256k1 documents that this function always succeeds.
+            maybe (error "could not encode public key") (return . EllSwift) out
+
+-- | The public key of a secret key, encoded with ElligatorSwift. The secret
+-- key itself is a source of randomness for the choice of the encoding, and
+-- the optional 32 bytes of auxiliary randomness add to it, as
+-- @EllSwiftCreate@ does in Bitcoin Core. 'Nothing' when the auxiliary
+-- randomness is given and is not 32 bytes long.
+--
+-- Without auxiliary randomness the encoding is a function of the secret key,
+-- and still looks uniformly random to anyone who does not know the key. BIP
+-- 324 recommends fresh randomness: see 'ellSwiftCreateIO'. Constant time in
+-- the secret key and the randomness, but not in the resulting public key.
+ellSwiftCreate :: SecKey -> Maybe ByteString -> Maybe EllSwift
+ellSwiftCreate (SecKey sec_key) aux = case aux of
+  Just a | BS.length a /= 32 -> Nothing
+  _ ->
+    Just . unsafePerformIO $
+      useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) ->
+        withAux $ \aux_ptr -> do
+          out <- withOutput 64 $ \ell_ptr ->
+            isSuccess <$> Ops.ellSwiftCreate globalContext ell_ptr sec_key_ptr aux_ptr
+          -- It fails only for a secret key out of range, which a t'SecKey' is
+          -- not.
+          maybe (error "could not create ElligatorSwift public key") (return . EllSwift) out
+  where
+    withAux f = case aux of
+      Nothing -> f nullPtr
+      Just a -> useFixedByteString "auxiliary randomness" 32 a $ f . castPtr . fst
+
+-- | 'ellSwiftCreate' with 32 bytes of fresh auxiliary randomness from the
+-- operating system, as Bitcoin Core does for every connection.
+ellSwiftCreateIO :: (MonadIO m) => SecKey -> m EllSwift
+ellSwiftCreateIO key = liftIO $ do
+  aux <- getEntropy 32
+  evaluate . fromMaybe (error "getEntropy gave the wrong length") $ ellSwiftCreate key (Just aux)
+
+-- | The public key that an encoding stands for. Every encoding decodes to a
+-- point, so this is total. The y coordinate of the point has the parity of
+-- t. Runs in variable time.
+ellSwiftDecode :: EllSwift -> PubKey
+ellSwiftDecode (EllSwift ell) =
+  unsafePerformIO $
+    useFixedByteString "EllSwift" 64 ell $ \(ell_ptr, _) -> do
+      out <- withOutput 64 $ \pub_key_ptr ->
+        isSuccess <$> Ops.ellSwiftDecode globalContext pub_key_ptr ell_ptr
+      -- libsecp256k1 documents that this function always succeeds.
+      maybe (error "could not decode ElligatorSwift encoding") (return . PubKey) out
+
+-- | The shared secret of BIP 324: x-only Diffie-Hellman between our secret key
+-- and the other party's encoded public key, hashed with the tagged hash
+-- @bip324_ellswift_xonly_ecdh@ of the encoding of A, the encoding of B and the
+-- shared x coordinate. The first two arguments are the encodings of A and B,
+-- in that order; the secret key is that of the party named by the last
+-- argument, whose encoding must be the one that comes from that key. That
+-- correspondence is not checked: a wrong one gives a secret that the other
+-- side does not share.
+--
+-- This is @CKey::ComputeBIP324ECDHSecret@ of Bitcoin Core, which passes the
+-- initiator as A. It is faster than decoding the other key and doing the
+-- Diffie-Hellman exchange by hand, and constant time in the secret key.
+ellSwiftXdhBip324 :: EllSwift -> EllSwift -> SecKey -> Party -> ByteString
+ellSwiftXdhBip324 (EllSwift ell_a) (EllSwift ell_b) (SecKey sec_key) party =
+  unsafePerformIO $
+    useFixedByteString "EllSwift" 64 ell_a $ \(a_ptr, _) ->
+      useFixedByteString "EllSwift" 64 ell_b $ \(b_ptr, _) ->
+        useFixedByteString "SecKey" 32 sec_key $ \(sec_key_ptr, _) -> do
+          hash_fun <- peek Ops.ellSwiftXdhHashFunctionBip324
+          out <- withOutput 32 $ \out_ptr ->
+            isSuccess
+              <$> Ops.ellSwiftXdh globalContext out_ptr a_ptr b_ptr sec_key_ptr side hash_fun nullPtr
+          -- It fails only for a secret key out of range, or when the hash
+          -- function fails, which the BIP 324 one never does.
+          maybe (error "could not compute ElligatorSwift shared secret") return out
+  where
+    side = case party of
+      PartyA -> 0
+      PartyB -> 1
diff --git a/src/Crypto/Secp256k1/Internal/EllSwiftOps.hs b/src/Crypto/Secp256k1/Internal/EllSwiftOps.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Internal/EllSwiftOps.hs
@@ -0,0 +1,73 @@
+-- | Foreign imports of the @ellswift@ module of libsecp256k1, which the
+-- library has from version 0.4.0 on when it was built with it, as it is by
+-- default. See "Crypto.Secp256k1.EllSwift". This module is only built when
+-- the @ellswift@ 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.EllSwiftOps where
+
+import Crypto.Secp256k1.Internal.ContextOps (LCtx)
+import Crypto.Secp256k1.Internal.ForeignTypes
+  ( EllSwift64,
+    PubKey64,
+    Ret,
+    SecKey32,
+    XdhHashFun,
+  )
+import Foreign (FunPtr, Ptr)
+import Foreign.C (CInt (..), CUChar)
+
+-- | Binding to @secp256k1_ellswift_encode@.
+foreign import ccall safe "secp256k1_ellswift.h secp256k1_ellswift_encode"
+  ellSwiftEncode ::
+    Ptr LCtx ->
+    Ptr EllSwift64 ->
+    Ptr PubKey64 ->
+    -- | 32 bytes of randomness
+    Ptr CUChar ->
+    IO Ret
+
+-- | Binding to @secp256k1_ellswift_decode@.
+foreign import ccall safe "secp256k1_ellswift.h secp256k1_ellswift_decode"
+  ellSwiftDecode ::
+    Ptr LCtx ->
+    Ptr PubKey64 ->
+    Ptr EllSwift64 ->
+    IO Ret
+
+-- | Binding to @secp256k1_ellswift_create@.
+foreign import ccall safe "secp256k1_ellswift.h secp256k1_ellswift_create"
+  ellSwiftCreate ::
+    Ptr LCtx ->
+    Ptr EllSwift64 ->
+    Ptr SecKey32 ->
+    -- | 32 bytes of auxiliary randomness, or null
+    Ptr CUChar ->
+    IO Ret
+
+-- | Binding to @secp256k1_ellswift_xdh@.
+foreign import ccall safe "secp256k1_ellswift.h secp256k1_ellswift_xdh"
+  ellSwiftXdh ::
+    Ptr LCtx ->
+    -- | output, filled by the hash function
+    Ptr CUChar ->
+    -- | encoding of party A
+    Ptr EllSwift64 ->
+    -- | encoding of party B
+    Ptr EllSwift64 ->
+    Ptr SecKey32 ->
+    -- | party: 0 for A, 1 for B
+    CInt ->
+    FunPtr (XdhHashFun a) ->
+    -- | data passed to the hash function
+    Ptr a ->
+    IO Ret
+
+-- | Address of @secp256k1_ellswift_xdh_hash_function_bip324@, a constant
+-- that holds the hash function of BIP 324: the tagged hash with tag
+-- @bip324_ellswift_xonly_ecdh@ of the encodings of A and B and the shared x
+-- coordinate. It ignores its data argument.
+foreign import ccall "secp256k1_ellswift.h &secp256k1_ellswift_xdh_hash_function_bip324"
+  ellSwiftXdhHashFunctionBip324 :: Ptr (FunPtr (XdhHashFun a))
diff --git a/src/Crypto/Secp256k1/Internal/ForeignTypes.hs b/src/Crypto/Secp256k1/Internal/ForeignTypes.hs
--- a/src/Crypto/Secp256k1/Internal/ForeignTypes.hs
+++ b/src/Crypto/Secp256k1/Internal/ForeignTypes.hs
@@ -1,32 +1,78 @@
+-- | Types and constants shared by the foreign imports.
+--
+-- Each empty data type stands for a C structure of libsecp256k1 and is only
+-- ever used behind a 'Ptr', so that the foreign imports cannot mix up, say, a
+-- pointer to a public key and a pointer to a signature. The number in the name
+-- is the size of the structure in bytes, which the Haskell side must allocate.
+-- This module is internal and has no API stability guarantee.
 module Crypto.Secp256k1.Internal.ForeignTypes where
 
 import Foreign (Ptr)
 import Foreign.C (CInt (..), CUChar, CUInt (..))
 
-data LCtx
-
+-- | Public key (@secp256k1_pubkey@), 64 bytes.
 data PubKey64
 
+-- | Message hash, 32 bytes.
 data Msg32
 
+-- | ECDSA signature (@secp256k1_ecdsa_signature@), 64 bytes.
 data Sig64
 
+-- | Randomization seed for a context, 32 bytes.
 data Seed32
 
+-- | Compact ECDSA signature, r and s, 64 bytes.
 data Compact64
 
+-- | Secret key, 32 bytes.
 data SecKey32
 
+-- | Tweak, 32 bytes.
 data Tweak32
 
+-- | Recoverable ECDSA signature (@secp256k1_ecdsa_recoverable_signature@), 65 bytes.
 data RecSig65
 
-type CtxFlags = CUInt
+-- | X-only public key (@secp256k1_xonly_pubkey@), 64 bytes.
+data XOnlyPubKey64
 
+-- | Key pair (@secp256k1_keypair@), 96 bytes.
+data KeyPair96
+
+-- | BIP-340 signature, 64 bytes.
+data SchnorrSig64
+
+-- | Auxiliary randomness for BIP-340 signing, 32 bytes.
+data AuxRand32
+
+-- | ElligatorSwift encoding of a public key, 64 bytes: two field elements u
+-- and t as 32-byte big-endian numbers.
+data EllSwift64
+
+-- | Hash function of @secp256k1_ellswift_xdh@, as
+-- @secp256k1_ellswift_xdh_hash_function@: it writes the shared secret from
+-- the shared x coordinate and the two encoded public keys. The bindings only
+-- pass the one that libsecp256k1 defines for BIP 324. The arguments are the
+-- output, the shared x coordinate (32 bytes), the encodings of party A and
+-- party B (64 bytes each) and the data pointer.
+type XdhHashFun a =
+  Ptr CUChar ->
+  Ptr CUChar ->
+  Ptr CUChar ->
+  Ptr CUChar ->
+  Ptr a ->
+  IO CInt
+
+-- | Flags passed to @secp256k1_ec_pubkey_serialize@.
 type SerFlags = CUInt
 
+-- | Return value of a C function: 1 for success, 0 for failure.
 type Ret = CInt
 
+-- | Nonce generation function, as @secp256k1_nonce_function@. The bindings pass
+-- 'Foreign.nullFunPtr' for the default RFC 6979 function, or a pointer to
+-- Bitcoin Core's grinding data through the last argument.
 type NonceFun a =
   Ptr CUChar ->
   Ptr CUChar ->
@@ -36,12 +82,17 @@
   CInt ->
   IO CInt
 
+-- | @SECP256K1_EC_COMPRESSED@: serialize a public key in 33 bytes.
 compressed :: SerFlags
 compressed = 0x0102
 
+-- | @SECP256K1_EC_UNCOMPRESSED@: serialize a public key in 65 bytes.
 uncompressed :: SerFlags
 uncompressed = 0x0002
 
+-- | Interpret a return value. Anything but 0 or 1 means the C library and these
+-- bindings disagree about a function's contract, so it raises an error rather
+-- than guess.
 isSuccess :: Ret -> Bool
 isSuccess 0 = False
 isSuccess 1 = True
diff --git a/src/Crypto/Secp256k1/Internal/Recovery.hs b/src/Crypto/Secp256k1/Internal/Recovery.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Internal/Recovery.hs
@@ -0,0 +1,238 @@
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DuplicateRecordFields #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE NoFieldSelectors #-}
+
+-- | Internal module. Everything is exported, including the raw t'RecSig'
+-- constructor that "Crypto.Secp256k1.Recovery" hides, and there is no API
+-- stability guarantee. This module is only built when the @recovery@ flag of
+-- the package is on.
+--
+-- A t'RecSig' built with the raw constructor skips validation. Every function
+-- here still checks the length of its bytes before calling the C library and
+-- raises an 'Control.Exception.ErrorCall' when the length is wrong, but it
+-- does not check the content. A raw t'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)
+import Control.Monad (guard, (<=<))
+import Crypto.Secp256k1.Internal.Base
+  ( CompactSig (..),
+    Msg (..),
+    PubKey (..),
+    SecKey (..),
+    Sig (..),
+    hasNonZeroComponents,
+  )
+import Crypto.Secp256k1.Internal.Context (globalContext)
+import Crypto.Secp256k1.Internal.ForeignTypes (isSuccess)
+import Crypto.Secp256k1.Internal.RecoveryOps
+  ( ecdsaRecover,
+    ecdsaRecoverableSignatureConvert,
+    ecdsaRecoverableSignatureParseCompact,
+    ecdsaRecoverableSignatureSerializeCompact,
+    ecdsaSignRecoverable,
+  )
+import Crypto.Secp256k1.Internal.Util
+  ( decodeHex,
+    packByteString,
+    showsHex,
+    unsafeUseByteString,
+    useFixedByteString,
+    withOutput,
+  )
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Hashable (Hashable)
+import Data.Maybe (fromMaybe)
+import Data.String (IsString (..))
+import Data.Word (Word8)
+import Foreign (alloca, allocaBytes, nullFunPtr, nullPtr, peek)
+import GHC.Generics (Generic)
+import GHC.Records (HasField (..))
+import System.IO.Unsafe (unsafePerformIO)
+import Text.Read
+  ( Lexeme (String),
+    lexP,
+    parens,
+    pfail,
+    readPrec,
+  )
+
+-- | ECDSA signature with a recovery id, in the internal representation of
+-- libsecp256k1 (65 bytes). A valid t'RecSig' has both components in the range
+-- 1 to n−1, where n is the order of the curve, and a recovery id of 0 to 3.
+--
+-- The bytes in @get@ are opaque. They are not a standard encoding, and they
+-- are not portable between platforms or library versions. Use
+-- 'exportCompactRecSig' to serialize a signature and 'importCompactRecSig' to
+-- parse one. 'recSig' only exists to rebuild a signature from the bytes of
+-- @get@ on the same platform.
+--
+-- 'Show', 'Read' and 'IsString' use hex of the 65-byte encoding that
+-- 'exportCompactRecSig' gives: r and s as 32-byte big-endian numbers, then
+-- the recovery id as one byte.
+newtype RecSig = RecSig ByteString
+  deriving (Eq, Generic, Hashable, NFData)
+
+-- | The bytes of a t'RecSig', read as @x.get@. @get@ is not a field, so no
+-- record update can replace them: see the instances of
+-- "Crypto.Secp256k1.Internal.Base".
+instance HasField "get" RecSig ByteString where
+  getField (RecSig bytes) = bytes
+
+instance Read RecSig where
+  readPrec = parens $ do
+    String str <- lexP
+    maybe pfail return $ recSigFromEncoding =<< decodeHex str
+
+instance IsString RecSig where
+  fromString = fromMaybe e . (recSigFromEncoding <=< decodeHex)
+    where
+      e = error "Could not decode recoverable signature from hex string"
+
+instance Show RecSig where
+  showsPrec _ = showsHex . recSigToEncoding
+
+-- | The 65-byte encoding of a signature: the compact encoding of r and s,
+-- then the recovery id as one byte. Used by the 'Show' instance.
+recSigToEncoding :: RecSig -> ByteString
+recSigToEncoding rs = compact.get `BS.snoc` rec_id
+  where
+    (compact, rec_id) = exportCompactRecSig rs
+
+-- | 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 (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 t'RecSig' on the same
+-- platform. 'Nothing' unless the bytes are the canonical representation of a
+-- signature whose components are both in the range 1 to n−1, with a recovery
+-- id of 0 to 3. Signatures from other sources go through
+-- 'importCompactRecSig'.
+recSig :: ByteString -> Maybe RecSig
+recSig bs
+  | isCanonicalRecSig bs = Just (RecSig bs)
+  | otherwise = Nothing
+
+-- | Serialize the internal bytes to the compact encoding and the id, parse
+-- those back and compare, as 'Crypto.Secp256k1.Internal.Base.isCanonicalSig'
+-- does. Parsing checks that both components are below the curve order and
+-- that the id is 0 to 3. Comparing the bytes rejects non-canonical forms, so
+-- that each signature has one representation and 'Eq' is meaningful. Zero
+-- components are rejected too, so that 'convertRecSig' always gives a valid
+-- t'Sig'.
+isCanonicalRecSig :: ByteString -> Bool
+isCanonicalRecSig bs =
+  BS.length bs == 65
+    && unsafePerformIO
+      ( 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)
+      )
+
+-- | 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 :: 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 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
+-- key comes out: no point has the x coordinate that r and the recovery id
+-- give, or the computation reaches the point at infinity.
+--
+-- A key that comes out verifies the signature for the hash, except for the
+-- lower-S rule, which recovery does not apply: the high-S form of a
+-- signature, with the parity bit of its recovery id flipped, recovers the
+-- 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 :: 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 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 :: RecSig -> Sig
+convertRecSig (RecSig rec_sig) =
+  unsafePerformIO $
+    useFixedByteString "RecSig" 65 rec_sig $ \(rec_sig_ptr, _) -> do
+      out <- withOutput 64 $ \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 :: 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 t'Sig', as 'Crypto.Secp256k1.importCompactSig' does.
+  guard (hasNonZeroComponents compact)
+  unsafePerformIO $
+    useFixedByteString "CompactSig" 64 compact $ \(compact_ptr, _) ->
+      (fmap . fmap) RecSig . withOutput 65 $ \out ->
+        isSuccess
+          <$> 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 :: 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 globalContext compact_ptr rec_id_ptr rec_sig_ptr
+        case out of
+          Nothing -> error "could not serialize recoverable signature"
+          Just compact -> do
+            rec_id <- peek rec_id_ptr
+            return (CompactSig compact, fromIntegral rec_id)
diff --git a/src/Crypto/Secp256k1/Internal/RecoveryOps.hs b/src/Crypto/Secp256k1/Internal/RecoveryOps.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Internal/RecoveryOps.hs
@@ -0,0 +1,74 @@
+-- | Foreign imports of the @recovery@ module of libsecp256k1, which the
+-- 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,
+    Msg32,
+    NonceFun,
+    PubKey64,
+    RecSig65,
+    Ret,
+    SecKey32,
+    Sig64,
+  )
+import Foreign (FunPtr, Ptr)
+import Foreign.C (CInt (..))
+
+-- | Binding to @secp256k1_ecdsa_recoverable_signature_parse_compact@.
+foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_parse_compact"
+  ecdsaRecoverableSignatureParseCompact ::
+    Ptr LCtx ->
+    Ptr RecSig65 ->
+    Ptr Compact64 ->
+    -- | recovery id, 0 to 3
+    CInt ->
+    IO Ret
+
+-- | Binding to @secp256k1_ecdsa_recoverable_signature_serialize_compact@.
+foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_serialize_compact"
+  ecdsaRecoverableSignatureSerializeCompact ::
+    Ptr LCtx ->
+    Ptr Compact64 ->
+    -- | recovery id, written by the function
+    Ptr CInt ->
+    Ptr RecSig65 ->
+    IO Ret
+
+-- | Binding to @secp256k1_ecdsa_recoverable_signature_convert@.
+foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_convert"
+  ecdsaRecoverableSignatureConvert ::
+    Ptr LCtx ->
+    -- | output
+    Ptr Sig64 ->
+    -- | input
+    Ptr RecSig65 ->
+    IO Ret
+
+-- | Binding to @secp256k1_ecdsa_sign_recoverable@.
+foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_sign_recoverable"
+  ecdsaSignRecoverable ::
+    Ptr LCtx ->
+    Ptr RecSig65 ->
+    Ptr Msg32 ->
+    Ptr SecKey32 ->
+    FunPtr (NonceFun a) ->
+    -- | nonce data
+    Ptr a ->
+    IO Ret
+
+-- | Binding to @secp256k1_ecdsa_recover@.
+foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recover"
+  ecdsaRecover ::
+    Ptr LCtx ->
+    Ptr PubKey64 ->
+    Ptr RecSig65 ->
+    Ptr Msg32 ->
+    IO Ret
diff --git a/src/Crypto/Secp256k1/Internal/Util.hs b/src/Crypto/Secp256k1/Internal/Util.hs
--- a/src/Crypto/Secp256k1/Internal/Util.hs
+++ b/src/Crypto/Secp256k1/Internal/Util.hs
@@ -1,44 +1,112 @@
 {-# LANGUAGE FlexibleContexts #-}
+
+-- | Helpers to move bytes between Haskell and the C library safely.
+--
+-- Most mistakes in C bindings are about memory: passing a buffer of the wrong
+-- size, letting the C side write into a 'ByteString' that other code shares,
+-- or leaking a buffer when an exception is thrown. Every binding goes through
+-- these functions, which check lengths before calling C, give the C library
+-- fresh buffers to write into, and free them on every path. This module is
+-- internal and has no API stability guarantee.
 module Crypto.Secp256k1.Internal.Util where
 
+import Control.Exception (onException)
 import Crypto.Secp256k1.Internal.ForeignTypes (Seed32)
-import Data.Base16.Types (assertBase16, extractBase16)
+import Data.Base16.Types (extractBase16)
 import Data.ByteString (ByteString)
 import qualified Data.ByteString as BS
-import Data.ByteString.Base16 (decodeBase16, encodeBase16, isBase16)
+import Data.ByteString.Base16 (decodeBase16, encodeBase16, parseBase16)
 import qualified Data.ByteString.Unsafe as BU
 import Data.String.Conversions (ConvertibleStrings, cs)
-import Foreign (Ptr, castPtr)
+import Foreign (Ptr, castPtr, copyBytes, free, mallocBytes)
 import Foreign.C (CSize (..))
 import System.Entropy (getEntropy)
 
+-- | Decode hex, or 'Nothing' if the string is not valid hex.
 decodeHex :: (ConvertibleStrings a ByteString) => a -> Maybe ByteString
 decodeHex str =
-  if isBase16 $ cs str
-    then Just . decodeBase16 $ assertBase16 $ cs str
-    else Nothing
+  case parseBase16 $ cs str of
+    Right b16 -> Just $ decodeBase16 b16
+    Left _ -> Nothing
 
+-- | Show bytes as a quoted hex string.
 showsHex :: ByteString -> ShowS
 showsHex = shows . extractBase16 . encodeBase16
 
+-- | Pass the bytes of a 'ByteString' to C without copying them. Only for
+-- arguments that the C library reads and never writes: writing would change a
+-- 'ByteString' that may be shared.
 unsafeUseByteString :: ByteString -> ((Ptr a, CSize) -> IO b) -> IO b
 unsafeUseByteString bs f =
   BU.unsafeUseAsCStringLen bs $ \(b, l) ->
     f (castPtr b, fromIntegral l)
 
+-- | Pass a copy of the bytes of a 'ByteString' to C.
 useByteString :: ByteString -> ((Ptr a, CSize) -> IO b) -> IO b
 useByteString bs f =
   BS.useAsCStringLen bs $ \(b, l) ->
     f (castPtr b, fromIntegral l)
 
+-- | Like 'unsafeUseByteString', for an argument that the C library reads as a
+-- fixed number of bytes. A 'ByteString' of any other length would make the
+-- library read outside the buffer, so this raises an error instead. The name
+-- is the Haskell type, for the error message.
+useFixedByteString ::
+  String -> Int -> ByteString -> ((Ptr a, CSize) -> IO b) -> IO b
+useFixedByteString name len bs f
+  | BS.length bs == len = unsafeUseByteString bs f
+  | otherwise = wrongLength name len bs
+
+-- | Raise the error for a value of the wrong length. The name is the Haskell
+-- type, for the error message.
+wrongLength :: String -> Int -> ByteString -> a
+wrongLength name len bs =
+  error $
+    name
+      ++ " must be "
+      ++ show len
+      ++ " bytes long, got "
+      ++ show (BS.length bs)
+
+-- | Allocate a buffer of the given size for the C library to fill. The buffer
+-- becomes the result when the action reports success. It is freed when the
+-- action reports failure or throws.
+withOutput :: Int -> (Ptr a -> IO Bool) -> IO (Maybe ByteString)
+withOutput len f = do
+  ptr <- mallocBytes len
+  ok <- f ptr `onException` free ptr
+  if ok
+    then Just <$> unsafePackByteString (ptr, fromIntegral len)
+    else free ptr >> return Nothing
+
+-- | Like 'withOutput', for a C function that always fills the buffer.
+fillOutput :: Int -> (Ptr a -> IO ()) -> IO ByteString
+fillOutput len f = do
+  ptr <- mallocBytes len
+  f ptr `onException` free ptr
+  unsafePackByteString (ptr, fromIntegral len)
+
+-- | Like 'withOutput', with the buffer starting as a copy of a fixed-size
+-- input that the C library modifies in place. The input is left untouched.
+withCopy ::
+  String -> Int -> ByteString -> (Ptr a -> IO Bool) -> IO (Maybe ByteString)
+withCopy name len bs f =
+  useFixedByteString name len bs $ \(src, _) ->
+    withOutput len $ \dst -> do
+      copyBytes dst (castPtr src) len
+      f dst
+
+-- | Take ownership of a @malloc@'ed buffer as a 'ByteString', without copying.
 unsafePackByteString :: (Ptr a, CSize) -> IO ByteString
 unsafePackByteString (b, l) =
   BU.unsafePackMallocCStringLen (castPtr b, fromIntegral l)
 
+-- | Copy a C buffer into a new 'ByteString'.
 packByteString :: (Ptr a, CSize) -> IO ByteString
 packByteString (b, l) =
   BS.packCStringLen (castPtr b, fromIntegral l)
 
+-- | Pass 32 bytes from the operating system's secure random source to C.
 withRandomSeed :: (Ptr Seed32 -> IO a) -> IO a
 withRandomSeed go = do
   bs <- getEntropy 32
diff --git a/src/Crypto/Secp256k1/Recovery.hs b/src/Crypto/Secp256k1/Recovery.hs
new file mode 100644
--- /dev/null
+++ b/src/Crypto/Secp256k1/Recovery.hs
@@ -0,0 +1,72 @@
+-- | ECDSA public key recovery, through the @recovery@ module of
+-- <https://github.com/bitcoin-core/secp256k1 libsecp256k1>.
+--
+-- Up to four public keys verify a given ECDSA signature (r, s) of a hash. A
+-- recovery id of 0 to 3 says which one: R is the point whose x coordinate is
+-- r, or r + n for the ids 2 and 3, and whose y coordinate is even for the
+-- ids 0 and 2 and odd for 1 and 3. The key is then Q = r⁻¹(s·R − e·G), where
+-- e is the hash as a number. 'signRecMsg' signs and keeps the id, and
+-- 'recover' computes the key from a signature, its id and the hash.
+--
+-- Bitcoin signed messages use this: a signature is 65 bytes, a header byte
+-- followed by r and s, and the verifier recovers the key and compares its
+-- address with the one given. The header byte is 27 plus the id, plus 4 for
+-- a compressed key, and BIP 137 adds 8 or 12 more for a SegWit address.
+-- 'exportCompactRecSig' and 'importCompactRecSig' convert between a t'RecSig'
+-- and the r‖s bytes with the id; the header byte itself is left to the
+-- caller.
+--
+-- == Relation to the ECDSA functions
+--
+-- 'signRecMsg' uses the same RFC 6979 nonce as 'Crypto.Secp256k1.signMsg',
+-- so 'convertRecSig' of its result is the signature that
+-- 'Crypto.Secp256k1.signMsg' gives, in lower-S form. There is no low-R
+-- grinding, and Bitcoin Core does not grind either when it signs a message,
+-- so message signatures are byte for byte the same as Bitcoin Core's.
+--
+-- 'recover' does not apply the lower-S rule of 'Crypto.Secp256k1.verifySig'.
+-- The high-S form of a signature, with the parity bit of its id flipped,
+-- recovers the same key, and Bitcoin Core accepts such message signatures
+-- too. Where the rule matters, check 'Crypto.Secp256k1.isLowS' on
+-- 'convertRecSig'.
+--
+-- The ids 2 and 3 only come out of 'signRecMsg' when r is below p − n, which
+-- happens for about one signature in 2^128. 'importCompactRecSig' accepts
+-- them and 'recover' handles them.
+--
+-- == The recovery module of libsecp256k1
+--
+-- libsecp256k1 only has this module when it was built with
+-- @--enable-module-recovery@, or @SECP256K1_ENABLE_MODULE_RECOVERY=ON@ with
+-- CMake. That is off by default upstream, but on in the libraries that
+-- Debian, Ubuntu, Fedora, Arch, Alpine, openSUSE, Homebrew and Nixpkgs ship.
+-- This package binds it when its @recovery@ flag is on, which is the
+-- default. With a library built without the module, the first program to
+-- link fails with an undefined reference to @secp256k1_ecdsa_recover@. Build
+-- the package with @-f -recovery@ then, and this module is not available.
+--
+-- == Values
+--
+-- t'RecSig' is built through 'signRecMsg', 'importCompactRecSig' or 'recSig',
+-- which validate it, so a t'RecSig' always has both components in the range 1
+-- to n−1 and an id of 0 to 3. @x.get@ gives the internal representation
+-- of libsecp256k1, which is opaque and not portable. 'Show',
+-- 'Read' and 'Data.String.IsString' use hex of r and s as 32-byte big-endian
+-- numbers followed by the id as one byte. The raw constructor is in
+-- "Crypto.Secp256k1.Internal.Recovery", which has no API stability
+-- guarantee.
+module Crypto.Secp256k1.Recovery
+  ( -- * Recoverable signatures
+    RecSig,
+    recSig,
+    signRecMsg,
+    recover,
+    convertRecSig,
+
+    -- ** Compact
+    importCompactRecSig,
+    exportCompactRecSig,
+  )
+where
+
+import Crypto.Secp256k1.Internal.Recovery
diff --git a/test/Crypto/Secp256k1/EllSwiftSpec.hs b/test/Crypto/Secp256k1/EllSwiftSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Crypto/Secp256k1/EllSwiftSpec.hs
@@ -0,0 +1,178 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+-- | ElligatorSwift and the Diffie-Hellman exchange of BIP 324. The module
+-- under test only exists when the @ellswift@ flag of the package is on, so
+-- the whole specification is behind the same flag. This module avoids string
+-- gaps, because CPP would join their lines.
+--
+-- The vectors are the files of BIP 324, copied unchanged into @test/data@
+-- from <https://github.com/bitcoin/bips/tree/master/bip-0324> at commit
+-- 8455d73ddfd763c1057e176d4919b0b061c786f6.
+module Crypto.Secp256k1.EllSwiftSpec (spec) where
+
+import Test.Hspec
+
+#ifdef ELLSWIFT
+
+import Control.Exception (evaluate)
+import Control.Monad (forM_, unless)
+import Crypto.Secp256k1
+import Crypto.Secp256k1.EllSwift
+import Crypto.Secp256k1.Internal.EllSwift (EllSwift (EllSwift))
+import Crypto.Secp256k1.Internal.Util (decodeHex)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Char8 qualified as C
+import Data.Maybe (fromJust, isNothing)
+import Data.String (fromString)
+import Test.QuickCheck
+import Text.Read (readMaybe)
+
+spec :: Spec
+spec = describe "ElligatorSwift" $ do
+  vectorSpec
+  propertySpec
+  valueSpec
+
+-- * The files of BIP 324
+
+-- | The rows of a CSV file of the BIP, each as a list of fields by name. The
+-- files have no quoted fields.
+readCsv :: FilePath -> IO [[(ByteString, ByteString)]]
+readCsv path = do
+  ls <- filter (not . BS.null) . C.lines . C.filter (/= '\r') <$> BS.readFile path
+  case ls of
+    [] -> fail ("empty file " <> path)
+    hdr : rows -> return [zip (C.split ',' hdr) (C.split ',' r) | r <- rows]
+
+field :: ByteString -> [(ByteString, ByteString)] -> ByteString
+field name row = maybe (error ("no field " <> C.unpack name)) id (lookup name row)
+
+hexField :: ByteString -> [(ByteString, ByteString)] -> ByteString
+hexField name = fromJust . decodeHex . field name
+
+-- | The x coordinate of a public key, from its compressed encoding.
+xOf :: PubKey -> ByteString
+xOf = BS.drop 1 . exportPubKey True
+
+vectorSpec :: Spec
+vectorSpec = describe "vectors of BIP 324" $ do
+  it "decodes the 76 encodings of ellswift_decode_test_vectors.csv" $ do
+    rows <- readCsv "test/data/ellswift_decode_test_vectors.csv"
+    length rows `shouldBe` 76
+    forM_ rows $ \row -> do
+      let ell = fromJust (ellSwift (hexField "ellswift" row))
+      (field "comment" row, xOf (ellSwiftDecode ell))
+        `shouldBe` (field "comment" row, hexField "x" row)
+  -- libsecp256k1 does not expose the inverse map xswiftec_inv, so which of
+  -- the eight cases gives which t, and that the empty cases have none,
+  -- cannot be checked through it. Every t that the file gives is checked
+  -- the other way: u and t decode to the point of x.
+  it "decodes u and each of the 98 values of t of xswiftec_inv_test_vectors.csv to x" $ do
+    rows <- readCsv "test/data/xswiftec_inv_test_vectors.csv"
+    length rows `shouldBe` 32
+    let pairs =
+          [ (hexField "u" row <> t, hexField "x" row)
+          | row <- rows,
+            c <- [0 .. 7 :: Int],
+            let name = "case" <> C.pack (show c) <> "_t",
+            not (BS.null (field name row)),
+            let t = hexField name row
+          ]
+    length pairs `shouldBe` 98
+    forM_ pairs $ \(ell, x) -> xOf (ellSwiftDecode (fromJust (ellSwift ell))) `shouldBe` x
+  it "computes the keys and secrets of the 7 rows of packet_encoding_test_vectors.csv" $ do
+    rows <- readCsv "test/data/packet_encoding_test_vectors.csv"
+    length rows `shouldBe` 7
+    forM_ rows $ \row -> do
+      let priv = fromJust (secKey (hexField "in_priv_ours" row))
+          ours = fromJust (ellSwift (hexField "in_ellswift_ours" row))
+          theirs = fromJust (ellSwift (hexField "in_ellswift_theirs" row))
+          initiating = field "in_initiating" row == "1"
+          shared
+            | initiating = ellSwiftXdhBip324 ours theirs priv PartyA
+            | otherwise = ellSwiftXdhBip324 theirs ours priv PartyB
+          point = fromJust (tweakMulPubKey (ellSwiftDecode theirs) (fromJust (tweak priv.get)))
+      xOf (derivePubKey priv) `shouldBe` hexField "mid_x_ours" row
+      xOf (ellSwiftDecode ours) `shouldBe` hexField "mid_x_ours" row
+      xOf (ellSwiftDecode theirs) `shouldBe` hexField "mid_x_theirs" row
+      xOf point `shouldBe` hexField "mid_x_shared" row
+      shared `shouldBe` hexField "mid_shared_secret" row
+
+propertySpec :: Spec
+propertySpec = describe "properties" $ do
+  it "decodes the encoding of a secret key to its public key (key_ellswift of Bitcoin Core)" $
+    property $ \key aux -> do
+      let ell = fromJust (ellSwiftCreate key (Just (bytes32 aux)))
+      ellSwiftDecode ell `shouldBe` derivePubKey key
+  it "decodes the encoding of a secret key made without randomness" $
+    property $ \key ->
+      ellSwiftDecode (fromJust (ellSwiftCreate key Nothing)) `shouldBe` derivePubKey key
+  it "decodes an encoded public key to the same key" $
+    property $ \key rnd -> do
+      let pub = derivePubKey key
+      ellSwiftDecode (fromJust (ellSwiftEncode pub (bytes32 rnd))) `shouldBe` pub
+  it "gives both parties the same secret, and another secret to a third key" $
+    property $ \a b c auxA auxB -> do
+      let ellA = fromJust (ellSwiftCreate a (Just (bytes32 auxA)))
+          ellB = fromJust (ellSwiftCreate b (Just (bytes32 auxB)))
+          secretA = ellSwiftXdhBip324 ellA ellB a PartyA
+          secretB = ellSwiftXdhBip324 ellA ellB b PartyB
+      secretA `shouldBe` secretB
+      BS.length secretA `shouldBe` 32
+      unless (c == a) $ ellSwiftXdhBip324 ellA ellB c PartyA `shouldNotBe` secretA
+  it "gives another secret when the parties swap their roles" $
+    property $ \a b -> do
+      let ellA = fromJust (ellSwiftCreate a Nothing)
+          ellB = fromJust (ellSwiftCreate b Nothing)
+      ellSwiftXdhBip324 ellB ellA a PartyB `shouldNotBe` ellSwiftXdhBip324 ellA ellB a PartyA
+  it "decodes any 64 bytes" $
+    property $ \(Bytes64 bs) ->
+      BS.length (exportPubKey True (ellSwiftDecode (fromJust (ellSwift bs)))) `shouldBe` 33
+
+valueSpec :: Spec
+valueSpec = describe "values" $ do
+  it "refuses an encoding of another length than 64 bytes" $
+    forM_ [0, 1, 32, 63, 65, 128] $ \n ->
+      ellSwift (BS.replicate n 0) `shouldSatisfy` isNothing
+  it "refuses randomness of another length than 32 bytes" $ do
+    let key = fromJust (secKey (BS.replicate 31 0 <> "\1"))
+    forM_ [0, 16, 31, 33] $ \n -> do
+      ellSwiftCreate key (Just (BS.replicate n 0)) `shouldSatisfy` isNothing
+      ellSwiftEncode (derivePubKey key) (BS.replicate n 0) `shouldSatisfy` isNothing
+  it "makes a fresh encoding each time with ellSwiftCreateIO" $ do
+    let key = fromJust (secKey (BS.replicate 31 0 <> "\2"))
+    e1 <- ellSwiftCreateIO key
+    e2 <- ellSwiftCreateIO key
+    e1 `shouldNotBe` e2
+    ellSwiftDecode e1 `shouldBe` ellSwiftDecode e2
+  it "shows, reads and parses hex" $
+    property $ \(Bytes64 bs) -> do
+      let e = EllSwift bs
+      readMaybe (show e) `shouldBe` Just e
+      fromString (read (show e)) `shouldBe` e
+      e.get `shouldBe` bs
+  it "raises an error for a raw encoding of the wrong length" $
+    evaluate (ellSwiftDecode (EllSwift "short")) `shouldThrow` anyErrorCall
+
+-- | 32 bytes from a list of arbitrary bytes, padded or cut.
+bytes32 :: [Word] -> ByteString
+bytes32 ws = BS.pack (take 32 (map fromIntegral ws ++ repeat 0))
+
+-- | 64 arbitrary bytes.
+newtype Bytes64 = Bytes64 ByteString
+  deriving (Show)
+
+instance Arbitrary Bytes64 where
+  arbitrary = Bytes64 . BS.pack <$> vectorOf 64 arbitrary
+
+#else
+
+spec :: Spec
+spec = describe "ElligatorSwift" $
+  it "is not built: the ellswift flag is off" (pendingWith "flag ellswift off")
+
+#endif
diff --git a/test/Crypto/Secp256k1/Fixtures.hs b/test/Crypto/Secp256k1/Fixtures.hs
new file mode 100644
--- /dev/null
+++ b/test/Crypto/Secp256k1/Fixtures.hs
@@ -0,0 +1,129 @@
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+-- | Fixtures and helpers shared by the specifications.
+module Crypto.Secp256k1.Fixtures where
+
+import Crypto.Secp256k1
+import Data.Base16.Types (assertBase16, extractBase16)
+import Data.ByteString qualified as BS
+import Data.ByteString.Base16 (decodeBase16, encodeBase16')
+import Data.ByteString.Char8 qualified as B8
+import Data.Maybe (fromJust)
+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",
+-- Bitcoin Core's key_tests.cpp, or this package's historical vectors, all
+-- recomputed with an independent implementation of the curve.
+
+zero, one, order, orderMinusOne, orderPlusOne, allOnes :: String
+zero = "0000000000000000000000000000000000000000000000000000000000000000"
+one = "0000000000000000000000000000000000000000000000000000000000000001"
+order = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
+orderMinusOne = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"
+orderPlusOne = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364142"
+allOnes = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
+
+-- Secret key 1. Its public key is the generator G.
+keyOne :: SecKey
+keyOne = fromString one
+
+-- The generator G in its three SEC1 encodings. y is even, so the compressed
+-- prefix is 02 and the hybrid prefix is 06.
+genCompressed, genUncompressed, genHybrid :: String
+genCompressed =
+  "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
+genUncompressed =
+  "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
+  \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
+genHybrid =
+  "0679be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
+  \483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
+
+-- RFC 6979 vector: key 1 signing sha256 "Satoshi Nakamoto".
+satoshiMsg :: Msg
+satoshiMsg = "a0dc65ffca799873cbea0ac274015b9526505daaaed385155425f7337704883e"
+
+satoshiR, satoshiS, satoshiHighS :: String
+satoshiR = "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d8"
+satoshiS = "2442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5"
+-- n - s
+satoshiHighS = "dbbd3162d46e9f9bef7feb87c16dc13b4f6568a87f4e83f728e2443ba586675c"
+
+satoshiDer :: String
+satoshiDer = "3045022100" ++ satoshiR ++ "0220" ++ satoshiS
+
+-- Bitcoin Core key_tests.cpp: the secret key of WIF
+-- 5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj signing
+-- sha256d "Very deterministic message".
+coreKey :: SecKey
+coreKey = "12b004fff7f4b69ef8650e767f18f11ede158148b425660723b9f9a66e61f747"
+
+coreMsg :: Msg
+coreMsg = "5255683da567900bfd3e786ed8836a4e7763c221bf1ac20ece2a5171b9199e8a"
+
+coreDer :: String
+coreDer =
+  "304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d\
+  \022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"
+
+-- Key 1 signing sha256 "4". Plain RFC 6979 gives a high r (first byte d4),
+-- so Bitcoin Core's grinding retries once with counter 1 as extra nonce data.
+highRMsg :: Msg
+highRMsg = "4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a"
+
+highRDer, groundDer :: String
+highRDer =
+  "3045022100d479c93a086bf5f4ae1fed7eaf2604a4da2007d851c5409961c81dd7f0600194\
+  \02201cd7a196454152f5b8d19865d49b4fa71e314ebff9c59e2f7b2295bf80331be8"
+groundDer =
+  "3044022020b11f7066dd4486e811ea4f1fee43b1538fcd5bedb64b52d01e56b13422430c\
+  \022056cb81320c8439cee666af08788c08e60fda80216a25f52b38714191c8cd1b99"
+
+-- Key 1 signing sha256 "1". Plain RFC 6979 already gives a low r.
+lowRMsg :: Msg
+lowRMsg = "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
+
+lowRDer :: String
+lowRDer =
+  "304402202d24f8d536fccf696a4edfa858e5d6fc89a11d25f72ef4f89de1577d53643c0a\
+  \02200d25586b118d5d7f8b79a7805c885fa8588dfa9e6cc777edc11a7e33de844285"
+
+-- Historical vectors of this package.
+histKey :: SecKey
+histKey = "f65255094d7773ed8dd417badc9fc045c1f80fdc5b2d25172b031ce6933e039a"
+
+histTweak :: Tweak
+histTweak = "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
+
+histPub :: String
+histPub =
+  "04dded4203dac96a7e85f2c374a37ce3e9c9a155a72b64b4551b0bfe779dd44705\
+  \12213d5ed790522c042dee8e85c4c0ec5f96800b72bc5940c8bc1c5e11e4fcbf"
+
+-- The field size p of secp256k1. It is not a valid x coordinate.
+fieldSize :: String
+fieldSize = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
+
+-- * Helpers
+
+hexToBytes :: String -> BS.ByteString
+hexToBytes = decodeBase16 . assertBase16 . B8.pack
+
+bytesToHex :: BS.ByteString -> String
+bytesToHex = B8.unpack . extractBase16 . encodeBase16'
+
+showRead :: (Show a, Read a, Eq a) => a -> Bool
+showRead x = read (show x) == x
+
+-- The hex literal, quoted the way 'show' quotes a string.
+quoted :: String -> String
+quoted s = "\"" ++ s ++ "\""
+
+-- The negation of a public key: multiplication by n - 1.
+negatePubKey :: PubKey -> PubKey
+negatePubKey p = fromJust (tweakMulPubKey p (fromString orderMinusOne))
diff --git a/test/Crypto/Secp256k1/InternalSpec.hs b/test/Crypto/Secp256k1/InternalSpec.hs
--- a/test/Crypto/Secp256k1/InternalSpec.hs
+++ b/test/Crypto/Secp256k1/InternalSpec.hs
@@ -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)
@@ -19,7 +19,7 @@
 import Data.ByteString.Base16 (decodeBase16)
 import Foreign
 import System.Entropy
-import Test.HUnit (Assertion, assertBool, assertEqual, assertFailure)
+import Test.HUnit (Assertion, assertBool, assertEqual)
 import Test.Hspec
 
 spec :: Spec
@@ -348,7 +348,7 @@
         ret <- ecPubKeyTweakAdd x p w
         tweaked <- serializeKey x p
         return (ret, tweaked)
-  assertBool "successful secret key tweak" $ isSuccess ret
+  assertBool "successful public key tweak" $ isSuccess ret
   assertEqual "tweaked keys match" expected tweaked
   where
     pub =
@@ -376,7 +376,7 @@
         ret <- ecPubKeyTweakMul x p w
         tweaked <- serializeKey x p
         return (ret, tweaked)
-  assertBool "successful secret key tweak" $ isSuccess ret
+  assertBool "successful public key tweak" $ isSuccess ret
   assertEqual "tweaked keys match" expected tweaked
   where
     pub =
diff --git a/test/Crypto/Secp256k1/RecoverySpec.hs b/test/Crypto/Secp256k1/RecoverySpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Crypto/Secp256k1/RecoverySpec.hs
@@ -0,0 +1,334 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- | ECDSA public key recovery. The module under test only exists when the
+-- @recovery@ flag of the package is on, so the whole specification is behind
+-- the same flag. This module avoids string gaps, because CPP would join
+-- their lines.
+module Crypto.Secp256k1.RecoverySpec (spec) where
+
+import Test.Hspec
+
+#ifdef RECOVERY
+
+import Control.DeepSeq (deepseq)
+import Control.Exception (evaluate)
+import Control.Monad (forM_)
+import Control.Monad.Par qualified as P
+import Crypto.Secp256k1
+import Crypto.Secp256k1.Fixtures
+import Crypto.Secp256k1.Internal.Base (CompactSig (CompactSig), Msg (Msg), SecKey (SecKey))
+import Crypto.Secp256k1.Internal.Recovery (RecSig (RecSig))
+import Crypto.Secp256k1.Recovery
+import Data.Bits (xor)
+import Data.ByteString qualified as BS
+import Data.Hashable (hash)
+import Data.Maybe (fromJust, isJust)
+import Data.String (fromString)
+import Data.Word (Word8)
+import Test.QuickCheck
+import Text.Read (readMaybe)
+
+spec :: Spec
+spec = describe "public key recovery" $ do
+  signingSpec
+  recoverySpec
+  formulaSpec
+  compactSpec
+  valueSpec
+  rawValueSpec
+  instanceSpec
+
+-- * Fixtures
+--
+-- As in "Crypto.Secp256k1.Fixtures", every expected value is a literal from
+-- an independent source, recomputed with an independent implementation of
+-- the curve.
+
+-- Bitcoin Core key_tests.cpp: the SignCompact signature of coreKey over
+-- coreMsg is 20 ++ coreR ++ coreS. The header byte 0x20 = 32 = 27 + 1 + 4
+-- says recovery id 1 and a compressed key. coreDer is 30440220 ++ coreR ++
+-- 0220 ++ coreS.
+coreR, coreS :: String
+coreR = "5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d"
+coreS = "14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"
+
+coreRecId :: Word8
+coreRecId = 1
+
+-- The compressed public key of coreKey, and the key that recovery id 0 gives
+-- for the same signature.
+corePub, coreOtherPub :: String
+corePub = "030b4c866585dd868a9d62348a9cd008d6a312937048fff31670e7e920cfc7a744"
+coreOtherPub = "02818f8ef9ebd82871789a39ea0385398c267d3d6bb6f537166bd813135870c8ec"
+
+-- Bitcoin Core util_tests.cpp, message_sign: the key of the address
+-- 15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs signs the message "Trust no one".
+messageKey :: SecKey
+messageKey = "d97f5108f11cda6eeebaaa420fef0726b1f898060b98489fa3098463c0032866"
+
+-- sha256d of the varstrings "Bitcoin Signed Message:\n" and "Trust no one".
+messageHash :: Msg
+messageHash = "aa8215d723ecd2f14867eeb7e19f192be7bc15a2352a24b991d4f5870cbaf6e8"
+
+-- The expected signature, base64
+-- IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=
+-- decoded: the header byte 0x20, recovery id 1 and a compressed key, then r
+-- and s.
+messageR, messageS :: String
+messageR = "fa237eb5f675f3e71f6e947a07db19040badd2bce380e51eae75e7bfcfea1e7b"
+messageS = "5b2b92fd0b25fa1fd64951831783148b8ad64acc16dfca2298361f34d50150e9"
+
+-- The compressed public key of messageKey.
+messagePub :: String
+messagePub = "03d2be3dddb497c7c4388cfcb941e14a222cf3e26fe5e2cc260da1821e60d26022"
+
+-- The RFC 6979 vector has recovery id 1. Recovery id 0 gives this other key.
+satoshiOtherPub :: String
+satoshiOtherPub = "0354d58835e07b996d6378eafa930ae9d2211e767381f1d52aedc67f48c8886f0b"
+
+-- Key 1 signing sha256 "4" (highRDer): r, s and recovery id 0.
+highRR, highRS :: String
+highRR = "d479c93a086bf5f4ae1fed7eaf2604a4da2007d851c5409961c81dd7f0600194"
+highRS = "1cd7a196454152f5b8d19865d49b4fa71e314ebff9c59e2f7b2295bf80331be8"
+
+-- Values for the formula Q = r⁻¹(s·R − e·G).
+two, five :: String
+two = "0000000000000000000000000000000000000000000000000000000000000002"
+-- 5³ + 7 = 132 is not a square modulo p, so no point has x = 5.
+five = "0000000000000000000000000000000000000000000000000000000000000005"
+
+-- x = 1 is on the curve: 1 + 7 = 8 is a square modulo p. pointOne is the
+-- point with x = 1 and an even y, so its compressed encoding is 02 ++ one and
+-- that of its negation is 03 ++ one.
+pointOne, pointOneMinusG, twicePointOne :: String
+pointOne = "02" ++ one
+pointOneMinusG = "02871e0c836ec675e07395aef58d72b646f77e0e33ce1622dfaa0fb8e131f3fe12"
+twicePointOne = "03c7ffffffffffffffffffffffffffffffffffffffffffffffffffffff37fffd03"
+
+-- x = n + 2 is on the curve, x = n + 1 is not.
+orderPlusTwo :: String
+orderPlusTwo = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364143"
+
+-- Half of the point with x = n + 2 and an even y.
+halfPointOrderPlusTwo :: String
+halfPointOrderPlusTwo = "02ad802f2145df548ce1fc418b851cb32669c5a6bb939e6caf744de90310f8f1ff"
+
+-- p − n and p − n − 1. With the recovery id 2, the first gives x = p, which
+-- is outside the field, and the second x = p − 1, which is not on the curve.
+fieldMinusOrder, fieldMinusOrderMinusOne :: String
+fieldMinusOrder = "000000000000000000000000000000014551231950b75fc4402da1722fc9baee"
+fieldMinusOrderMinusOne = "000000000000000000000000000000014551231950b75fc4402da1722fc9baed"
+
+-- The x coordinate of G, and the key −(x⁻¹)·G.
+genX, genNegatedOverX :: String
+genX = drop 2 genCompressed
+genNegatedOverX = "028ff83d8cf12121491609c4939dc11c4aa35503508fe432dc5a5c1905608b9218"
+
+-- * Signing
+
+signingSpec :: Spec
+signingSpec = describe "signing" $ do
+  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'" $
+    exportCompactRecSig (signRecMsg messageKey messageHash)
+      `shouldBe` (fromString (messageR ++ messageS), 1)
+  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" $ do
+    exportCompactRecSig (signRecMsg keyOne highRMsg)
+      `shouldBe` (fromString (highRR ++ highRS), 0)
+    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 (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) xs
+      and <$> mapM P.get results
+  where
+    signsAndRecovers (m, k) =
+      recover (signRecMsg k m) m == Just (derivePubKey k)
+
+-- * Recovery
+
+recoverySpec :: Spec
+recoverySpec = describe "recovery" $ do
+  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 (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 (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 (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 (signRecMsg k m)
+          (r, s) = BS.splitAt 32 compact.get
+          -- n - s, through the negation of a tweak.
+          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 sigHex m = bytesToHex . exportPubKey True <$> recover (fromString sigHex) m
+
+-- * The formula
+
+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" $
+    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 (genX ++ one ++ "00") one `shouldBe` Nothing
+    -- With e = 2 instead: (G - 2G) / x = -(x⁻¹)·G.
+    recovered (genX ++ one ++ "00") two `shouldBe` Just genNegatedOverX
+  where
+    recovered sigHex msgHex =
+      bytesToHex . exportPubKey True <$> recover (fromString sigHex) (fromString msgHex)
+
+-- * Compact encoding
+
+compactSpec :: Spec
+compactSpec = describe "compact encoding" $ do
+  it "imports and exports back the same signature" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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 (derivePubKey k) (convertRecSig (signRecMsg k m)) m
+
+-- * Signature values
+
+valueSpec :: Spec
+valueSpec = describe "signature values" $ 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" $ do
+    -- libsecp256k1 keeps the id in the last byte of the representation.
+    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" $
+    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
+    (readMaybe (quoted (order ++ coreS ++ "01")) :: Maybe RecSig) `shouldBe` Nothing
+    (readMaybe (quoted (coreR ++ coreS ++ "0")) :: Maybe RecSig) `shouldBe` Nothing
+    evaluate (fromString (coreR ++ coreS) :: RecSig) `shouldThrow` anyErrorCall
+
+-- * Values built with the raw constructors of the Internal modules
+
+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" $
+    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 :: Spec
+instanceSpec = describe "derived instances" $ do
+  it "equal values hash equally, whichever way they were built" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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" $
+    (signRecMsg keyOne satoshiMsg `deepseq` ()) `shouldBe` ()
+
+#else
+
+spec :: Spec
+spec =
+  describe "public key recovery" $
+    it "needs the recovery flag of the package" $
+      pendingWith "the package was built with -f -recovery"
+
+#endif
diff --git a/test/Crypto/Secp256k1Spec.hs b/test/Crypto/Secp256k1Spec.hs
--- a/test/Crypto/Secp256k1Spec.hs
+++ b/test/Crypto/Secp256k1Spec.hs
@@ -1,312 +1,993 @@
 {-# LANGUAGE DuplicateRecordFields #-}
 {-# LANGUAGE ImportQualifiedPost #-}
 {-# LANGUAGE OverloadedRecordDot #-}
-
-module Crypto.Secp256k1Spec (spec) where
-
-import Control.Arrow (first)
-import Control.Monad.Par qualified as P
-import Crypto.Secp256k1
-import Data.Base16.Types (assertBase16, extractBase16)
-import Data.ByteString qualified as BS
-import Data.ByteString.Base16 (decodeBase16, encodeBase16)
-import Data.ByteString.Char8 qualified as B8
-import Data.Either (fromRight)
-import Data.Maybe (fromJust, fromMaybe, isJust, isNothing)
-import Data.String (fromString)
-import Data.String.Conversions (cs)
-import Test.HUnit (Assertion, assertBool, assertEqual)
-import Test.Hspec
-import Test.QuickCheck
-
-spec :: Spec
-spec = around withContext $ do
-  describe "signatures" $ do
-    it "signs message" $ \ctx ->
-      property $ signMsgTest ctx
-    it "signs messages in parallel" $ \ctx ->
-      property $ signMsgParTest ctx
-    it "detects bad signature" $ \ctx ->
-      property $ badSignatureTest ctx
-    it "normalizes signatures" $ \ctx ->
-      property $ normalizeSigTest ctx
-  describe "serialization" $ do
-    it "serializes public key" $ \ctx ->
-      property $ serializePubKeyTest ctx
-    it "serializes public keys in parallel" $ \ctx ->
-      property $ parSerializePubKeyTest ctx
-    it "serializes DER signature" $ \ctx ->
-      property $ serializeSigTest ctx
-    it "serializes DER signatures in parallel" $ \ctx ->
-      property $ parSerializeSigTest ctx
-    it "serializes compact signature" $ \ctx ->
-      property $ serializeCompactSigTest ctx
-    it "serialize secret key" $ \_ ->
-      property serializeSecKeyTest
-    it "shows and reads secret key" $ \_ ->
-      property (showRead :: SecKey -> Bool)
-    it "shows and reads tweak" $ \_ ->
-      property showReadTweak
-    it "shows and reads message" $ \_ ->
-      property (showRead :: Msg -> Bool)
-    it "shows and reads public key" $ \ctx ->
-      property $ showReadPubKey ctx
-    it "reads secret key from string" $ \_ ->
-      property isStringSecKey
-    it "reads message from string" $ \_ ->
-      property isStringMsg
-    it "reads tweak from string" $ \_ ->
-      property isStringTweak
-  describe "tweaks" $ do
-    it "add secret key" $ \ctx ->
-      property $ tweakAddSecKeyTest ctx
-    it "multiply secret key" $ \ctx ->
-      property $ tweakMulSecKeyTest ctx
-    it "add public key" $ \ctx ->
-      property $ tweakAddPubKeyTest ctx
-    it "multiply public key" $ \ctx ->
-      property $ tweakMulPubKeyTest ctx
-    it "combine public keys" $ \ctx ->
-      property $ combinePubKeyTest ctx
-    it "can't combine 0 public keys" $ \ctx ->
-      property $ combinePubKeyEmptyListTest ctx
-    it "negates tweak" $ \ctx ->
-      property $ negateTweakTest ctx
-
-hexToBytes :: String -> BS.ByteString
-hexToBytes = decodeBase16 . assertBase16 . B8.pack
-
-isStringMsg :: Msg -> Bool
-isStringMsg m = m == fromString (cs m')
-  where
-    m' = (extractBase16 . encodeBase16) m.get
-
-isStringSecKey :: SecKey -> Bool
-isStringSecKey k = k == fromString (cs hex)
-  where
-    hex = (extractBase16 . encodeBase16) k.get
-
-isStringTweak :: SecKey -> Bool
-isStringTweak k = t == fromString (cs hex)
-  where
-    t = (fromMaybe e . tweak) k.get
-    hex = (extractBase16 . encodeBase16) t.get
-    e = error "Could not extract tweak from secret key"
-
-showReadTweak :: SecKey -> Bool
-showReadTweak k = showRead t
-  where
-    t = tweak k.get
-
-showReadPubKey :: Ctx -> SecKey -> Bool
-showReadPubKey ctx k =
-  (read . show) p == p
-  where
-    p = derivePubKey ctx k
-
-showRead :: (Show a, Read a, Eq a) => a -> Bool
-showRead x = read (show x) == x
-
-signMsgTest :: Ctx -> (Msg, SecKey) -> Bool
-signMsgTest ctx (fm, fk) = verifySig ctx fp fg fm
-  where
-    fp = derivePubKey ctx fk
-    fg = signMsg ctx fk fm
-
-signMsgParTest :: Ctx -> [(Msg, SecKey)] -> Bool
-signMsgParTest ctx xs = P.runPar $ do
-  ys <- mapM (P.spawnP . signMsgTest ctx) xs
-  and <$> mapM P.get ys
-
-badSignatureTest :: Ctx -> (Msg, SecKey, SecKey) -> Bool
-badSignatureTest ctx (fm, fk, fk') = not $ verifySig ctx fp fg fm
-  where
-    fp = derivePubKey ctx fk'
-    fg = signMsg ctx fk fm
-
-normalizeSigTest :: Ctx -> (Msg, SecKey) -> Bool
-normalizeSigTest ctx (fm, fk) = isNothing sig
-  where
-    fg = signMsg ctx fk fm
-    sig = normalizeSig ctx fg
-
-serializePubKeyTest :: Ctx -> (SecKey, Bool) -> Bool
-serializePubKeyTest ctx (fk, b) =
-  case importPubKey ctx $ exportPubKey ctx b fp of
-    Just fp' -> fp == fp'
-    Nothing -> False
-  where
-    fp = derivePubKey ctx fk
-
-parSerializePubKeyTest :: Ctx -> [(SecKey, Bool)] -> Bool
-parSerializePubKeyTest ctx ks = P.runPar $ do
-  as <- mapM (P.spawnP . serializePubKeyTest ctx) ks
-  and <$> mapM P.get as
-  where
-    ps = map (first (derivePubKey ctx)) ks
-
-serializeSigTest :: Ctx -> (Msg, SecKey) -> Bool
-serializeSigTest ctx (fm, fk) =
-  case importSig ctx $ exportSig ctx fg of
-    Just fg' -> fg == fg'
-    Nothing -> False
-  where
-    fg = signMsg ctx fk fm
-
-parSerializeSigTest :: Ctx -> [(Msg, SecKey)] -> Bool
-parSerializeSigTest ctx ms = P.runPar $ do
-  as <- mapM (P.spawnP . serializeSigTest ctx) ms
-  and <$> mapM P.get as
-
-serializeCompactSigTest :: Ctx -> (Msg, SecKey) -> Bool
-serializeCompactSigTest ctx (fm, fk) =
-  case importCompactSig ctx $ exportCompactSig ctx fg of
-    Just fg' -> fg == fg'
-    Nothing -> False
-  where
-    fg = signMsg ctx fk fm
-
-serializeSecKeyTest :: SecKey -> Bool
-serializeSecKeyTest fk =
-  case secKey fk.get of
-    Just fk' -> fk == fk'
-    Nothing -> False
-
-tweakAddSecKeyTest :: Ctx -> Assertion
-tweakAddSecKeyTest ctx =
-  assertEqual "tweaked keys match" expected tweaked
-  where
-    tweaked = do
-      key <-
-        secKey $
-          hexToBytes
-            "f65255094d7773ed8dd417badc9fc045c1f80fdc5b2d25172b031ce6933e039a"
-      twk <-
-        tweak $
-          hexToBytes
-            "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
-      tweakAddSecKey ctx key twk
-    expected =
-      secKey $
-        hexToBytes
-          "ec1e3ce1cefa18a671d51125e2b249688d934b0e28f5d1665384d9b02f929059"
-
-tweakMulSecKeyTest :: Ctx -> Assertion
-tweakMulSecKeyTest ctx =
-  assertEqual "tweaked keys match" expected tweaked
-  where
-    tweaked = do
-      key <-
-        secKey $
-          hexToBytes
-            "f65255094d7773ed8dd417badc9fc045c1f80fdc5b2d25172b031ce6933e039a"
-      twk <-
-        tweak $
-          hexToBytes
-            "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
-      tweakMulSecKey ctx key twk
-    expected =
-      secKey $
-        hexToBytes
-          "a96f5962493acb179f60a86a9785fc7a30e0c39b64c09d24fe064d9aef15e4c0"
-
-tweakAddPubKeyTest :: Ctx -> Assertion
-tweakAddPubKeyTest ctx = do
-  assertBool "did not fail to decode" $ isJust tweaked
-  assertBool "is not empty" $ not $ maybe False BS.null tweaked
-  assertEqual "tweaked keys match" expected tweaked
-  where
-    tweaked = do
-      pub <-
-        importPubKey ctx $
-          hexToBytes
-            "04dded4203dac96a7e85f2c374a37ce3e9c9a155a72b64b4551b0bfe779dd4470512213d5ed790522c042dee8e85c4c0ec5f96800b72bc5940c8bc1c5e11e4fcbf"
-      twk <-
-        tweak $
-          hexToBytes
-            "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
-      key <- tweakAddPubKey ctx pub twk
-      return $ exportPubKey ctx True key
-    expected = do
-      key <-
-        importPubKey ctx $
-          hexToBytes
-            "04441c3982b97576646e0df0c96736063df6b42f2ee566d13b9f6424302d1379e518fdc87a14c5435bff7a5db4552042cb4120c6b86a4bbd3d0643f3c14ad01368"
-      return $ exportPubKey ctx True key
-
-tweakMulPubKeyTest :: Ctx -> Assertion
-tweakMulPubKeyTest ctx = do
-  assertBool "did not fail to decode" $ isJust tweaked
-  assertBool "is not empty" $ not $ maybe False BS.null tweaked
-  assertEqual "tweaked keys match" expected tweaked
-  where
-    tweaked = do
-      pub <-
-        importPubKey ctx $
-          hexToBytes
-            "04dded4203dac96a7e85f2c374a37ce3e9c9a155a72b64b4551b0bfe779dd4470512213d5ed790522c042dee8e85c4c0ec5f96800b72bc5940c8bc1c5e11e4fcbf"
-      twk <-
-        tweak $
-          hexToBytes
-            "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
-      key <- tweakMulPubKey ctx pub twk
-      return $ exportPubKey ctx True key
-    expected = do
-      key <-
-        importPubKey ctx $
-          hexToBytes
-            "04f379dc99cdf5c83e433defa267fbb3377d61d6b779c06a0e4ce29ae3ff5353b12ae49c9d07e7368f2ba5a446c203255ce912322991a2d6a9d5d5761c61ed1845"
-      return $ exportPubKey ctx True key
-
-combinePubKeyTest :: Ctx -> Assertion
-combinePubKeyTest ctx = do
-  assertBool "did not fail to decode" $ isJust combined
-  assertBool "is not empty" $ not $ maybe False BS.null combined
-  assertEqual "combined keys match" expected combined
-  where
-    combined = do
-      pub1 <-
-        importPubKey ctx $
-          hexToBytes
-            "04dded4203dac96a7e85f2c374a37ce3e9c9a155a72b64b4551b0bfe779dd4470512213d5ed790522c042dee8e85c4c0ec5f96800b72bc5940c8bc1c5e11e4fcbf"
-      pub2 <-
-        importPubKey ctx $
-          hexToBytes
-            "0487d82042d93447008dfe2af762068a1e53ff394a5bf8f68a045fa642b99ea5d153f577dd2dba6c7ae4cfd7b6622409d7edd2d76dd13a8092cd3af97b77bd2c77"
-      pub3 <-
-        importPubKey ctx $
-          hexToBytes
-            "049b101edcbe1ee37ff6b2318526a425b629e823d7d8d9154417880595a28000ee3febd908754b8ce4e491aa6fe488b41fb5d4bb3788e33c9ff95a7a9229166d59"
-      key <- combinePubKeys ctx [pub1, pub2, pub3]
-      return $ exportPubKey ctx True key
-    expected = do
-      key <-
-        importPubKey ctx $
-          hexToBytes
-            "043d9a7ec70011efc23c33a7e62d2ea73cca87797e3b659d93bea6aa871aebde56c3bc6134ca82e324b0ab9c0e601a6d2933afe7fb5d9f3aae900f5c5dc6e362c8"
-      return $ exportPubKey ctx True key
-
-combinePubKeyEmptyListTest :: Ctx -> Assertion
-combinePubKeyEmptyListTest ctx =
-  assertEqual "empty pubkey list must return Nothing" expected combined
-  where
-    expected = Nothing
-    combined = do
-      key <- combinePubKeys ctx []
-      return $ exportPubKey ctx True key
-
-negateTweakTest :: Ctx -> Assertion
-negateTweakTest ctx =
-  assertEqual "can recover secret key 1 after adding tweak 1" oneKey subtracted
-  where
-    Just oneKey =
-      secKey . decodeBase16 . assertBase16 $
-        B8.pack
-          "0000000000000000000000000000000000000000000000000000000000000001"
-    Just oneTwk =
-      tweak . decodeBase16 . assertBase16 $
-        B8.pack
-          "0000000000000000000000000000000000000000000000000000000000000001"
-    Just minusOneTwk = tweakNegate ctx oneTwk
-    Just twoKey = tweakAddSecKey ctx oneKey oneTwk
-    Just subtracted = tweakAddSecKey ctx twoKey minusOneTwk
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Crypto.Secp256k1Spec (spec) where
+
+import Control.DeepSeq (deepseq)
+import Control.Exception (evaluate)
+import Control.Monad.Par qualified as P
+import Crypto.Secp256k1
+import Crypto.Secp256k1.Fixtures
+import Crypto.Secp256k1.Internal.Base
+  ( CompactSig (CompactSig),
+    Msg (Msg),
+    PubKey (PubKey),
+    SchnorrSig (SchnorrSig),
+    SecKey (SecKey),
+    Sig (Sig),
+    Tweak (Tweak),
+    signMsgWith,
+  )
+import Data.Bits (xor)
+import Data.ByteString qualified as BS
+import Data.Hashable (hash)
+import Data.Maybe (fromJust, isJust, isNothing)
+import Data.String (fromString)
+import Test.Hspec
+import Test.QuickCheck
+import Text.Read (readMaybe)
+
+spec :: Spec
+spec = do
+  secretKeySpec
+  publicKeySpec
+  messageSpec
+  signingSpec
+  verificationSpec
+  derSpec
+  compactSpec
+  tweakSpec
+  combineSpec
+  schnorrSpec
+  xOnlySpec
+  taprootSpec
+  rawValueSpec
+  instanceSpec
+
+-- BIP-340 vector 0: secret key 3 signing 32 zero bytes with 32 zero bytes of
+-- auxiliary randomness.
+bip340Key0 :: SecKey
+bip340Key0 = "0000000000000000000000000000000000000000000000000000000000000003"
+
+bip340Pub0, bip340Sig0 :: String
+bip340Pub0 = "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"
+bip340Sig0 =
+  "e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca8215\
+  \25f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0"
+
+-- A BIP-340 test vector from
+-- https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv.
+-- Vectors 15 to 18 sign messages that are not 32 bytes long, which 'Msg'
+-- does not hold, so they are left out.
+data BIP340Vector = BIP340Vector
+  { index :: Int,
+    comment :: String,
+    secretKey :: Maybe String,
+    publicKey :: String,
+    auxRand :: Maybe String,
+    message :: String,
+    signature :: String,
+    result :: Bool
+  }
+
+bip340Vectors :: [BIP340Vector]
+bip340Vectors =
+  [ BIP340Vector
+      { index = 0,
+        comment = "",
+        secretKey = Just "0000000000000000000000000000000000000000000000000000000000000003",
+        publicKey = "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9",
+        auxRand = Just "0000000000000000000000000000000000000000000000000000000000000000",
+        message = "0000000000000000000000000000000000000000000000000000000000000000",
+        signature = "e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0",
+        result = True
+      },
+    BIP340Vector
+      { index = 1,
+        comment = "",
+        secretKey = Just "b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef",
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Just "0000000000000000000000000000000000000000000000000000000000000001",
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "6896bd60eeae296db48a229ff71dfe071bde413e6d43f917dc8dcf8c78de33418906d11ac976abccb20b091292bff4ea897efcb639ea871cfa95f6de339e4b0a",
+        result = True
+      },
+    BIP340Vector
+      { index = 2,
+        comment = "",
+        secretKey = Just "c90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b14e5c9",
+        publicKey = "dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8",
+        auxRand = Just "c87aa53824b4d7ae2eb035a2b5bbbccc080e76cdc6d1692c4b0b62d798e6d906",
+        message = "7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c",
+        signature = "5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7",
+        result = True
+      },
+    BIP340Vector
+      { index = 3,
+        comment = "test fails if msg is reduced modulo p or n",
+        secretKey = Just "0b432b2677937381aef05bb02a66ecd012773062cf3fa2549e44f58ed2401710",
+        publicKey = "25d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517",
+        auxRand = Just "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+        message = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+        signature = "7eb0509757e246f19449885651611cb965ecc1a187dd51b64fda1edc9637d5ec97582b9cb13db3933705b32ba982af5af25fd78881ebb32771fc5922efc66ea3",
+        result = True
+      },
+    BIP340Vector
+      { index = 4,
+        comment = "",
+        secretKey = Nothing,
+        publicKey = "d69c3509bb99e412e68b0fe8544e72837dfa30746d8be2aa65975f29d22dc7b9",
+        auxRand = Nothing,
+        message = "4df3c3f68fcc83b27e9d42c90431a72499f17875c81a599b566c9889b9696703",
+        signature = "00000000000000000000003b78ce563f89a0ed9414f5aa28ad0d96d6795f9c6376afb1548af603b3eb45c9f8207dee1060cb71c04e80f593060b07d28308d7f4",
+        result = True
+      },
+    BIP340Vector
+      { index = 5,
+        comment = "public key not on the curve",
+        secretKey = Nothing,
+        publicKey = "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e17776969e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b",
+        result = False
+      },
+    BIP340Vector
+      { index = 6,
+        comment = "has_even_y(R) is false",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a14602975563cc27944640ac607cd107ae10923d9ef7a73c643e166be5ebeafa34b1ac553e2",
+        result = False
+      },
+    BIP340Vector
+      { index = 7,
+        comment = "negated message",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "1fa62e331edbc21c394792d2ab1100a7b432b013df3f6ff4f99fcb33e0e1515f28890b3edb6e7189b630448b515ce4f8622a954cfe545735aaea5134fccdb2bd",
+        result = False
+      },
+    BIP340Vector
+      { index = 8,
+        comment = "negated s value",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769961764b3aa9b2ffcb6ef947b6887a226e8d7c93e00c5ed0c1834ff0d0c2e6da6",
+        result = False
+      },
+    BIP340Vector
+      { index = 9,
+        comment = "sG - eP is infinite",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "0000000000000000000000000000000000000000000000000000000000000000123dda8328af9c23a94c1feecfd123ba4fb73476f0d594dcb65c6425bd186051",
+        result = False
+      },
+    BIP340Vector
+      { index = 10,
+        comment = "sG - eP is infinite",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "00000000000000000000000000000000000000000000000000000000000000017615fbaf5ae28864013c099742deadb4dba87f11ac6754f93780d5a1837cf197",
+        result = False
+      },
+    BIP340Vector
+      { index = 11,
+        comment = "sig[0:32] is not an X coordinate on the curve",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "4a298dacae57395a15d0795ddbfd1dcb564da82b0f269bc70a74f8220429ba1d69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b",
+        result = False
+      },
+    BIP340Vector
+      { index = 12,
+        comment = "sig[0:32] is equal to field size",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b",
+        result = False
+      },
+    BIP340Vector
+      { index = 13,
+        comment = "sig[32:64] is equal to curve order",
+        secretKey = Nothing,
+        publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
+        result = False
+      },
+    BIP340Vector
+      { index = 14,
+        comment = "public key is not a valid X coordinate because it exceeds the field size",
+        secretKey = Nothing,
+        publicKey = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc30",
+        auxRand = Nothing,
+        message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89",
+        signature = "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e17776969e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b",
+        result = False
+      }
+  ]
+
+-- A BIP-341 key path spending vector from
+-- https://github.com/bitcoin/bips/blob/master/bip-0341/wallet-test-vectors.json:
+-- the internal secret key, its x-only public key, the tweak, the tweaked
+-- secret key, the output key (from the spent scriptPubKey), the signature
+-- hash, and the signature without its hash type byte. The signatures were
+-- made without auxiliary randomness.
+data BIP341Vector = BIP341Vector
+  { internalKey :: String,
+    internalPub :: String,
+    tapTweak :: String,
+    tweakedKey :: String,
+    outputKey :: String,
+    sigHash :: String,
+    keyPathSig :: String
+  }
+
+bip341Vectors :: [BIP341Vector]
+bip341Vectors =
+  [ BIP341Vector
+      { internalKey = "6b973d88838f27366ed61c9ad6367663045cb456e28335c109e30717ae0c6baa",
+        internalPub = "d6889cb081036e0faefa3a35157ad71086b123b2b144b649798b494c300a961d",
+        tapTweak = "b86e7be8f39bab32a6f2c0443abbc210f0edac0e2c53d501b36b64437d9c6c70",
+        tweakedKey = "2405b971772ad26915c8dcdf10f238753a9b837e5f8e6a86fd7c0cce5b7296d9",
+        outputKey = "53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343",
+        sigHash = "2514a6272f85cfa0f45eb907fcb0d121b808ed37c6ea160a5a9046ed5526d555",
+        keyPathSig = "ed7c1647cb97379e76892be0cacff57ec4a7102aa24296ca39af7541246d8ff14d38958d4cc1e2e478e4d4a764bbfd835b16d4e314b72937b29833060b87276c"
+      },
+    BIP341Vector
+      { internalKey = "1e4da49f6aaf4e5cd175fe08a32bb5cb4863d963921255f33d3bc31e1343907f",
+        internalPub = "187791b6f712a8ea41c8ecdd0ee77fab3e85263b37e1ec18a3651926b3a6cf27",
+        tapTweak = "cbd8679ba636c1110ea247542cfbd964131a6be84f873f7f3b62a777528ed001",
+        tweakedKey = "ea260c3b10e60f6de018455cd0278f2f5b7e454be1999572789e6a9565d26080",
+        outputKey = "147c9c57132f6e7ecddba9800bb0c4449251c92a1e60371ee77557b6620f3ea3",
+        sigHash = "325a644af47e8a5a2591cda0ab0723978537318f10e6a63d4eed783b96a71a4d",
+        keyPathSig = "052aedffc554b41f52b521071793a6b88d6dbca9dba94cf34c83696de0c1ec35ca9c5ed4ab28059bd606a4f3a657eec0bb96661d42921b5f50a95ad33675b54f"
+      },
+    BIP341Vector
+      { internalKey = "d3c7af07da2d54f7a7735d3d0fc4f0a73164db638b2f2f7c43f711f6d4aa7e64",
+        internalPub = "93478e9488f956df2396be2ce6c5cced75f900dfa18e7dabd2428aae78451820",
+        tapTweak = "6af9e28dbf9d6aaf027696e2598a5b3d056f5fd2355a7fd5a37a0e5008132d30",
+        tweakedKey = "97323385e57015b75b0339a549c56a948eb961555973f0951f555ae6039ef00d",
+        outputKey = "e4d810fd50586274face62b8a807eb9719cef49c04177cc6b76a9a4251d5450e",
+        sigHash = "bf013ea93474aa67815b1b6cc441d23b64fa310911d991e713cd34c7f5d46669",
+        keyPathSig = "ff45f742a876139946a149ab4d9185574b98dc919d2eb6754f8abaa59d18b025637a3aa043b91817739554f4ed2026cf8022dbd83e351ce1fabc272841d2510a"
+      },
+    BIP341Vector
+      { internalKey = "f36bb07a11e469ce941d16b63b11b9b9120a84d9d87cff2c84a8d4affb438f4e",
+        internalPub = "e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6f",
+        tapTweak = "b57bfa183d28eeb6ad688ddaabb265b4a41fbf68e5fed2c72c74de70d5a786f4",
+        tweakedKey = "a8e7aa924f0d58854185a490e6c41f6efb7b675c0f3331b7f14b549400b4d501",
+        outputKey = "91b64d5324723a985170e4dc5a0f84c041804f2cd12660fa5dec09fc21783605",
+        sigHash = "4f900a0bae3f1446fd48490c2958b5a023228f01661cda3496a11da502a7f7ef",
+        keyPathSig = "b4010dd48a617db09926f729e79c33ae0b4e94b79f04a1ae93ede6315eb3669de185a17d2b0ac9ee09fd4c64b678a0b61a0a86fa888a273c8511be83bfd6810f"
+      },
+    BIP341Vector
+      { internalKey = "415cfe9c15d9cea27d8104d5517c06e9de48e2f986b695e4f5ffebf230e725d8",
+        internalPub = "55adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312d",
+        tapTweak = "6579138e7976dc13b6a92f7bfd5a2fc7684f5ea42419d43368301470f3b74ed9",
+        tweakedKey = "241c14f2639d0d7139282aa6abde28dd8a067baa9d633e4e7230287ec2d02901",
+        outputKey = "75169f4001aa68f15bbed28b218df1d0a62cbbcf1188c6665110c293c907b831",
+        sigHash = "15f25c298eb5cdc7eb1d638dd2d45c97c4c59dcaec6679cfc16ad84f30876b85",
+        keyPathSig = "a3785919a2ce3c4ce26f298c3d51619bc474ae24014bcdd31328cd8cfbab2eff3395fa0a16fe5f486d12f22a9cedded5ae74feb4bbe5351346508c5405bcfee0"
+      },
+    BIP341Vector
+      { internalKey = "c7b0e81f0a9a0b0499e112279d718cca98e79a12e2f137c72ae5b213aad0d103",
+        internalPub = "ee4fe085983462a184015d1f782d6a5f8b9c2b60130aff050ce221ecf3786592",
+        tapTweak = "9e0517edc8259bb3359255400b23ca9507f2a91cd1e4250ba068b4eafceba4a9",
+        tweakedKey = "65b6000cd2bfa6b7cf736767a8955760e62b6649058cbc970b7c0871d786346b",
+        outputKey = "712447206d7a5238acc7ff53fbe94a3b64539ad291c7cdbc490b7577e4b17df5",
+        sigHash = "cd292de50313804dabe4685e83f923d2969577191a3e1d2882220dca88cbeb10",
+        keyPathSig = "ea0c6ba90763c2d3a296ad82ba45881abb4f426b3f87af162dd24d5109edc1cdd11915095ba47c3a9963dc1e6c432939872bc49212fe34c632cd3ab9fed429c4"
+      },
+    BIP341Vector
+      { internalKey = "77863416be0d0665e517e1c375fd6f75839544eca553675ef7fdf4949518ebaa",
+        internalPub = "f9f400803e683727b14f463836e1e78e1c64417638aa066919291a225f0e8dd8",
+        tapTweak = "639f0281b7ac49e742cd25b7f188657626da1ad169209078e2761cefd91fd65e",
+        tweakedKey = "ec18ce6af99f43815db543f47b8af5ff5df3b2cb7315c955aa4a86e8143d2bf5",
+        outputKey = "77e30a5522dd9f894c3f8b8bd4c4b2cf82ca7da8a3ea6a239655c39c050ab220",
+        sigHash = "cccb739eca6c13a8a89e6e5cd317ffe55669bbda23f2fd37b0f18755e008edd2",
+        keyPathSig = "bbc9584a11074e83bc8c6759ec55401f0ae7b03ef290c3139814f545b58a9f8127258000874f44bc46db7646322107d4d86aec8e73b8719a61fff761d75b5dd9"
+      }
+  ]
+
+-- * Secret keys
+
+secretKeySpec :: Spec
+secretKeySpec = describe "secret keys" $ 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
+    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
+    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" $ do
+    bytesToHex (exportPubKey True (derivePubKey keyOne))
+      `shouldBe` genCompressed
+    bytesToHex (exportPubKey False (derivePubKey keyOne))
+      `shouldBe` genUncompressed
+  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 True (derivePubKey (fromString orderMinusOne)))
+      `shouldBe` "0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
+  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
+    (readMaybe (quoted ("zz" ++ drop 2 one)) :: Maybe SecKey) `shouldBe` Nothing
+    evaluate (fromString order :: SecKey) `shouldThrow` anyErrorCall
+
+-- * Public keys
+
+publicKeySpec :: Spec
+publicKeySpec = describe "public keys" $ do
+  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 (hexToBytes ("05" ++ drop 2 genCompressed)) `shouldBe` Nothing
+    -- x only, no prefix
+    importPubKey (hexToBytes (drop 2 genCompressed)) `shouldBe` Nothing
+    -- x and y without a prefix
+    importPubKey (hexToBytes (drop 2 genUncompressed)) `shouldBe` Nothing
+    -- uncompressed prefix on a compressed length
+    importPubKey (hexToBytes ("04" ++ drop 2 genCompressed)) `shouldBe` Nothing
+    -- compressed prefix on an uncompressed length
+    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 (hexToBytes ("02" ++ take 62 zero ++ "05")) `shouldBe` Nothing
+    -- (1, 1) is not on the curve: 1 /= 1 + 7.
+    importPubKey (hexToBytes ("04" ++ take 62 zero ++ "01" ++ take 62 zero ++ "01"))
+      `shouldBe` Nothing
+  it "exports and imports back the same key" $
+    property $ \(k :: SecKey, compress :: Bool) ->
+      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) ks
+      and <$> mapM P.get results
+  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" $
+    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" $
+    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 (k, compress) =
+      let p = derivePubKey k
+       in importPubKey (exportPubKey compress p) == Just p
+
+-- * Messages
+
+messageSpec :: Spec
+messageSpec = describe "messages" $ 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" $
+    property (showRead :: Msg -> Bool)
+  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
+    (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').
+    (readMaybe (quoted (take 63 allOnes ++ "\xFF41")) :: Maybe Msg) `shouldBe` Nothing
+    evaluate (fromString (take 63 allOnes ++ "\xFF41") :: Msg) `shouldThrow` anyErrorCall
+  where
+    toUpperHex c = if c >= 'a' && c <= 'f' then toEnum (fromEnum c - 32) else c
+
+-- * Signing
+
+signingSpec :: Spec
+signingSpec = describe "signing" $ do
+  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" $ 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) xs
+      and <$> mapM P.get results
+  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" $ 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 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 k m
+         in isLowR s ==> signMsgLowR k m == s
+  where
+    signsAndVerifies (m, k) =
+      verifySig (derivePubKey k) (signMsg k m) m
+
+-- * Verification
+
+verificationSpec :: Spec
+verificationSpec = describe "verification" $ do
+  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" $
+    verifySig
+      (fromString histPub)
+      ( fromJust . importSig . hexToBytes $
+          "3045022100f502bfa07af43e7ef265618b0d929a7619ee01d6150e37eb6eaaf2c8bd37fb22\
+          \02206f0415ab0e9a977afd78b2c26ef39b3952096d319fd4b101c768ad6c132e3045"
+      )
+      "f5cbe7d88182a4b8e400f96b06128921864a18187d114c8ae8541b566c8ace00"
+      `shouldBe` True
+  it "rejects a signature from another key" $
+    property $ \(m :: Msg, k :: SecKey, k' :: SecKey) ->
+      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 (derivePubKey k) (signMsg k m) m')
+  it "rejects a signature with one bit flipped" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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 (fromJust (compactSig flipped)) of
+            Nothing -> False
+            Just s -> not (verifySig (derivePubKey k) s m)
+  describe "lower-S form" $ do
+    it "rejects the high-S form of a valid signature" $ do
+      let high = fromString (satoshiR ++ satoshiHighS) :: Sig
+      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 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 k m in normalizeSig s == s
+    it "is idempotent" $ do
+      let high = fromString (satoshiR ++ satoshiHighS) :: Sig
+      normalizeSig (normalizeSig high) `shouldBe` normalizeSig high
+
+-- * DER
+
+derSpec :: Spec
+derSpec = describe "DER signatures" $ do
+  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 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) xs
+      and <$> mapM P.get results
+  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 (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 (hexToBytes ("3046022100" ++ order ++ "022100" ++ satoshiR)) `shouldBe` Nothing
+    -- r = 0, s = r of the vector. 3 + 35 = 38 = 0x26 bytes.
+    importSig (hexToBytes ("3026020100022100" ++ satoshiR)) `shouldBe` Nothing
+    -- r of the vector, s = 0.
+    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 (hexToBytes ("308145" ++ drop 4 satoshiDer)) `shouldBe` Nothing
+    -- A byte after the sequence.
+    importSig (hexToBytes (satoshiDer ++ "00")) `shouldBe` Nothing
+    -- A byte missing at the end.
+    importSig (hexToBytes (take (length satoshiDer - 2) satoshiDer)) `shouldBe` Nothing
+    -- Wrong sequence tag.
+    importSig (hexToBytes ("31" ++ drop 2 satoshiDer)) `shouldBe` Nothing
+    -- Negative r: the zero pad is removed although the first byte is 0x93.
+    importSig (hexToBytes ("30440220" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing
+    -- Two zero pad bytes on r.
+    importSig (hexToBytes ("3046022200" ++ "00" ++ satoshiR ++ "0220" ++ satoshiS)) `shouldBe` Nothing
+  where
+    roundTrip (m, k) = let s = signMsg k m in importSig (exportSig s) == Just s
+
+-- * Compact signatures
+
+compactSpec :: Spec
+compactSpec = describe "compact signatures" $ do
+  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 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
+    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" $
+      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" $
+      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
+      evaluate (fromString satoshiDer :: Sig) `shouldThrow` anyErrorCall
+
+-- * Tweaks
+
+tweakSpec :: Spec
+tweakSpec = describe "tweaks" $ 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" $
+    property (showRead :: Tweak -> Bool)
+  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" $
+    -- (key + tweak) mod n
+    tweakAddSecKey histKey histTweak
+      `shouldBe` Just "ec1e3ce1cefa18a671d51125e2b249688d934b0e28f5d1665384d9b02f929059"
+  it "multiplies a secret key" $
+    -- (key * tweak) mod n
+    tweakMulSecKey histKey histTweak
+      `shouldBe` Just "a96f5962493acb179f60a86a9785fc7a30e0c39b64c09d24fe064d9aef15e4c0"
+  it "adds to a public key" $
+    -- P + tweak * G
+    fmap (bytesToHex . exportPubKey False) (tweakAddPubKey (fromString histPub) histTweak)
+      `shouldBe` Just
+        "04441c3982b97576646e0df0c96736063df6b42f2ee566d13b9f6424302d1379e5\
+        \18fdc87a14c5435bff7a5db4552042cb4120c6b86a4bbd3d0643f3c14ad01368"
+  it "multiplies a public key" $
+    -- tweak * P
+    fmap (bytesToHex . exportPubKey False) (tweakMulPubKey (fromString histPub) histTweak)
+      `shouldBe` Just
+        "04f379dc99cdf5c83e433defa267fbb3377d61d6b779c06a0e4ce29ae3ff5353b1\
+        \2ae49c9d07e7368f2ba5a446c203255ce912322991a2d6a9d5d5761c61ed1845"
+  it "tweaks the public key like the secret key" $
+    property $ \(k :: SecKey, t :: Tweak) ->
+      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 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 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 histTweak
+      `shouldBe` Just "0a3418277e7d5b471bff0694f9ed76dd3464c4ce323753b0d77e433663ab7341"
+  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 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 k
+          pBytes = BS.copy p.get
+          tBytes = BS.copy t.get
+       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 :: Spec
+combineSpec = describe "combining public keys" $ do
+  it "adds three historical keys" $
+    fmap
+      (bytesToHex . exportPubKey False)
+      ( combinePubKeys
+          [ fromString histPub,
+            "0487d82042d93447008dfe2af762068a1e53ff394a5bf8f68a045fa642b99ea5d1\
+            \53f577dd2dba6c7ae4cfd7b6622409d7edd2d76dd13a8092cd3af97b77bd2c77",
+            "049b101edcbe1ee37ff6b2318526a425b629e823d7d8d9154417880595a28000ee\
+            \3febd908754b8ce4e491aa6fe488b41fb5d4bb3788e33c9ff95a7a9229166d59"
+          ]
+      )
+      `shouldBe` Just
+        "043d9a7ec70011efc23c33a7e62d2ea73cca87797e3b659d93bea6aa871aebde56\
+        \c3bc6134ca82e324b0ab9c0e601a6d2933afe7fb5d9f3aae900f5c5dc6e362c8"
+  it "adds G to itself" $
+    -- 2 * G
+    fmap (bytesToHex . exportPubKey True) (combinePubKeys [fromString genCompressed, fromString genCompressed])
+      `shouldBe` Just "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"
+  it "adds like the secret keys add" $
+    property $ \(k1 :: SecKey, k2 :: SecKey) ->
+      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 k
+          minusP = fromJust (tweakMulPubKey p (fromString orderMinusOne))
+       in isNothing (combinePubKeys [p, minusP])
+
+-- * Schnorr signatures
+
+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" $
+    signSchnorr bip340Key0 (fromString zero) `shouldBe` fromString bip340Sig0
+  it "signs without randomness as with 32 zero bytes" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      signSchnorrWithAux k m (BS.replicate 32 0) == Just (signSchnorr k m)
+  it "verifies with the matching public key" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      verifySchnorr (derivePubKey k) (signSchnorr k m) m
+  it "verifies with the negation of the public key" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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 k m
+      return (verifySchnorr (derivePubKey k) s m)
+  it "changes with the auxiliary randomness" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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 (derivePubKey k') (signSchnorr k m) m)
+  it "rejects a signature over another message" $
+    property $ \(m :: Msg, m' :: Msg, k :: SecKey) ->
+      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" $
+    show (fromString bip340Sig0 :: SchnorrSig) `shouldBe` quoted bip340Sig0
+  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 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
+
+-- For a vector with a secret key: the key gives the public key, and signing
+-- 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 -> 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 (derivePubKey k)) `shouldBe` v.publicKey
+      signSchnorrWithAux k m (hexToBytes aux) `shouldBe` Just s
+    _ -> return ()
+  maybe False (\p -> verifySchnorr p s m) (importXOnlyPubKey (hexToBytes v.publicKey))
+    `shouldBe` v.result
+
+-- * X-only public keys
+
+xOnlySpec :: Spec
+xOnlySpec = describe "x-only public keys" $ do
+  it "exports the x coordinate of G" $
+    -- the compressed encoding of G without its 02 prefix
+    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 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 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" $
+    property $ \(k :: SecKey) ->
+      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 (hexToBytes "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34")
+      `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 :: 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" $
+    property $ \(k :: SecKey, t :: Tweak) ->
+      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 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 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 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 (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 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 (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 -> 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 (derivePubKey k)) `shouldBe` v.internalPub
+  tweakAddXOnlySecKey k t `shouldBe` Just k'
+  fmap (bytesToHex . exportXOnlyPubKey) (tweakAddXOnlyPubKey (derivePubKey k) t)
+    `shouldBe` Just v.outputKey
+  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 :: 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" $
+      property $ \(m :: Msg, k :: SecKey) ->
+        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" $ 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 :: Spec
+instanceSpec = describe "derived instances" $ do
+  it "equal values hash equally, whichever way they were built" $
+    property $ \(m :: Msg, k :: SecKey) ->
+      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" $ do
+    let p = derivePubKey keyOne
+        s = signMsg keyOne satoshiMsg
+    ((p, s, keyOne, satoshiMsg, histTweak, exportCompactSig s, signSchnorr keyOne satoshiMsg) `deepseq` ())
+      `shouldBe` ()
diff --git a/test/data/ellswift_decode_test_vectors.csv b/test/data/ellswift_decode_test_vectors.csv
new file mode 100644
--- /dev/null
+++ b/test/data/ellswift_decode_test_vectors.csv
@@ -0,0 +1,77 @@
+ellswift,x,comment
+00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,edd1fd3e327ce90cc7a3542614289aee9682003e9cf7dcc9cf2ca9743be5aa0c,u%p=0;t%p=0;valid_x(x2)
+000000000000000000000000000000000000000000000000000000000000000001d3475bf7655b0fb2d852921035b2ef607f49069b97454e6795251062741771,b5da00b73cd6560520e7c364086e7cd23a34bf60d0e707be9fc34d4cd5fdfa2c,u%p=0;valid_x(x1)
+000000000000000000000000000000000000000000000000000000000000000082277c4a71f9d22e66ece523f8fa08741a7c0912c66a69ce68514bfd3515b49f,f482f2e241753ad0fb89150d8491dc1e34ff0b8acfbb442cfe999e2e5e6fd1d2,u%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+00000000000000000000000000000000000000000000000000000000000000008421cc930e77c9f514b6915c3dbe2a94c6d8f690b5b739864ba6789fb8a55dd0,9f59c40275f5085a006f05dae77eb98c6fd0db1ab4a72ac47eae90a4fc9e57e0,u%p=0;valid_x(x2)
+0000000000000000000000000000000000000000000000000000000000000000bde70df51939b94c9c24979fa7dd04ebd9b3572da7802290438af2a681895441,aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9fffffd6b,u%p=0;(u'^3-t'^2+7)%p=0;valid_x(x3)
+0000000000000000000000000000000000000000000000000000000000000000d19c182d2759cd99824228d94799f8c6557c38a1c0d6779b9d4b729c6f1ccc42,70720db7e238d04121f5b1afd8cc5ad9d18944c6bdc94881f502b7a3af3aecff,u%p=0;valid_x(x3)
+0000000000000000000000000000000000000000000000000000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,edd1fd3e327ce90cc7a3542614289aee9682003e9cf7dcc9cf2ca9743be5aa0c,u%p=0;t%p=0;valid_x(x2);t>=p
+0000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff2664bbd5,50873db31badcc71890e4f67753a65757f97aaa7dd5f1e82b753ace32219064b,u%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+0000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff7028de7d,1eea9cc59cfcf2fa151ac6c274eea4110feb4f7b68c5965732e9992e976ef68e,u%p=0;valid_x(x2);t>=p
+0000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffcbcfb7e7,12303941aedc208880735b1f1795c8e55be520ea93e103357b5d2adb7ed59b8e,u%p=0;valid_x(x1);t>=p
+0000000000000000000000000000000000000000000000000000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff3113ad9,7eed6b70e7b0767c7d7feac04e57aa2a12fef5e0f48f878fcbb88b3b6b5e0783,u%p=0;valid_x(x3);t>=p
+0a2d2ba93507f1df233770c2a797962cc61f6d15da14ecd47d8d27ae1cd5f8530000000000000000000000000000000000000000000000000000000000000000,532167c11200b08c0e84a354e74dcc40f8b25f4fe686e30869526366278a0688,t%p=0;(u'^3+t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+0a2d2ba93507f1df233770c2a797962cc61f6d15da14ecd47d8d27ae1cd5f853fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,532167c11200b08c0e84a354e74dcc40f8b25f4fe686e30869526366278a0688,t%p=0;(u'^3+t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+0ffde9ca81d751e9cdaffc1a50779245320b28996dbaf32f822f20117c22fbd6c74d99efceaa550f1ad1c0f43f46e7ff1ee3bd0162b7bf55f2965da9c3450646,74e880b3ffd18fe3cddf7902522551ddf97fa4a35a3cfda8197f947081a57b8f,valid_x(x3)
+0ffde9ca81d751e9cdaffc1a50779245320b28996dbaf32f822f20117c22fbd6ffffffffffffffffffffffffffffffffffffffffffffffffffffffff156ca896,377b643fce2271f64e5c8101566107c1be4980745091783804f654781ac9217c,valid_x(x2);t>=p
+123658444f32be8f02ea2034afa7ef4bbe8adc918ceb49b12773b625f490b368ffffffffffffffffffffffffffffffffffffffffffffffffffffffff8dc5fe11,ed16d65cf3a9538fcb2c139f1ecbc143ee14827120cbc2659e667256800b8142,(u'^3-t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+146f92464d15d36e35382bd3ca5b0f976c95cb08acdcf2d5b3570617990839d7ffffffffffffffffffffffffffffffffffffffffffffffffffffffff3145e93b,0d5cd840427f941f65193079ab8e2e83024ef2ee7ca558d88879ffd879fb6657,(u'^3+t'^2+7)%p=0;valid_x(x3);t>=p
+15fdf5cf09c90759add2272d574d2bb5fe1429f9f3c14c65e3194bf61b82aa73ffffffffffffffffffffffffffffffffffffffffffffffffffffffff04cfd906,16d0e43946aec93f62d57eb8cde68951af136cf4b307938dd1447411e07bffe1,(u'^3+t'^2+7)%p=0;valid_x(x2);t>=p
+1f67edf779a8a649d6def60035f2fa22d022dd359079a1a144073d84f19b92d50000000000000000000000000000000000000000000000000000000000000000,025661f9aba9d15c3118456bbe980e3e1b8ba2e047c737a4eb48a040bb566f6c,t%p=0;valid_x(x2)
+1f67edf779a8a649d6def60035f2fa22d022dd359079a1a144073d84f19b92d5fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,025661f9aba9d15c3118456bbe980e3e1b8ba2e047c737a4eb48a040bb566f6c,t%p=0;valid_x(x2);t>=p
+1fe1e5ef3fceb5c135ab7741333ce5a6e80d68167653f6b2b24bcbcfaaaff507fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,98bec3b2a351fa96cfd191c1778351931b9e9ba9ad1149f6d9eadca80981b801,t%p=0;(u'^3-t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+4056a34a210eec7892e8820675c860099f857b26aad85470ee6d3cf1304a9dcf375e70374271f20b13c9986ed7d3c17799698cfc435dbed3a9f34b38c823c2b4,868aac2003b29dbcad1a3e803855e078a89d16543ac64392d122417298cec76e,(u'^3-t'^2+7)%p=0;valid_x(x3)
+4197ec3723c654cfdd32ab075506648b2ff5070362d01a4fff14b336b78f963fffffffffffffffffffffffffffffffffffffffffffffffffffffffffb3ab1e95,ba5a6314502a8952b8f456e085928105f665377a8ce27726a5b0eb7ec1ac0286,(u'^3+t'^2+7)%p=0;valid_x(x1);t>=p
+47eb3e208fedcdf8234c9421e9cd9a7ae873bfbdbc393723d1ba1e1e6a8e6b24ffffffffffffffffffffffffffffffffffffffffffffffffffffffff7cd12cb1,d192d52007e541c9807006ed0468df77fd214af0a795fe119359666fdcf08f7c,(u'^3+t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+5eb9696a2336fe2c3c666b02c755db4c0cfd62825c7b589a7b7bb442e141c1d693413f0052d49e64abec6d5831d66c43612830a17df1fe4383db896468100221,ef6e1da6d6c7627e80f7a7234cb08a022c1ee1cf29e4d0f9642ae924cef9eb38,(u'^3+t'^2+7)%p=0;valid_x(x1)
+7bf96b7b6da15d3476a2b195934b690a3a3de3e8ab8474856863b0de3af90b0e0000000000000000000000000000000000000000000000000000000000000000,50851dfc9f418c314a437295b24feeea27af3d0cd2308348fda6e21c463e46ff,t%p=0;valid_x(x1)
+7bf96b7b6da15d3476a2b195934b690a3a3de3e8ab8474856863b0de3af90b0efffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,50851dfc9f418c314a437295b24feeea27af3d0cd2308348fda6e21c463e46ff,t%p=0;valid_x(x1);t>=p
+851b1ca94549371c4f1f7187321d39bf51c6b7fb61f7cbf027c9da62021b7a65fc54c96837fb22b362eda63ec52ec83d81bedd160c11b22d965d9f4a6d64d251,3e731051e12d33237eb324f2aa5b16bb868eb49a1aa1fadc19b6e8761b5a5f7b,(u'^3+t'^2+7)%p=0;valid_x(x2)
+943c2f775108b737fe65a9531e19f2fc2a197f5603e3a2881d1d83e4008f91250000000000000000000000000000000000000000000000000000000000000000,311c61f0ab2f32b7b1f0223fa72f0a78752b8146e46107f8876dd9c4f92b2942,t%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+943c2f775108b737fe65a9531e19f2fc2a197f5603e3a2881d1d83e4008f9125fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,311c61f0ab2f32b7b1f0223fa72f0a78752b8146e46107f8876dd9c4f92b2942,t%p=0;valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+a0f18492183e61e8063e573606591421b06bc3513631578a73a39c1c3306239f2f32904f0d2a33ecca8a5451705bb537d3bf44e071226025cdbfd249fe0f7ad6,97a09cf1a2eae7c494df3c6f8a9445bfb8c09d60832f9b0b9d5eabe25fbd14b9,valid_x(x1)
+a1ed0a0bd79d8a23cfe4ec5fef5ba5cccfd844e4ff5cb4b0f2e71627341f1c5b17c499249e0ac08d5d11ea1c2c8ca7001616559a7994eadec9ca10fb4b8516dc,65a89640744192cdac64b2d21ddf989cdac7500725b645bef8e2200ae39691f2,valid_x(x2)
+ba94594a432721aa3580b84c161d0d134bc354b690404d7cd4ec57c16d3fbe98ffffffffffffffffffffffffffffffffffffffffffffffffffffffffea507dd7,5e0d76564aae92cb347e01a62afd389a9aa401c76c8dd227543dc9cd0efe685a,valid_x(x1);t>=p
+bcaf7219f2f6fbf55fe5e062dce0e48c18f68103f10b8198e974c184750e1be3932016cbf69c4471bd1f656c6a107f1973de4af7086db897277060e25677f19a,2d97f96cac882dfe73dc44db6ce0f1d31d6241358dd5d74eb3d3b50003d24c2b,valid_x(x3);valid_x(x2);valid_x(x1)
+bcaf7219f2f6fbf55fe5e062dce0e48c18f68103f10b8198e974c184750e1be3ffffffffffffffffffffffffffffffffffffffffffffffffffffffff6507d09a,e7008afe6e8cbd5055df120bd748757c686dadb41cce75e4addcc5e02ec02b44,valid_x(x3);valid_x(x2);valid_x(x1);t>=p
+c5981bae27fd84401c72a155e5707fbb811b2b620645d1028ea270cbe0ee225d4b62aa4dca6506c1acdbecc0552569b4b21436a5692e25d90d3bc2eb7ce24078,948b40e7181713bc018ec1702d3d054d15746c59a7020730dd13ecf985a010d7,(u'^3+t'^2+7)%p=0;valid_x(x3)
+c894ce48bfec433014b931a6ad4226d7dbd8eaa7b6e3faa8d0ef94052bcf8cff336eeb3919e2b4efb746c7f71bbca7e9383230fbbc48ffafe77e8bcc69542471,f1c91acdc2525330f9b53158434a4d43a1c547cff29f15506f5da4eb4fe8fa5a,(u'^3-t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+cbb0deab125754f1fdb2038b0434ed9cb3fb53ab735391129994a535d925f6730000000000000000000000000000000000000000000000000000000000000000,872d81ed8831d9998b67cb7105243edbf86c10edfebb786c110b02d07b2e67cd,t%p=0;(u'^3-t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+d917b786dac35670c330c9c5ae5971dfb495c8ae523ed97ee2420117b171f41effffffffffffffffffffffffffffffffffffffffffffffffffffffff2001f6f6,e45b71e110b831f2bdad8651994526e58393fde4328b1ec04d59897142584691,valid_x(x3);t>=p
+e28bd8f5929b467eb70e04332374ffb7e7180218ad16eaa46b7161aa679eb4260000000000000000000000000000000000000000000000000000000000000000,66b8c980a75c72e598d383a35a62879f844242ad1e73ff12edaa59f4e58632b5,t%p=0;valid_x(x3)
+e28bd8f5929b467eb70e04332374ffb7e7180218ad16eaa46b7161aa679eb426fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,66b8c980a75c72e598d383a35a62879f844242ad1e73ff12edaa59f4e58632b5,t%p=0;valid_x(x3);t>=p
+e7ee5814c1706bf8a89396a9b032bc014c2cac9c121127dbf6c99278f8bb53d1dfd04dbcda8e352466b6fcd5f2dea3e17d5e133115886eda20db8a12b54de71b,e842c6e3529b234270a5e97744edc34a04d7ba94e44b6d2523c9cf0195730a50,(u'^3+t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1)
+f292e46825f9225ad23dc057c1d91c4f57fcb1386f29ef10481cb1d22518593fffffffffffffffffffffffffffffffffffffffffffffffffffffffff7011c989,3cea2c53b8b0170166ac7da67194694adacc84d56389225e330134dab85a4d55,(u'^3-t'^2+7)%p=0;valid_x(x3);t>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f0000000000000000000000000000000000000000000000000000000000000000,edd1fd3e327ce90cc7a3542614289aee9682003e9cf7dcc9cf2ca9743be5aa0c,u%p=0;t%p=0;valid_x(x2);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f01d3475bf7655b0fb2d852921035b2ef607f49069b97454e6795251062741771,b5da00b73cd6560520e7c364086e7cd23a34bf60d0e707be9fc34d4cd5fdfa2c,u%p=0;valid_x(x1);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f4218f20ae6c646b363db68605822fb14264ca8d2587fdd6fbc750d587e76a7ee,aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9fffffd6b,u%p=0;(u'^3-t'^2+7)%p=0;valid_x(x3);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f82277c4a71f9d22e66ece523f8fa08741a7c0912c66a69ce68514bfd3515b49f,f482f2e241753ad0fb89150d8491dc1e34ff0b8acfbb442cfe999e2e5e6fd1d2,u%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f8421cc930e77c9f514b6915c3dbe2a94c6d8f690b5b739864ba6789fb8a55dd0,9f59c40275f5085a006f05dae77eb98c6fd0db1ab4a72ac47eae90a4fc9e57e0,u%p=0;valid_x(x2);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fd19c182d2759cd99824228d94799f8c6557c38a1c0d6779b9d4b729c6f1ccc42,70720db7e238d04121f5b1afd8cc5ad9d18944c6bdc94881f502b7a3af3aecff,u%p=0;valid_x(x3);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,edd1fd3e327ce90cc7a3542614289aee9682003e9cf7dcc9cf2ca9743be5aa0c,u%p=0;t%p=0;valid_x(x2);u>=p;t>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fffffffffffffffffffffffffffffffffffffffffffffffffffffffff2664bbd5,50873db31badcc71890e4f67753a65757f97aaa7dd5f1e82b753ace32219064b,u%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p;t>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fffffffffffffffffffffffffffffffffffffffffffffffffffffffff7028de7d,1eea9cc59cfcf2fa151ac6c274eea4110feb4f7b68c5965732e9992e976ef68e,u%p=0;valid_x(x2);u>=p;t>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fffffffffffffffffffffffffffffffffffffffffffffffffffffffffcbcfb7e7,12303941aedc208880735b1f1795c8e55be520ea93e103357b5d2adb7ed59b8e,u%p=0;valid_x(x1);u>=p;t>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3113ad9,7eed6b70e7b0767c7d7feac04e57aa2a12fef5e0f48f878fcbb88b3b6b5e0783,u%p=0;valid_x(x3);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff13cea4a70000000000000000000000000000000000000000000000000000000000000000,649984435b62b4a25d40c6133e8d9ab8c53d4b059ee8a154a3be0fcf4e892edb,t%p=0;valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff13cea4a7fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,649984435b62b4a25d40c6133e8d9ab8c53d4b059ee8a154a3be0fcf4e892edb,t%p=0;valid_x(x1);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff15028c590063f64d5a7f1c14915cd61eac886ab295bebd91992504cf77edb028bdd6267f,3fde5713f8282eead7d39d4201f44a7c85a5ac8a0681f35e54085c6b69543374,(u'^3+t'^2+7)%p=0;valid_x(x2);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff2715de860000000000000000000000000000000000000000000000000000000000000000,3524f77fa3a6eb4389c3cb5d27f1f91462086429cd6c0cb0df43ea8f1e7b3fb4,t%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff2715de86fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,3524f77fa3a6eb4389c3cb5d27f1f91462086429cd6c0cb0df43ea8f1e7b3fb4,t%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff2c2c5709e7156c417717f2feab147141ec3da19fb759575cc6e37b2ea5ac9309f26f0f66,d2469ab3e04acbb21c65a1809f39caafe7a77c13d10f9dd38f391c01dc499c52,(u'^3-t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff3a08cc1efffffffffffffffffffffffffffffffffffffffffffffffffffffffff760e9f0,38e2a5ce6a93e795e16d2c398bc99f0369202ce21e8f09d56777b40fc512bccc,valid_x(x3);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff3e91257d932016cbf69c4471bd1f656c6a107f1973de4af7086db897277060e25677f19a,864b3dc902c376709c10a93ad4bbe29fce0012f3dc8672c6286bba28d7d6d6fc,valid_x(x3);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff795d6c1c322cadf599dbb86481522b3cc55f15a67932db2afa0111d9ed6981bcd124bf44,766dfe4a700d9bee288b903ad58870e3d4fe2f0ef780bcac5c823f320d9a9bef,(u'^3+t'^2+7)%p=0;valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff8e426f0392389078c12b1a89e9542f0593bc96b6bfde8224f8654ef5d5cda935a3582194,faec7bc1987b63233fbc5f956edbf37d54404e7461c58ab8631bc68e451a0478,valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff91192139ffffffffffffffffffffffffffffffffffffffffffffffffffffffff45f0f1eb,ec29a50bae138dbf7d8e24825006bb5fc1a2cc1243ba335bc6116fb9e498ec1f,valid_x(x2);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff98eb9ab76e84499c483b3bf06214abfe065dddf43b8601de596d63b9e45a166a580541fe,1e0ff2dee9b09b136292a9e910f0d6ac3e552a644bba39e64e9dd3e3bbd3d4d4,(u'^3-t'^2+7)%p=0;valid_x(x3);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9b77b7f2c74d99efceaa550f1ad1c0f43f46e7ff1ee3bd0162b7bf55f2965da9c3450646,8b7dd5c3edba9ee97b70eff438f22dca9849c8254a2f3345a0a572ffeaae0928,valid_x(x2);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9b77b7f2ffffffffffffffffffffffffffffffffffffffffffffffffffffffff156ca896,0881950c8f51d6b9a6387465d5f12609ef1bb25412a08a74cb2dfb200c74bfbf,valid_x(x3);valid_x(x2);valid_x(x1);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffa2f5cd838816c16c4fe8a1661d606fdb13cf9af04b979a2e159a09409ebc8645d58fde02,2f083207b9fd9b550063c31cd62b8746bd543bdc5bbf10e3a35563e927f440c8,(u'^3+t'^2+7)%p=0;valid_x(x3);valid_x(x2);valid_x(x1);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffb13f75c00000000000000000000000000000000000000000000000000000000000000000,4f51e0be078e0cddab2742156adba7e7a148e73157072fd618cd60942b146bd0,t%p=0;valid_x(x3);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffb13f75c0fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,4f51e0be078e0cddab2742156adba7e7a148e73157072fd618cd60942b146bd0,t%p=0;valid_x(x3);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffe7bc1f8d0000000000000000000000000000000000000000000000000000000000000000,16c2ccb54352ff4bd794f6efd613c72197ab7082da5b563bdf9cb3edaafe74c2,t%p=0;valid_x(x2);u>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffe7bc1f8dfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,16c2ccb54352ff4bd794f6efd613c72197ab7082da5b563bdf9cb3edaafe74c2,t%p=0;valid_x(x2);u>=p;t>=p
+ffffffffffffffffffffffffffffffffffffffffffffffffffffffffef64d162750546ce42b0431361e52d4f5242d8f24f33e6b1f99b591647cbc808f462af51,d41244d11ca4f65240687759f95ca9efbab767ededb38fd18c36e18cd3b6f6a9,(u'^3+t'^2+7)%p=0;valid_x(x3);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffff0e5be52372dd6e894b2a326fc3605a6e8f3c69c710bf27d630dfe2004988b78eb6eab36,64bf84dd5e03670fdb24c0f5d3c2c365736f51db6c92d95010716ad2d36134c8,valid_x(x3);valid_x(x2);valid_x(x1);u>=p
+fffffffffffffffffffffffffffffffffffffffffffffffffffffffffefbb982fffffffffffffffffffffffffffffffffffffffffffffffffffffffff6d6db1f,1c92ccdfcf4ac550c28db57cff0c8515cb26936c786584a70114008d6c33a34b,valid_x(x1);u>=p;t>=p
diff --git a/test/data/packet_encoding_test_vectors.csv b/test/data/packet_encoding_test_vectors.csv
new file mode 100644
--- /dev/null
+++ b/test/data/packet_encoding_test_vectors.csv
@@ -0,0 +1,8 @@
+in_idx,in_priv_ours,in_ellswift_ours,in_ellswift_theirs,in_initiating,in_contents,in_multiply,in_aad,in_ignore,mid_x_ours,mid_x_theirs,mid_x_shared,mid_shared_secret,mid_initiator_l,mid_initiator_p,mid_responder_l,mid_responder_p,mid_send_garbage_terminator,mid_recv_garbage_terminator,out_session_id,out_ciphertext,out_ciphertext_endswith
+1,61062ea5071d800bbfd59e2e8b53d47d194b095ae5a4df04936b49772ef0d4d7,ec0adff257bbfe500c188c80b4fdd640f6b45a482bbc15fc7cef5931deff0aa186f6eb9bba7b85dc4dcc28b28722de1e3d9108b985e2967045668f66098e475b,a4a94dfce69b4a2a0a099313d10f9f7e7d649d60501c9e1d274c300e0d89aafaffffffffffffffffffffffffffffffffffffffffffffffffffffffff8faf88d5,1,8e,1,,0,19e965bc20fc40614e33f2f82d4eeff81b5e7516b12a5c6c0d6053527eba0923,0c71defa3fafd74cb835102acd81490963f6b72d889495e06561375bd65f6ffc,4eb2bf85bd00939468ea2abb25b63bc642e3d1eb8b967fb90caa2d89e716050e,c6992a117f5edbea70c3f511d32d26b9798be4b81a62eaee1a5acaa8459a3592,9a6478b5fbab1f4dd2f78994b774c03211c78312786e602da75a0d1767fb55cf,7d0c7820ba6a4d29ce40baf2caa6035e04f1e1cefd59f3e7e59e9e5af84f1f51,17bc726421e4054ac6a1d54915085aaa766f4d3cf67bbd168e6080eac289d15e,9f0fc1c0e85fd9a8eee07e6fc41dba2ff54c7729068a239ac97c37c524cca1c0,faef555dfcdb936425d84aba524758f3,02cb8ff24307a6e27de3b4e7ea3fa65b,ce72dffb015da62b0d0f5474cab8bc72605225b0cee3f62312ec680ec5f41ba5,7530d2a18720162ac09c25329a60d75adf36eda3c3,
+999,6f312890ec83bbb26798abaadd574684a53e74ccef7953b790fcc29409080246,a8785af31c029efc82fa9fc677d7118031358d7c6a25b5779a9b900e5ccd94aac97eb36a3c5dbcdb2ca5843cc4c2fe0aaa46d10eb3d233a81c3dde476da00eef,fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f0000000000000000000000000000000000000000000000000000000000000000,0,3eb1d4e98035cfd8eeb29bac969ed3824a,1,,0,d4b65faa965b31fe2d9faaeb806c6449a50fe3679555c3518f7a0885f572457f,edd1fd3e327ce90cc7a3542614289aee9682003e9cf7dcc9cf2ca9743be5aa0c,13c1bf6a3ca37da9ffc7f45ec1810fa935c45454c03dc0144c1a9755bb52f81f,a6f79eb08243b6f65dbe42bfe4a6cf3f131d6963fa5d06c770a18f7b9c489b78,efc938c88c925459a9c837238716cfadfb1c3016f60d12923933710b5fcc9b55,91702f3cbd33b3c4a0b29b40548aea1ab01e43582db194afee70637d247aa036,7f457572e4260c611a6858acc8f325d87a3c8af8a59ce1da26ef6041f35715e8,1fe4d56334f5b0a5bd3c71ce4e338f40fc7e194925daa7ee6ce98aecf1766d7c,44737108aec5f8b6c1c277b31bbce9c1,ca29b3a35237f8212bd13ed187a1da2e,b0490e26111cb2d55bbff2ace00f7f644f64006539abb4e7513f05107bb10608,d78adbcba0eebfb15cfbd8142c84dc729d233d0dc11b1d851e46a114122b8d5b96b7d59317,
+0,846a784f1a03dea59cc679754a60a7145542fa130e3efbd815c81e909ce32933,480eacf1536b52257bf8ce78d8f4ce09395d744767c6c129e7838947ee625af3245592c111275e877d5baae22584cb5f1153e67c16bcd7da767726cd0d0c846a,ffffffffffffffffffffffffffffffffffffffffffffffffffffffff22d5e441524d571a52b3def126189d3f416890a99d4da6ede2b0cde1760ce2c3f98457ae,1,054290a6c6ba8d80478172e89d32bf690913ae9835de6dcf206ff1f4d652286fe0ddf74deba41d55de3edc77c42a32af79bbea2c00bae7492264c60866ae5a,1,84932a55aac22b51e7b128d31d9f0550da28e6a3f394224707d878603386b2f9d0c6bcd8046679bfed7b68c517e7431e75d9dd34605727d2ef1c2babbf680ecc8d68d2c4886e9953a4034abde6da4189cd47c6bb3192242cf714d502ca6103ee84e08bc2ca4fd370d5ad4e7d06c7fbf496c6c7cc7eb19c40c61fb33df2a9ba48497a96c98d7b10c1f91098a6b7b16b4bab9687f27585ade1491ae0dba6a79e1e2d85dd9d9d45c5135ca5fca3f0f99a60ea39edbc9efc7923111c937913f225d67788d5f7e8852b697e26b92ec7bfcaa334a1665511c2b4c0a42d06f7ab98a9719516c8fd17f73804555ee84ab3b7d1762f6096b778d3cb9c799cbd49a9e4a325197b4e6cc4a5c4651f8b41ff88a92ec428354531f970263b467c77ed11312e2617d0d53fe9a8707f51f9f57a77bfb49afe3d89d85ec05ee17b9186f360c94ab8bb2926b65ca99dae1d6ee1af96cad09de70b6767e949023e4b380e66669914a741ed0fa420a48dbc7bfae5ef2019af36d1022283dd90655f25eec7151d471265d22a6d3f91dc700ba749bb67c0fe4bc0888593fbaf59d3c6fff1bf756a125910a63b9682b597c20f560ecb99c11a92c8c8c3f7fbfaa103146083a0ccaecf7a5f5e735a784a8820155914a289d57d8141870ffcaf588882332e0bcd8779efa931aa108dab6c3cce76691e345df4a91a03b71074d66333fd3591bff071ea099360f787bbe43b7b3dff2a59c41c7642eb79870222ad1c6f2e5a191ed5acea51134679587c9cf71c7d8ee290be6bf465c4ee47897a125708704ad610d8d00252d01959209d7cd04d5ecbbb1419a7e84037a55fefa13dee464b48a35c96bcb9a53e7ed461c3a1607ee00c3c302fd47cd73fda7493e947c9834a92d63dcfbd65aa7c38c3e3a2748bb5d9a58e7495d243d6b741078c8f7ee9c8813e473a323375702702b0afae1550c8341eedf5247627343a95240cb02e3e17d5dca16f8d8d3b2228e19c06399f8ec5c5e9dbe4caef6a0ea3ffb1d3c7eac03ae030e791fa12e537c80d56b55b764cadf27a8701052df1282ba8b5e3eb62b5dc7973ac40160e00722fa958d95102fc25c549d8c0e84bed95b7acb61ba65700c4de4feebf78d13b9682c52e937d23026fb4c6193e6644e2d3c99f91f4f39a8b9fc6d013f89c3793ef703987954dc0412b550652c01d922f525704d32d70d6d4079bc3551b563fb29577b3aecdc9505011701dddfd94830431e7a4918927ee44fb3831ce8c4513839e2deea1287f3fa1ab9b61a256c09637dbc7b4f0f8fbb783840f9c24526da883b0df0c473cf231656bd7bc1aaba7f321fec0971c8c2c3444bff2f55e1df7fea66ec3e440a612db9aa87bb505163a59e06b96d46f50d8120b92814ac5ab146bc78dbbf91065af26107815678ce6e33812e6bf3285d4ef3b7b04b076f21e7820dcbfdb4ad5218cf4ff6a65812d8fcb98ecc1e95e2fa58e3efe4ce26cd0bd400d6036ab2ad4f6c713082b5e3f1e04eb9e3b6c8f63f57953894b9e220e0130308e1fd91f72d398c1e7962ca2c31be83f31d6157633581a0a6910496de8d55d3d07090b6aa087159e388b7e7dec60f5d8a60d93ca2ae91296bd484d916bfaaa17c8f45ea4b1a91b37c82821199a2b7596672c37156d8701e7352aa48671d3b1bbbd2bd5f0a2268894a25b0cb2514af39c8743f8cce8ab4b523053739fd8a522222a09acf51ac704489cf17e4b7125455cb8f125b4d31af1eba1f8cf7f81a5a100a141a7ee72e8083e065616649c241f233645c5fc865d17f0285f5c52d9f45312c979bfb3ce5f2a1b951deddf280ffb3f370410cffd1583bfa90077835aa201a0712d1dcd1293ee177738b14e6b5e2a496d05220c3253bb6578d6aff774be91946a614dd7e879fb3dcf7451e0b9adb6a8c44f53c2c464bcc0019e9fad89cac7791a0a3f2974f759a9856351d4d2d7c5612c17cfc50f8479945df57716767b120a590f4bf656f4645029a525694d8a238446c5f5c2c1c995c09c1405b8b1eb9e0352ffdf766cc964f8dcf9f8f043dfab6d102cf4b298021abd78f1d9025fa1f8e1d710b38d9d1652f2d88d1305874ec41609b6617b65c5adb19b6295dc5c5da5fdf69f28144ea12f17c3c6fcce6b9b5157b3dfc969d6725fa5b098a4d9b1d31547ed4c9187452d281d0a5d456008caf1aa251fac8f950ca561982dc2dc908d3691ee3b6ad3ae3d22d002577264ca8e49c523bd51c4846be0d198ad9407bf6f7b82c79893eb2c05fe9981f687a97a4f01fe45ff8c8b7ecc551135cd960a0d6001ad35020be07ffb53cb9e731522ca8ae9364628914b9b8e8cc2f37f03393263603cc2b45295767eb0aac29b0930390eb89587ab2779d2e3decb8042acece725ba42eda650863f418f8d0d50d104e44fbbe5aa7389a4a144a8cecf00f45fb14c39112f9bfb56c0acbd44fa3ff261f5ce4acaa5134c2c1d0cca447040820c81ab1bcdc16aa075b7c68b10d06bbb7ce08b5b805e0238f24402cf24a4b4e00701935a0c68add3de090903f9b85b153cb179a582f57113bfc21c2093803f0cfa4d9d4672c2b05a24f7e4c34a8e9101b70303a7378b9c50b6cddd46814ef7fd73ef6923feceab8fc5aa8b0d185f2e83c7a99dcb1077c0ab5c1f5d5f01ba2f0420443f75c4417db9ebf1665efbb33dca224989920a64b44dc26f682cc77b4632c8454d49135e52503da855bc0f6ff8edc1145451a9772c06891f41064036b66c3119a0fc6e80dffeb65dc456108b7ca0296f4175fff3ed2b0f842cd46bd7e86f4c62dfaf1ddbf836263c00b34803de164983d0811cebfac86e7720c726d3048934c36c23189b02386a722ca9f0fe00233ab50db928d3bccea355cc681144b8b7edcaae4884d5a8f04425c0890ae2c74326e138066d8c05f4c82b29df99b034ea727afde590a1f2177ace3af99cfb1729d6539ce7f7f7314b046aab74497e63dd399e1f7d5f16517c23bd830d1fdee810f3c3b77573dd69c4b97d80d71fb5a632e00acdfa4f8e829faf3580d6a72c40b28a82172f8dcd4627663ebf6069736f21735fd84a226f427cd06bb055f94e7c92f31c48075a2955d82a5b9d2d0198ce0d4e131a112570a8ee40fb80462a81436a58e7db4e34b6e2c422e82f934ecda9949893da5730fc5c23c7c920f363f85ab28cc6a4206713c3152669b47efa8238fa826735f17b4e78750276162024ec85458cd5808e06f40dd9fd43775a456a3ff6cae90550d76d8b2899e0762ad9a371482b3e38083b1274708301d6346c22fea9bb4b73db490ff3ab05b2f7f9e187adef139a7794454b7300b8cc64d3ad76c0e4bc54e08833a4419251550655380d675bc91855aeb82585220bb97f03e976579c08f321b5f8f70988d3061f41465517d53ac571dbf1b24b94443d2e9a8e8a79b392b3d6a4ecdd7f626925c365ef6221305105ce9b5f5b6ecc5bed3d702bd4b7f5008aa8eb8c7aa3ade8ecf6251516fbefeea4e1082aa0e1848eddb31ffe44b04792d296054402826e4bd054e671f223e5557e4c94f89ca01c25c44f1a2ff2c05a70b43408250705e1b858bf0670679fdcd379203e36be3500dd981b1a6422c3cf15224f7fefdef0a5f225c5a09d15767598ecd9e262460bb33a4b5d09a64591efabc57c923d3be406979032ae0bc0997b65336a06dd75b253332ad6a8b63ef043f780a1b3fb6d0b6cad98b1ef4a02535eb39e14a866cfc5fc3a9c5deb2261300d71280ebe66a0776a151469551c3c5fa308757f956655278ec6330ae9e3625468c5f87e02cd9a6489910d4143c1f4ee13aa21a6859d907b788e28572fecee273d44e4a900fa0aa668dd861a60fb6b6b12c2c5ef3c8df1bd7ef5d4b0d1cdb8c15fffbb365b9784bd94abd001c6966216b9b67554ad7cb7f958b70092514f7800fc40244003e0fd1133a9b850fb17f4fcafde07fc87b07fb510670654a5d2d6fc9876ac74728ea41593beef003d6858786a52d3a40af7529596767c17000bfaf8dc52e871359f4ad8bf6e7b2853e5229bdf39657e213580294a5317c5df172865e1e17fe37093b585e04613f5f078f761b2b1752eb32983afda24b523af8851df9a02b37e77f543f18888a782a994a50563334282bf9cdfccc183fdf4fcd75ad86ee0d94f91ee2300a5befbccd14e03a77fc031a8cfe4f01e4c5290f5ac1da0d58ea054bd4837cfd93e5e34fc0eb16e48044ba76131f228d16cde9b0bb978ca7cdcd10653c358bdb26fdb723a530232c32ae0a4cecc06082f46e1c1d596bfe60621ad1e354e01e07b040cc7347c016653f44d926d13ca74e6cbc9d4ab4c99f4491c95c76fff5076b3936eb9d0a286b97c035ca88a3c6309f5febfd4cdaac869e4f58ed409b1e9eb4192fb2f9c2f12176d460fd98286c9d6df84598f260119fd29c63f800c07d8df83d5cc95f8c2fea2812e7890e8a0718bb1e031ecbebc0436dcf3e3b9a58bcc06b4c17f711f80fe1dffc3326a6eb6e00283055c6dabe20d311bfd5019591b7954f8163c9afad9ef8390a38f3582e0a79cdf0353de8eeb6b5f9f27b16ffdef7dd62869b4840ee226ccdce95e02c4545eb981b60571cd83f03dc5eaf8c97a0829a4318a9b3dc06c0e003db700b2260ff1fa8fee66890e637b109abb03ec901b05ca599775f48af50154c0e67d82bf0f558d7d3e0778dc38bea1eb5f74dc8d7f90abdf5511a424be66bf8b6a3cacb477d2e7ef4db68d2eba4d5289122d851f9501ba7e9c4957d8eba3be3fc8e785c4265a1d65c46f2809b70846c693864b169c9dcb78be26ea14b8613f145b01887222979a9e67aee5f800caa6f5c4229bdeefc901232ace6143c9865e4d9c07f51aa200afaf7e48a7d1d8faf366023beab12906ffcb3eaf72c0eb68075e4daf3c080e0c31911befc16f0cc4a09908bb7c1e26abab38bd7b788e1a09c0edf1a35a38d2ff1d3ed47fcdaae2f0934224694f5b56705b9409b6d3d64f3833b686f7576ec64bbdd6ff174e56c2d1edac0011f904681a73face26573fbba4e34652f7ae84acfb2fa5a5b3046f98178cd0831df7477de70e06a4c00e305f31aafc026ef064dd68fd3e4252b1b91d617b26c6d09b6891a00df68f105b5962e7f9d82da101dd595d286da721443b72b2aba2377f6e7772e33b3a5e3753da9c2578c5d1daab80187f55518c72a64ee150a7cb5649823c08c9f62cd7d020b45ec2cba8310db1a7785a46ab24785b4d54ff1660b5ca78e05a9a55edba9c60bf044737bc468101c4e8bd1480d749be5024adefca1d998abe33eaeb6b11fbb39da5d905fdd3f611b2e51517ccee4b8af72c2d948573505590d61a6783ab7278fc43fe55b1fcc0e7216444d3c8039bb8145ef1ce01c50e95a3f3feab0aee883fdb94cc13ee4d21c542aa795e18932228981690f4d4c57ca4db6eb5c092e29d8a05139d509a8aeb48baa1eb97a76e597a32b280b5e9d6c36859064c98ff96ef5126130264fa8d2f49213870d9fb036cff95da51f270311d9976208554e48ffd486470d0ecdb4e619ccbd8226147204baf8e235f54d8b1cba8fa34a9a4d055de515cdf180d2bb6739a175183c472e30b5c914d09eeb1b7dafd6872b38b48c6afc146101200e6e6a44fe5684e220adc11f5c403ddb15df8051e6bdef09117a3a5349938513776286473a3cf1d2788bb875052a2e6459fa7926da33380149c7f98d7700528a60c954e6f5ecb65842fde69d614be69eaa2040a4819ae6e756accf936e14c1e894489744a79c1f2c1eb295d13e2d767c09964b61f9cfe497649f712,0,014e5bdbb1d7eb34a88a016ab3dd45e343dc703fafa8266907ab67a76c5eb2d6,568146140669e69646a6ffeb3793e8010e2732209b4c34ec13e209a070109183,10578110283044630bc13a9f12b00eb0af7cba9f53506add2b57ae07b3987ced,e500c670f1b32f60e05009bddcdbfa7153afb19c20479583a54b43d85b3433a8,67b155367abf65d45a60412e16bd5ef5e862aa0a4a7a56366cfcc602072176b8,93f5b4c59038c16c3f09793976c75e522bf994635e3f1ef9f04e628281e0d5f7,08fe46857ab4e62d7463c00ac510e041d28dbfc21853e8f4db971890c7330098,2271d5f5351a91ca768a83c5aa7f45fb2b2742e89351d93a680f51a030f9255c,3ba1f51de6272aa28fd21059b91d3893,faf3b317340de00e29f2181db270ff81,d083d09c1bdf71795b39a9534601cf7c7a7e767e578c44a17dfaf43a3c18f98c,6aa28bc4b6719eca144ac33a3f17859317d5450e4978db9365ce61e7085a617dd386ec18eb436c9056aa1d2d4736c9bffd25803d967fcae916ce1647ccae3d5258b17dfa1cdc7eb99581c48ff2898ef92d3aa1,
+223,c0f15820459f64d98e5c48681d13340572c574533dd9f7161b85fcc8224fdf30,682871104d694baca8b9c7990ae6288f49e1ff4feb21dd5cffad67db7752fdfb6c3608d6996c54be04b35feef037da09ee4d9dca2363b343bc2d4f6d0ea609da,56bd0c06f10352c3a1a9f4b4c92f6fa2b26df124b57878353c1fc691c51abea77c8817daeeb9fa546b77c8daf79d89b22b0e1b87574ece42371f00237aa9d83a,0,7e0e78eb6990b059e6cf0ded66ea93ef82e72aa2f18ac24f2fc6ebab561ae557420729da103f64cecfa20527e15f9fb669a49bbbf274ef0389b3e43c8c44e5f60bf2ac38e2b55e7ec4273dba15ba41d21f8f5b3ee1688b3c29951218caf847a97fb50d75a86515d445699497d968164bf740012679b8962de573be941c62b7ef,1,,1,5d673dd0a75ccacf4e1310e9402ecdacdd474d8bbfa6eeefdde2e1b216d41dbe,2dd7b9cc85524f8670f695c3143ac26b45cebcabb2782a85e0fe15aee3956535,1c229ba46fadced7217df782d410961c1399375135e4aa718fa3424ec36539cc,b764f617cf8c8dcf6018e4f5e8ee603a086498a3732621c9b0fc0a485ea0d2f0,e25747c749e78c7a0102352378f7c15566145b57f082f7e10b10a0606b323996,c0547fbf3082c7a0377b4e709b982ecb4710012dcf3b0c073ed3811a2b7c1309,5bb291885bf5b08a4218c2bf3498d3591be93a47412c770b60299c8e740ac560,fdf5a3e3e75afc15a924373e58af505052731efa75c76a1fa3546954d60b50b1,8461c1dc173be7e6a2316d09710ebd8d,dfa2d33623fe80e2347999e6de0f96fd,279a96e6ce08e5074608fcad77d6a78f90c8b618a4520575435b1a37b1c56df9,,5afbd61f6e989833df2f12ff70c98f1a20ebe84acba2a05429cc6a57238dba87cdc432474f378889b2d0e95ade9f892eb1a1f6b03b73f903682476537f653f738f7a9f1cc9856ed75f3d69122bdeb00af48e66a64872f639a67fc109ee5ca124d0ee183da3c2b8f2da828850b50976b491f1add78d7f01e07565570621266852
+448,96cb391886681d1d3e23948e51987771a8ec3001b640c18fb994a855cea66b6e,ffffffffffffffffffffffffffffffffffffffffffffffffffffffffdde3a077a6fd73711a27250c439ba78ef63d89cd0918c0a0a75f301ed96aa2a43ecf3f61,ffffffffffffffffffffffffffffffffffffffffffffffffffffffffa7730be30000000000000000000000000000000000000000000000000000000000000000,1,00cf68f8f7ac49ffaa02c4864fdf6dfe7bbf2c740b88d98c50ebafe32c92f3427f57601ffcb21a3435979287db8fee6c302926741f9d5e464c647eeb9b7acaeda46e00abd7506fc9a719847e9a7328215801e96198dac141a15c7c2f68e0690dd1176292a0dded04d1f548aad88f1aebdc0a8f87da4bb22df32dd7c160c225b843e83f6525d6d484f502f16d923124fc538794e21da2eb689d18d87406ecced5b9f92137239ed1d37bcfa7836641a83cf5e0a1cf63f51b06f158e499a459ede41c,1,,0,f7561c791f6f4aa73dcef3cac32f2433b4cfa4ab0666e93552b7cbc7249fb2de,5232c4b6bde9d3d45d7b763ebd7495399bb825cc21de51011761cd81a51bdc84,2651a46a622f79e2ab18819587e7f897e3f8351b1e1b66d8ed4543a1e40bc569,779a18107756169a6b369d043f3ef9a90178c7ab8c8c37b4edcd9b5397e41eca,368c7283e088e40b79e6214046beab64cbac30a89940acbc30d430f941fe7d35,224065c728d5cdabbe209cd52621324471ce8dc229907c018cec05781a9c770d,9ce33c019a081e5f8b62e1f12d652f0b036ed65f5de195d931dfcd92043b5eb2,001e576d8828a6d84913b01cb88e8f5532207f34275017b61650ba1383646cbc,7bf55f6b58f73cdff19ee3292607239f,d121874372c61a48fd87da6d01d89da4,e9515794acced50e0550a3ebd95c170d2abd48b5f23fccca73bc597f00c88cf2,,33953941be2682da1c6d1b167cbf180d7cb8159c94c6ea1c52356716f1057af4df53321f18894c285f7b2fd85b2edc44a13c9295f310962fdfc8d944bd77c5500b10ca68ca5d0977d19d183a7def742c41cfeee763dc09ef985c96ab6e74e464f66992f752c9368e42082ad338705062ddfcad4ca1c9c54004b9345d8df25953
+673,4a7065c3ddbf84e29b8e20da0da3aaae1f708eae8ad1af4c4c00f46a7cda7b6b,ffffffffffffffffffffffffffffffffffffffffffffffffffffffff450012ec3aeecf516f4b374af2e7fbb040e92dc3c0f12eafd00c729a137f4e892e5293c3,9652d78baefc028cd37a6a92625b8b8f85fde1e4c944ad3f20e198bef8c02f19fffffffffffffffffffffffffffffffffffffffffffffffffffffffff2e91870,0,5c6272ee55da855bbbf7b1246d9885aa7aa601a715ab86fa46c50da533badf82b97597c968293ae04e,97561,,0,a0ff3dd41ca11036eea75ea08993c938894c7eebca99354ac2e0daa8a1a6b2ca,64c383e0e78ac99476ddff2061683eeefa505e3666673a1371342c3e6c26981d,ca3f58a228c530be63eec8a427d16496776aefb22e693152a3a9394b9a87d097,a993062a328371beecae7e2b05a34355c1cefbad7f855ad48331dcf002972999,24cdf9d8533696a5795cadcf5b94826ddbe5f047ba02c832b3495ac7c1110e31,7b5d1c66668d20d57a4e0a6ba4d9aa3e3ba0f704697aa7edb9ce9471d46647da,e6a808d35ee403b3f4bbcd8fd49fa005a40dfaaf36f9f504318bb94637067060,d6ae42117344fb71cb1817a1dc192a4b5bb35d885005093c3e9bd4576069b217,1fec304dcaacf1f5b088325306272d78,d2d16a8452807baa4f63b059b5804624,dccb606c4f2a0f64bc164dbc00eb0f6cf1474575e89d7928be6346720bb53610,,58daef966f33c036740aeb3f6a4b31c0f0a070b25fd6a1abf82ef56fc2cb3ca8da8c434f23790c69349dd0cb4058f88a7bd0e333c8ceba3c80f21e951b9fdb1c84e2e7f49f43c21087566d58f1bcc42b041e0b462e37e927c0071caa9a2b650dccf448c9f88d73b62e80a3e5d5e4e46992e34b416ceb9590a7c8b7bfaccf37ab
+1024,0f69aeffeff6172647ee5aa80bfb418ee742f4e9f1a51b463ac7c120d620e37d,ffffffffffffffffffffffffffffffffffffffffffffffffffffffff04df0e67f9753e2cdb066b3b588a0069fde936a312e0d3f31acb335026b7072d8f2ad24c,12a50f3fafea7c1eeada4cf8d33777704b77361453afc83bda91eef349ae044d20126c6200547ea5a6911776c05dee2a7f1a9ba7dfbabbbd273c3ef29ef46e46,1,5f67d15d22ca9b2804eeab0a66f7f8e3a10fa5de5809a046084348cbc5304e843ef96f59a59c7d7fdfe5946489f3ea297d941bac326225df316a25fc90f0e65b0d31a9c497e960fdbf8c482516bc8a9c1c77b7f6d0e1143810c737f76f9224e6f2c9af5186b4f7259c7e8d165b6e4fe3d38a60bdbdd4d06ecdcaaf62086070dbb68686b802d53dfd7db14b18743832605f5461ad81e2af4b7e8ff0eff0867a25b93cec7becf15c43131895fed09a83bf1ee4a87d44dd0f02a837bf5a1232e201cb882734eb9643dc2dc4d4e8b5690840766212c7ac8f38ad8a9ec47c7a9b3e022ae3eb6a32522128b518bd0d0085dd81c5,69615,,1,115b298a52a9362706ddd1e493de09443dd8ac2b0c3e4e5e8b6bb295598db05d,eef379db9bd4b1aa90fc347fad33f7d53083389e22e971036f59f4e29d325ac2,32e15c20a09591b6600c778752a582fed444444fd0d3317613555c6509ff4b8d,1756deace376ece25da9825fe49f76a9272a89a7b746c83ca2c4016f5a30ead4,15e26b12238d66ebc4cb72d16a62a8bb404c94d31bbe3b1d22a01b851e935010,c135367f39b24a9cc9b73ad628fba1887737f5686062c4c36146e76849828a50,ffa25ddf7cd4cd10a47f6c3b32a54ee882837058e31677d3958539f4f23e4616,12f9b3ebbf743f6b93c7d0f4f20259fac2a27ea6735fd9ef2e2699049af60fcc,4dfac3b0a99401f6aad1a8df3cd7dd05,e5d4905a8b6a5d18ec6cebbdecd703d3,fc2431beb9a666bf888df0662276a4b6a1af5061072992ef408f2b686c86a2ac,,1a7f3fb83ad2b050b663b8df6b7c2cc2d8e169a869a58bf7ef5ab5db97a505c84a812e100d9445da4fc39a1176d6aed3995f6868631224b86f10603217c8d13270e0c6d054ad9e0d0b7dc0c8e59a37cd05a0a45faa14b4ffc8d12b641f62e6f1b71c1f72b737e9ce3fe74be779b25e70bf11d98766b3876d0fa28d3c669087fc
diff --git a/test/data/xswiftec_inv_test_vectors.csv b/test/data/xswiftec_inv_test_vectors.csv
new file mode 100644
--- /dev/null
+++ b/test/data/xswiftec_inv_test_vectors.csv
@@ -0,0 +1,33 @@
+u,x,case0_t,case1_t,case2_t,case3_t,case4_t,case5_t,case6_t,case7_t,comment
+05ff6bdad900fc3261bc7fe34e2fb0f569f06e091ae437d3a52e9da0cbfb9590,80cdf63774ec7022c89a5a8558e373a279170285e0ab27412dbce510bdfe23fc,,,45654798ece071ba79286d04f7f3eb1c3f1d17dd883610f2ad2efd82a287466b,0aeaa886f6b76c7158452418cbf5033adc5747e9e9b5d3b2303db96936528557,,,ba9ab867131f8e4586d792fb080c14e3c0e2e82277c9ef0d52d1027c5d78b5c4,f51557790948938ea7badbe7340afcc523a8b816164a2c4dcfc24695c9ad76d8,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:info[v=0]&ok;case3:ok;case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:info[v=0]&ok;case7:ok
+1737a85f4c8d146cec96e3ffdca76d9903dcf3bd53061868d478c78c63c2aa9e,39e48dd150d2f429be088dfd5b61882e7e8407483702ae9a5ab35927b15f85ea,1be8cc0b04be0c681d0c6a68f733f82c6c896e0c8a262fcd392918e303a7abf4,605b5814bf9b8cb066667c9e5480d22dc5b6c92f14b4af3ee0a9eb83b03685e3,,,e41733f4fb41f397e2f3959708cc07d3937691f375d9d032c6d6e71bfc58503b,9fa4a7eb4064734f99998361ab7f2dd23a4936d0eb4b50c11f56147b4fc9764c,,,case0:ok;case1:ok;case2:info[v=0]&bad[non_square(s)];case3:bad[non_square(s)];case4:ok;case5:ok;case6:info[v=0]&bad[non_square(s)];case7:bad[non_square(s)]
+1aaa1ccebf9c724191033df366b36f691c4d902c228033ff4516d122b2564f68,c75541259d3ba98f207eaa30c69634d187d0b6da594e719e420f4898638fc5b0,,,,,,,,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:bad[non_square(q)];case3:bad[non_square(q)];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:bad[non_square(q)];case7:bad[non_square(q)]
+2323a1d079b0fd72fc8bb62ec34230a815cb0596c2bfac998bd6b84260f5dc26,239342dfb675500a34a196310b8d87d54f49dcac9da50c1743ceab41a7b249ff,f63580b8aa49c4846de56e39e1b3e73f171e881eba8c66f614e67e5c975dfc07,b6307b332e699f1cf77841d90af25365404deb7fed5edb3090db49e642a156b6,,,09ca7f4755b63b7b921a91c61e4c18c0e8e177e145739909eb1981a268a20028,49cf84ccd19660e30887be26f50dac9abfb2148012a124cf6f24b618bd5ea579,,,case0:ok;case1:ok;case2:bad[non_square(q)];case3:bad[non_square(q)];case4:ok;case5:ok;case6:bad[non_square(q)];case7:bad[non_square(q)]
+2dc90e640cb646ae9164c0b5a9ef0169febe34dc4437d6e46acb0e27e219d1e8,d236f19bf349b9516e9b3f4a5610fe960141cb23bbc8291b9534f1d71de62a47,e69df7d9c026c36600ebdf588072675847c0c431c8eb730682533e964b6252c9,4f18bbdf7c2d6c5f818c18802fa35cd069eaa79fff74e4fc837c80d93fece2f8,,,196208263fd93c99ff1420a77f8d98a7b83f3bce37148cf97dacc168b49da966,b0e7442083d293a07e73e77fd05ca32f96155860008b1b037c837f25c0131937,,,case0:ok;case1:info[v=0]&ok;case2:bad[non_square(q)];case3:bad[non_square(q)];case4:ok;case5:info[v=0]&ok;case6:bad[non_square(q)];case7:bad[non_square(q)]
+3edd7b3980e2f2f34d1409a207069f881fda5f96f08027ac4465b63dc278d672,053a98de4a27b1961155822b3a3121f03b2a14458bd80eb4a560c4c7a85c149c,,,b3dae4b7dcf858e4c6968057cef2b156465431526538199cf52dc1b2d62fda30,4aa77dd55d6b6d3cfa10cc9d0fe42f79232e4575661049ae36779c1d0c666d88,,,4c251b482307a71b39697fa8310d4ea9b9abcead9ac7e6630ad23e4c29d021ff,b558822aa29492c305ef3362f01bd086dcd1ba8a99efb651c98863e1f3998ea7,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:ok;case3:ok;case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:ok;case7:ok
+4295737efcb1da6fb1d96b9ca7dcd1e320024b37a736c4948b62598173069f70,fa7ffe4f25f88362831c087afe2e8a9b0713e2cac1ddca6a383205a266f14307,,,,,,,,,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:bad[non_square(s)];case3:bad[non_square(s)];case4:bad[non_square(s)];case5:bad[non_square(s)];case6:bad[non_square(s)];case7:bad[non_square(s)]
+587c1a0cee91939e7f784d23b963004a3bf44f5d4e32a0081995ba20b0fca59e,2ea988530715e8d10363907ff25124524d471ba2454d5ce3be3f04194dfd3a3c,cfd5a094aa0b9b8891b76c6ab9438f66aa1c095a65f9f70135e8171292245e74,a89057d7c6563f0d6efa19ae84412b8a7b47e791a191ecdfdf2af84fd97bc339,475d0ae9ef46920df07b34117be5a0817de1023e3cc32689e9be145b406b0aef,a0759178ad80232454f827ef05ea3e72ad8d75418e6d4cc1cd4f5306c5e7c453,302a5f6b55f464776e48939546bc709955e3f6a59a0608feca17e8ec6ddb9dbb,576fa82839a9c0f29105e6517bbed47584b8186e5e6e132020d507af268438f6,b8a2f51610b96df20f84cbee841a5f7e821efdc1c33cd9761641eba3bf94f140,5f8a6e87527fdcdbab07d810fa15c18d52728abe7192b33e32b0acf83a1837dc,case0:ok;case1:ok;case2:ok;case3:ok;case4:ok;case5:ok;case6:ok;case7:ok
+5fa88b3365a635cbbcee003cce9ef51dd1a310de277e441abccdb7be1e4ba249,79461ff62bfcbcac4249ba84dd040f2cec3c63f725204dc7f464c16bf0ff3170,,,6bb700e1f4d7e236e8d193ff4a76c1b3bcd4e2b25acac3d51c8dac653fe909a0,f4c73410633da7f63a4f1d55aec6dd32c4c6d89ee74075edb5515ed90da9e683,,,9448ff1e0b281dc9172e6c00b5893e4c432b1d4da5353c2ae3725399c016f28f,0b38cbef9cc25809c5b0e2aa513922cd3b39276118bf8a124aaea125f25615ac,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:ok;case3:info[v=0]&ok;case4:bad[non_square(s)];case5:bad[non_square(s)];case6:ok;case7:info[v=0]&ok
+6fb31c7531f03130b42b155b952779efbb46087dd9807d241a48eac63c3d96d6,56f81be753e8d4ae4940ea6f46f6ec9fda66a6f96cc95f506cb2b57490e94260,,,59059774795bdb7a837fbe1140a5fa59984f48af8df95d57dd6d1c05437dcec1,22a644db79376ad4e7b3a009e58b3f13137c54fdf911122cc93667c47077d784,,,a6fa688b86a424857c8041eebf5a05a667b0b7507206a2a82292e3f9bc822d6e,dd59bb2486c8952b184c5ff61a74c0ecec83ab0206eeedd336c9983a8f8824ab,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:ok;case3:info[v=0]&ok;case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:ok;case7:info[v=0]&ok
+704cd226e71cb6826a590e80dac90f2d2f5830f0fdf135a3eae3965bff25ff12,138e0afa68936ee670bd2b8db53aedbb7bea2a8597388b24d0518edd22ad66ec,,,,,,,,,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:bad[non_square(q)];case3:bad[non_square(q)];case4:bad[non_square(s)];case5:bad[non_square(s)];case6:bad[non_square(q)];case7:bad[non_square(q)]
+725e914792cb8c8949e7e1168b7cdd8a8094c91c6ec2202ccd53a6a18771edeb,8da16eb86d347376b6181ee9748322757f6b36e3913ddfd332ac595d788e0e44,dd357786b9f6873330391aa5625809654e43116e82a5a5d82ffd1d6624101fc4,a0b7efca01814594c59c9aae8e49700186ca5d95e88bcc80399044d9c2d8613d,,,22ca8879460978cccfc6e55a9da7f69ab1bcee917d5a5a27d002e298dbefdc6b,5f481035fe7eba6b3a63655171b68ffe7935a26a1774337fc66fbb253d279af2,,,case0:ok;case1:info[v=0]&ok;case2:bad[non_square(s)];case3:bad[non_square(s)];case4:ok;case5:info[v=0]&ok;case6:bad[non_square(s)];case7:bad[non_square(s)]
+78fe6b717f2ea4a32708d79c151bf503a5312a18c0963437e865cc6ed3f6ae97,8701948e80d15b5cd8f72863eae40afc5aced5e73f69cbc8179a33902c094d98,,,,,,,,,case0:bad[non_square(s)];case1:info[v=0]&bad[non_square(s)];case2:bad[non_square(q)];case3:bad[non_square(q)];case4:bad[non_square(s)];case5:info[v=0]&bad[non_square(s)];case6:bad[non_square(q)];case7:bad[non_square(q)]
+7c37bb9c5061dc07413f11acd5a34006e64c5c457fdb9a438f217255a961f50d,5c1a76b44568eb59d6789a7442d9ed7cdc6226b7752b4ff8eaf8e1a95736e507,,,b94d30cd7dbff60b64620c17ca0fafaa40b3d1f52d077a60a2e0cafd145086c2,,,,46b2cf32824009f49b9df3e835f05055bf4c2e0ad2f8859f5d1f3501ebaf756d,,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:info[q=0]&info[X=0]&ok;case3:info[q=0]&bad[r=0];case4:bad[non_square(s)];case5:bad[non_square(s)];case6:info[q=0]&info[X=0]&ok;case7:info[q=0]&bad[r=0]
+82388888967f82a6b444438a7d44838e13c0d478b9ca060da95a41fb94303de6,29e9654170628fec8b4972898b113cf98807f4609274f4f3140d0674157c90a0,,,,,,,,,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:bad[non_square(s)];case3:info[v=0]&bad[non_square(s)];case4:bad[non_square(s)];case5:bad[non_square(s)];case6:bad[non_square(s)];case7:info[v=0]&bad[non_square(s)]
+91298f5770af7a27f0a47188d24c3b7bf98ab2990d84b0b898507e3c561d6472,144f4ccbd9a74698a88cbf6fd00ad886d339d29ea19448f2c572cac0a07d5562,e6a0ffa3807f09dadbe71e0f4be4725f2832e76cad8dc1d943ce839375eff248,837b8e68d4917544764ad0903cb11f8615d2823cefbb06d89049dbabc69befda,,,195f005c7f80f6252418e1f0b41b8da0d7cd189352723e26bc317c6b8a1009e7,7c8471972b6e8abb89b52f6fc34ee079ea2d7dc31044f9276fb6245339640c55,,,case0:ok;case1:ok;case2:bad[non_square(s)];case3:info[v=0]&bad[non_square(s)];case4:ok;case5:ok;case6:bad[non_square(s)];case7:info[v=0]&bad[non_square(s)]
+b682f3d03bbb5dee4f54b5ebfba931b4f52f6a191e5c2f483c73c66e9ace97e1,904717bf0bc0cb7873fcdc38aa97f19e3a62630972acff92b24cc6dda197cb96,,,,,,,,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:bad[non_square(s)];case3:bad[non_square(s)];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:bad[non_square(s)];case7:bad[non_square(s)]
+c17ec69e665f0fb0dbab48d9c2f94d12ec8a9d7eacb58084833091801eb0b80b,147756e66d96e31c426d3cc85ed0c4cfbef6341dd8b285585aa574ea0204b55e,6f4aea431a0043bdd03134d6d9159119ce034b88c32e50e8e36c4ee45eac7ae9,fd5be16d4ffa2690126c67c3ef7cb9d29b74d397c78b06b3605fda34dc9696a6,5e9c60792a2f000e45c6250f296f875e174efc0e9703e628706103a9dd2d82c7,,90b515bce5ffbc422fcecb2926ea6ee631fcb4773cd1af171c93b11aa1538146,02a41e92b005d96fed93983c1083462d648b2c683874f94c9fa025ca23696589,a1639f86d5d0fff1ba39daf0d69078a1e8b103f168fc19d78f9efc5522d27968,,case0:ok;case1:ok;case2:info[q=0]&info[X=0]&ok;case3:info[q=0]&bad[r=0];case4:ok;case5:ok;case6:info[q=0]&info[X=0]&ok;case7:info[q=0]&bad[r=0]
+c25172fc3f29b6fc4a1155b8575233155486b27464b74b8b260b499a3f53cb14,1ea9cbdb35cf6e0329aa31b0bb0a702a65123ed008655a93b7dcd5280e52e1ab,,,7422edc7843136af0053bb8854448a8299994f9ddcefd3a9a92d45462c59298a,78c7774a266f8b97ea23d05d064f033c77319f923f6b78bce4e20bf05fa5398d,,,8bdd12387bcec950ffac4477abbb757d6666b06223102c5656d2bab8d3a6d2a5,873888b5d990746815dc2fa2f9b0fcc388ce606dc09487431b1df40ea05ac2a2,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:ok;case3:ok;case4:bad[non_square(s)];case5:bad[non_square(s)];case6:ok;case7:ok
+cab6626f832a4b1280ba7add2fc5322ff011caededf7ff4db6735d5026dc0367,2b2bef0852c6f7c95d72ac99a23802b875029cd573b248d1f1b3fc8033788eb6,,,,,,,,,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:info[v=0]&bad[non_square(s)];case3:bad[non_square(s)];case4:bad[non_square(s)];case5:bad[non_square(s)];case6:info[v=0]&bad[non_square(s)];case7:bad[non_square(s)]
+d8621b4ffc85b9ed56e99d8dd1dd24aedcecb14763b861a17112dc771a104fd2,812cabe972a22aa67c7da0c94d8a936296eb9949d70c37cb2b2487574cb3ce58,fbc5febc6fdbc9ae3eb88a93b982196e8b6275a6d5a73c17387e000c711bd0e3,8724c96bd4e5527f2dd195a51c468d2d211ba2fac7cbe0b4b3434253409fb42d,,,043a014390243651c147756c467de691749d8a592a58c3e8c781fff28ee42b4c,78db36942b1aad80d22e6a5ae3b972d2dee45d0538341f4b4cbcbdabbf604802,,,case0:ok;case1:ok;case2:bad[non_square(s)];case3:bad[non_square(s)];case4:ok;case5:ok;case6:bad[non_square(s)];case7:bad[non_square(s)]
+da463164c6f4bf7129ee5f0ec00f65a675a8adf1bd931b39b64806afdcda9a22,25b9ce9b390b408ed611a0f13ff09a598a57520e426ce4c649b7f94f2325620d,,,,,,,,,case0:bad[non_square(s)];case1:info[v=0]&bad[non_square(s)];case2:bad[non_square(s)];case3:bad[non_square(s)];case4:bad[non_square(s)];case5:info[v=0]&bad[non_square(s)];case6:bad[non_square(s)];case7:bad[non_square(s)]
+dafc971e4a3a7b6dcfb42a08d9692d82ad9e7838523fcbda1d4827e14481ae2d,250368e1b5c58492304bd5f72696d27d526187c7adc03425e2b7d81dbb7e4e02,,,370c28f1be665efacde6aa436bf86fe21e6e314c1e53dd040e6c73a46b4c8c49,cd8acee98ffe56531a84d7eb3e48fa4034206ce825ace907d0edf0eaeb5e9ca2,,,c8f3d70e4199a105321955bc9407901de191ceb3e1ac22fbf1938c5a94b36fe6,327531167001a9ace57b2814c1b705bfcbdf9317da5316f82f120f1414a15f8d,case0:bad[non_square(s)];case1:info[v=0]&bad[non_square(s)];case2:ok;case3:ok;case4:bad[non_square(s)];case5:info[v=0]&bad[non_square(s)];case6:ok;case7:ok
+e0294c8bc1a36b4166ee92bfa70a5c34976fa9829405efea8f9cd54dcb29b99e,ae9690d13b8d20a0fbbf37bed8474f67a04e142f56efd78770a76b359165d8a1,,,dcd45d935613916af167b029058ba3a700d37150b9df34728cb05412c16d4182,,,,232ba26ca9ec6e950e984fd6fa745c58ff2c8eaf4620cb8d734fabec3e92baad,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:info[q=0]&info[X=0]&ok;case3:info[q=0]&bad[r=0];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:info[q=0]&info[X=0]&ok;case7:info[q=0]&bad[r=0]
+e148441cd7b92b8b0e4fa3bd68712cfd0d709ad198cace611493c10e97f5394e,164a639794d74c53afc4d3294e79cdb3cd25f99f6df45c000f758aba54d699c0,,,,,,,,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:bad[non_square(s)];case3:info[v=0]&bad[non_square(s)];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:bad[non_square(s)];case7:info[v=0]&bad[non_square(s)]
+e4b00ec97aadcca97644d3b0c8a931b14ce7bcf7bc8779546d6e35aa5937381c,94e9588d41647b3fcc772dc8d83c67ce3be003538517c834103d2cd49d62ef4d,c88d25f41407376bb2c03a7fffeb3ec7811cc43491a0c3aac0378cdc78357bee,51c02636ce00c2345ecd89adb6089fe4d5e18ac924e3145e6669501cd37a00d4,205b3512db40521cb200952e67b46f67e09e7839e0de44004138329ebd9138c5,58aab390ab6fb55c1d1b80897a207ce94a78fa5b4aa61a33398bcae9adb20d3e,3772da0bebf8c8944d3fc5800014c1387ee33bcb6e5f3c553fc8732287ca8041,ae3fd9c931ff3dcba132765249f7601b2a1e7536db1ceba19996afe22c85fb5b,dfa4caed24bfade34dff6ad1984b90981f6187c61f21bbffbec7cd60426ec36a,a7554c6f54904aa3e2e47f7685df8316b58705a4b559e5ccc6743515524deef1,case0:ok;case1:ok;case2:ok;case3:info[v=0]&ok;case4:ok;case5:ok;case6:ok;case7:info[v=0]&ok
+e5bbb9ef360d0a501618f0067d36dceb75f5be9a620232aa9fd5139d0863fde5,e5bbb9ef360d0a501618f0067d36dceb75f5be9a620232aa9fd5139d0863fde5,,,,,,,,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:bad[s=0];case3:bad[s=0];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:bad[s=0];case7:bad[s=0]
+e6bcb5c3d63467d490bfa54fbbc6092a7248c25e11b248dc2964a6e15edb1457,19434a3c29cb982b6f405ab04439f6d58db73da1ee4db723d69b591da124e7d8,67119877832ab8f459a821656d8261f544a553b89ae4f25c52a97134b70f3426,ffee02f5e649c07f0560eff1867ec7b32d0e595e9b1c0ea6e2a4fc70c97cd71f,b5e0c189eb5b4bacd025b7444d74178be8d5246cfa4a9a207964a057ee969992,5746e4591bf7f4c3044609ea372e908603975d279fdef8349f0b08d32f07619d,98ee67887cd5470ba657de9a927d9e0abb5aac47651b0da3ad568eca48f0c809,0011fd0a19b63f80fa9f100e7981384cd2f1a6a164e3f1591d5b038e36832510,4a1f3e7614a4b4532fda48bbb28be874172adb9305b565df869b5fa71169629d,a8b91ba6e4080b3cfbb9f615c8d16f79fc68a2d8602107cb60f4f72bd0f89a92,case0:ok;case1:info[v=0]&ok;case2:ok;case3:ok;case4:ok;case5:info[v=0]&ok;case6:ok;case7:ok
+f28fba64af766845eb2f4302456e2b9f8d80affe57e7aae42738d7cddb1c2ce6,f28fba64af766845eb2f4302456e2b9f8d80affe57e7aae42738d7cddb1c2ce6,4f867ad8bb3d840409d26b67307e62100153273f72fa4b7484becfa14ebe7408,5bbc4f59e452cc5f22a99144b10ce8989a89a995ec3cea1c91ae10e8f721bb5d,,,b079852744c27bfbf62d9498cf819deffeacd8c08d05b48b7b41305db1418827,a443b0a61bad33a0dd566ebb4ef317676576566a13c315e36e51ef1608de40d2,,,case0:ok;case1:ok;case2:bad[s=0];case3:bad[s=0];case4:ok;case5:ok;case6:bad[s=0];case7:bad[s=0]
+f455605bc85bf48e3a908c31023faf98381504c6c6d3aeb9ede55f8dd528924d,d31fbcd5cdb798f6c00db6692f8fe8967fa9c79dd10958f4a194f01374905e99,,,0c00c5715b56fe632d814ad8a77f8e66628ea47a6116834f8c1218f3a03cbd50,df88e44fac84fa52df4d59f48819f18f6a8cd4151d162afaf773166f57c7ff46,,,f3ff3a8ea4a9019cd27eb527588071999d715b859ee97cb073ede70b5fc33edf,20771bb0537b05ad20b2a60b77e60e7095732beae2e9d505088ce98fa837fce9,case0:bad[non_square(s)];case1:bad[non_square(s)];case2:info[v=0]&ok;case3:ok;case4:bad[non_square(s)];case5:bad[non_square(s)];case6:info[v=0]&ok;case7:ok
+f58cd4d9830bad322699035e8246007d4be27e19b6f53621317b4f309b3daa9d,78ec2b3dc0948de560148bbc7c6dc9633ad5df70a5a5750cbed721804f082a3b,6c4c580b76c7594043569f9dae16dc2801c16a1fbe12860881b75f8ef929bce5,94231355e7385c5f25ca436aa64191471aea4393d6e86ab7a35fe2afacaefd0d,dff2a1951ada6db574df834048149da3397a75b829abf58c7e69db1b41ac0989,a52b66d3c907035548028bf804711bf422aba95f1a666fc86f4648e05f29caae,93b3a7f48938a6bfbca9606251e923d7fe3e95e041ed79f77e48a07006d63f4a,6bdcecaa18c7a3a0da35bc9559be6eb8e515bc6c291795485ca01d4f5350ff22,200d5e6ae525924a8b207cbfb7eb625cc6858a47d6540a73819624e3be53f2a6,5ad4992c36f8fcaab7fd7407fb8ee40bdd5456a0e599903790b9b71ea0d63181,case0:ok;case1:ok;case2:info[v=0]&ok;case3:ok;case4:ok;case5:ok;case6:info[v=0]&ok;case7:ok
+fd7d912a40f182a3588800d69ebfb5048766da206fd7ebc8d2436c81cbef6421,8d37c862054debe731694536ff46b273ec122b35a9bf1445ac3c4ff9f262c952,,,,,,,,,case0:bad[valid_x(-x-u)];case1:bad[valid_x(-x-u)];case2:info[v=0]&bad[non_square(s)];case3:bad[non_square(s)];case4:bad[valid_x(-x-u)];case5:bad[valid_x(-x-u)];case6:info[v=0]&bad[non_square(s)];case7:bad[non_square(s)]
