musig2
Copyright(c) 2025 Jose Storopoli
LicenseMIT
MaintainerJose Storopoli <jose@storopoli.com>
Safe HaskellNone
LanguageHaskell2010

Crypto.Curve.Secp256k1.MuSig2

Description

BIP-327 MuSig2 multi-signatures on secp256k1: \(n\) signers produce one ordinary BIP-340 Schnorr signature for their aggregate public key, in two rounds.

  1. Key aggregation: everyone runs keyAgg on the same list of public keys (optionally sorted with keySort) and applies the same tweaks, e.g. applyTaprootTweak.
  2. Round one: each signer runs nonceGen and sends its PubNonce to the others (or to a coordinator), who aggregate them with nonceAgg.
  3. Round two: everyone opens the same Session with newSession; each signer runs sign once (it consumes the secret nonce) and sends its PartialSignature.
  4. The aggregator checks each partial signature with partialSigVerify and combines them with partialSigAgg. Anyone can check the result with verify against aggXOnlyPubKey.

Crypto.Curve.Secp256k1.MuSig2.Coordinator runs both rounds for a coordinator that receives the contributions as bytes: it decodes and verifies each one and blames the signer of an invalid, conflicting or missing one.

Values sent between signers are encoded and decoded with Encode, in the BIP-327 byte formats. Decoding validates: every value of a type exported here is valid by construction.

Security considerations

  • Each nonce signs once. Signing twice with the same secret nonce, in any two sessions, lets the other signers compute your secret key. A SecNonce from nonceGen is one-shot: sign atomically marks it used before doing anything else, so a second sign with it (or with any copy of it, from any thread) returns SecNonceAlreadyUsed. A failed sign uses the nonce up too: after any SignError, generate a new nonce and start again from round one. SecNonce cannot be encoded, shown, compared or rebuilt from its parts, and nonceGen always draws fresh randomness. Crypto.Curve.Secp256k1.MuSig2.Unsafe has the escape hatches (caller-supplied randomness, counters, export and import of secret nonces) that this protection cannot cover.
  • Bind nonces to the session when you can. If the aggregate key or the message is known in round one, pass them to nonceGen (see NonceInputs): sign then refuses any other session (SecNonceSessionMismatch), and they add protection should the random number generator fail.
  • Signers without randomness can use deterministicSign (BIP-327 DeterministicSign) if they are the last to send their public nonce, after receiving everyone else's.
  • Verify partial signatures. partialSigAgg does not check its inputs; run partialSigVerify on every partial signature you did not make, so a wrong one is attributed to its signer instead of producing an invalid signature (Crypto.Curve.Secp256k1.MuSig2.Coordinator does this). sign checks its own result.
  • Bound the size of untrusted messages. BIP-327 allows messages of any length. No function copies a long message or extra input to hash it, but each one holds the whole message in memory, so if messages come from untrusted parties, cap their size before passing them in.
  • Constant-time arithmetic on secrets. Secret keys and nonces are never held in an Integer. They are parsed, range-checked, reduced from hashes, combined (\(k_1 + b k_2\) and \(k + e a d\) in sign), negated and encoded with the fixed-width, constant-time Montgomery arithmetic of ppad-fixed, and multiplied with the generator by ppad-secp256k1's timing-safe wNAF. Caveats:

    • Public values (key aggregation coefficients, nonce coefficients, challenges, tweaks, partial signatures, public keys and nonces) use variable-time Integer arithmetic and curve operations, by design.
    • Constant time is a property of the machine code, which GHC does not guarantee. The Haskell code has no branch or memory access that depends on a secret (checked in GHC Core); with the llvm flag on x86_64, LLVM's conversion of conditional moves into branches is disabled, as in ppad-fixed and ppad-secp256k1. Other code generators and architectures are not audited.
  • Zeroization is best-effort. The scalars of a SecNonce live in a pinned buffer (which the garbage collector never copies) that sign zero-fills when it consumes the nonce. Everything else is an ordinary Haskell value that is not wiped and may be copied by the garbage collector: secret keys, the intermediate values computed from the nonce while signing (fixed-width words, but still heap values), and the buffer of a nonce that is dropped without being used.
  • Randomness. nonceGen reads 32 bytes from the operating system's random number generator (getrandom on Linux, via the entropy package). Passing the optional NonceInputs adds protection should it fail.

Usage

Two signers (this example is compiled and run by the test suite; it needs the OverloadedStrings language extension):

import Control.Exception (Exception, throwIO)
import qualified Crypto.Curve.Secp256k1.MuSig2 as MuSig2
import qualified Data.ByteString as BS
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
-- | Throws the error of a 'Left'.
orThrow :: (Exception e) => Either e a -> IO a
orThrow = either throwIO pure

-- | Two signers sign a message; returns whether the signature verifies.
example :: IO Bool
example = do
  -- Each signer has a secret key and publishes its public key.
  -- (Fixed keys for the example only: never hard-code real keys.)
  sk1 <- orThrow (MuSig2.secKeyFromBytes (BS.replicate 32 0x11))
  sk2 <- orThrow (MuSig2.secKeyFromBytes (BS.replicate 32 0x22))
  let pk1 = MuSig2.secKeyPubKey sk1
      pk2 = MuSig2.secKeyPubKey sk2

  -- Everyone aggregates the same list of public keys, here sorted.
  keyAggCtx <- orThrow (MuSig2.keyAgg (MuSig2.keySort (pk1 :| [pk2])))
  let aggKey = MuSig2.aggXOnlyPubKey keyAggCtx
      msg = "i approve of this message"

  -- Each signer generates a fresh nonce and publishes the public part.
  (secNonce1, pubNonce1) <- MuSig2.nonceGen pk1 MuSig2.noNonceInputs >>= orThrow
  (secNonce2, pubNonce2) <- MuSig2.nonceGen pk2 MuSig2.noNonceInputs >>= orThrow

  -- Values travel as bytes; decoding validates them.
  received <- orThrow (MuSig2.decode (MuSig2.encode pubNonce2))

  -- Everyone aggregates the public nonces and opens the same session.
  let session = MuSig2.newSession keyAggCtx (MuSig2.nonceAgg (pubNonce1 :| [received])) msg

  -- Each signer signs once with its nonce and publishes its partial signature.
  -- 'sign' consumes the secret nonce: signing again with it fails.
  psig1 <- MuSig2.sign secNonce1 sk1 session >>= orThrow
  psig2 <- MuSig2.sign secNonce2 sk2 session >>= orThrow

  -- The aggregator checks each partial signature, then aggregates them.
  let valid =
        MuSig2.partialSigVerify session pk1 pubNonce1 psig1
          && MuSig2.partialSigVerify session pk2 pubNonce2 psig2
      signature = MuSig2.partialSigAgg session (psig1 :| [psig2])

  -- The result is an ordinary BIP-340 signature for the aggregate key.
  pure (valid && MuSig2.verify aggKey msg signature)

Taproot

A Taproot output key is the aggregate key tweaked with applyTaprootTweak:

-- | Three signers spend a Taproot output by key path.
taprootExample :: IO Bool
taprootExample = do
  sks <- traverse (orThrow . MuSig2.secKeyFromBytes . BS.replicate 32) (0x33 :| [0x44, 0x55])
  let pks = fmap MuSig2.secKeyPubKey sks

  -- The internal key is the aggregate key; the output key commits to the
  -- script tree's merkle root ('Nothing' for a key-path-only output, BIP-86).
  internal <- orThrow (MuSig2.keyAgg (MuSig2.keySort pks))
  output <- orThrow (MuSig2.applyTaprootTweak (Just (BS.replicate 32 0xAB)) internal)
  let outputKey = MuSig2.aggXOnlyPubKey output
      sighash = BS.replicate 32 0x01

  -- Binding the nonces to the key and message adds protection against bad randomness.
  let inputs sk =
        MuSig2.noNonceInputs
          { MuSig2.nonceSecKey = Just sk
          , MuSig2.nonceAggPubKey = Just outputKey
          , MuSig2.nonceMessage = Just sighash
          }
  nonces <- traverse (\sk -> MuSig2.nonceGen (MuSig2.secKeyPubKey sk) (inputs sk) >>= orThrow) sks

  -- Sessions are opened on the tweaked context: the tweak lives in the context only.
  let session = MuSig2.newSession output (MuSig2.nonceAgg (fmap snd nonces)) sighash
  psigs <- traverse (\(sk, (secNonce, _)) -> MuSig2.sign secNonce sk session >>= orThrow) (NE.zip sks nonces)
  let signature = MuSig2.partialSigAgg session psigs
  pure (MuSig2.verify outputKey sighash signature)
Synopsis

Keys

data SecKey Source #

A secret key \(0 < d < n\), with its public key.

The scalar is held as four 64-bit words in Montgomery form, never in an Integer: it is parsed, encoded and computed with in constant time.

Deliberately has no Show, Eq, Ord, Read, Num or Encode instance.

Instances

Instances details
NFData SecKey Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

Methods

rnf :: SecKey -> () #

secKeyFromBytes :: ByteString -> Either DecodeError SecKey Source #

A secret key from 32 big-endian bytes in \([1, n)\). The range check runs in constant time; only its outcome (valid, ScalarZero or ScalarOutOfRange) is revealed.

secKeyToBytes :: SecKey -> ByteString Source #

The 32-byte big-endian encoding of a secret key, in constant time.

secKeyPubKey :: SecKey -> PubKey Source #

The public key \(d \cdot G\) of a secret key.

data PubKey Source #

A public key: a finite point on the curve.

Caches its 33-byte compressed encoding; Eq and Ord compare that encoding (the order is the one BIP-327 KeySort uses), and Show prints it in hex.

pubKeyFromPoint :: Projective -> Either DecodeError PubKey Source #

A PubKey from any point: rejects infinity and points not on the curve.

pubKeyPoint :: PubKey -> Projective Source #

The public key as a ppad-secp256k1 point.

pubKeyXOnly :: PubKey -> XOnlyPubKey Source #

The x-only key of a public key (negated to even y if needed).

Encodings

class Encode a where Source #

Types with a canonical BIP-327 byte encoding.

decode . encode = Right, and decode accepts exactly the canonical encodings: it rejects wrong lengths, invalid points and out-of-range scalars. Secrets have no instance.

Methods

encode :: a -> ByteString Source #

The canonical encoding.

decode :: ByteString -> Either DecodeError a Source #

Parses and validates an encoding.

Key aggregation

data KeyAggContext Source #

The result of key aggregation, plus any tweaks applied since.

Holds the signers' keys in order, each signer's key aggregation coefficient, the (possibly tweaked) aggregate key \(Q\), and the tweak accumulators \(gacc\) and \(tacc\) of BIP-327.

Instances

Instances details
NFData KeyAggContext Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.KeyAgg

Methods

rnf :: KeyAggContext -> () #

keySort :: NonEmpty PubKey -> NonEmpty PubKey Source #

BIP-327 KeySort: sorts keys by their 33-byte encoding.

keyAgg :: NonEmpty PubKey -> Either KeyAggError KeyAggContext Source #

BIP-327 KeyAgg, in \(O(n)\): the key list is hashed once, the second distinct key is found once, each coefficient takes one hash, and keys with coefficient \(1\) are added without a multiplication.

aggPubKey :: KeyAggContext -> PubKey Source #

The aggregate key \(Q\), including the tweaks applied so far.

aggXOnlyPubKey :: KeyAggContext -> XOnlyPubKey Source #

The x-only aggregate key: the key the final signature verifies against.

keyAggPubKeys :: KeyAggContext -> NonEmpty PubKey Source #

The signers' public keys, in the order they were aggregated.

signerIndex :: KeyAggContext -> PubKey -> Maybe Int Source #

The index of a public key among the signers (its first position if it appears more than once).

Tweaks

data Tweak Source #

A tweak \(0 \le t < n\) (zero allowed, as in BIP-327).

Eq, Ord and Show use the 32-byte encoding.

Instances

Instances details
NFData Tweak Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

Methods

rnf :: Tweak -> () #

Show Tweak Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

Methods

showsPrec :: Int -> Tweak -> ShowS #

show :: Tweak -> String #

showList :: [Tweak] -> ShowS #

Eq Tweak Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

Methods

(==) :: Tweak -> Tweak -> Bool #

(/=) :: Tweak -> Tweak -> Bool #

Ord Tweak Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

Methods

compare :: Tweak -> Tweak -> Ordering #

(<) :: Tweak -> Tweak -> Bool #

(<=) :: Tweak -> Tweak -> Bool #

(>) :: Tweak -> Tweak -> Bool #

(>=) :: Tweak -> Tweak -> Bool #

max :: Tweak -> Tweak -> Tweak #

min :: Tweak -> Tweak -> Tweak #

Encode Tweak Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Types

applyPlainTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext Source #

BIP-327 ApplyTweak with a plain tweak: \(Q' = Q + t \cdot G\). Use it for BIP-32 derivation from the aggregate key.

applyXOnlyTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext Source #

BIP-327 ApplyTweak with an x-only tweak: \(Q' = g \cdot Q + t \cdot G\) where \(g = -1\) if \(Q\) has odd \(y\).

applyTaprootTweak :: Maybe ByteString -> KeyAggContext -> Either KeyAggError KeyAggContext Source #

The BIP-341 Taproot tweak: an x-only tweak by \(t = hash_{TapTweak}(xbytes(Q) \| merkle\_root)\) (no merkle root for Nothing).

Nonces

data SecNonce Source #

A secret nonce: two secret scalars \(0 < k_1, k_2 < n\), bound to the signer's public key (and, optionally, to an aggregate key and a message), with the matching public nonce.

The scalars live in a pinned buffer that can be read once: signing (or exporting) the nonce marks it used and zero-fills the buffer. Copies of a tSecNonce share that buffer, so they are used up together.

Deliberately has no Show, Eq, Ord, Encode or other instance that could copy, compare or leak it.

Instances

Instances details
NFData SecNonce Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Nonce

Methods

rnf :: SecNonce -> () #

data PubNonce Source #

A signer's public nonce \((R_1, R_2)\): two finite points.

Eq, Ord and Show use the 66-byte encoding.

data AggNonce Source #

An aggregate nonce \((R_1, R_2)\); either point may be infinity.

Eq, Ord and Show use the 66-byte encoding (infinity as 33 zero bytes).

data NonceInputs Source #

The optional inputs of BIP-327 NonceGen. Each one that is given is hashed into the nonce, as extra protection should the random number generator fail.

Constructors

NonceInputs 

Fields

noNonceInputs :: NonceInputs Source #

No optional inputs: the nonce depends only on fresh randomness and the public key.

nonceGen :: PubKey -> NonceInputs -> IO (Either NonceGenError (SecNonce, PubNonce)) Source #

BIP-327 NonceGen with fresh randomness from the operating system (getrandom on Linux, via the entropy package).

nonceAgg :: NonEmpty PubNonce -> AggNonce Source #

BIP-327 NonceAgg: sums the first and the second points. Either sum may be infinity.

Signing

data Session Source #

A signing session: a key aggregation context, an aggregate nonce and a message, with the BIP-327 session values computed once.

Instances

Instances details
NFData Session Source # 
Instance details

Defined in Crypto.Curve.Secp256k1.MuSig2.Internal.Session

Methods

rnf :: Session -> () #

newSession :: KeyAggContext -> AggNonce -> ByteString -> Session Source #

Starts a signing session (BIP-327 GetSessionValues): computes \(b\), \(R = R_1 + b \cdot R_2\) (or \(G\) if that is infinity) and \(e\).

sessionKeyAgg :: Session -> KeyAggContext Source #

The key aggregation context of a session.

sign :: SecNonce -> SecKey -> Session -> IO (Either SignError PartialSignature) Source #

BIP-327 Sign, followed by PartialSigVerifyInternal on the result as the BIP recommends.

Consumes the secret nonce first, as BIP-327 and libsecp256k1 do: the nonce is atomically marked used and its buffer zero-filled before any check, so every call after the first, through any copy of the SecNonce and from any thread, returns SecNonceAlreadyUsed, and a failed call uses the nonce up too. Then, in order: SecNonceKeyMismatch, SecNonceSessionMismatch (if the nonce was generated with an aggregate key or a message, they must be the session's), SignerNotInSession, and SelfVerificationFailed.

deterministicSign Source #

Arguments

:: SecKey

The signer's secret key.

-> AggNonce

aggothernonce: the aggregate of the other signers' public nonces.

-> KeyAggContext

The key aggregation context, with all tweaks applied.

-> ByteString

The message.

-> Maybe ByteString

Optional auxiliary randomness: 32 bytes.

-> Either SignError (PubNonce, PartialSignature) 

BIP-327 DeterministicSign: signing without a random nonce, for the signer who contributes its nonce last.

Derives the nonce from the secret key, the other signers' aggregate nonce aggothernonce (the nonceAgg of all other signers' public nonces), the (tweaked) aggregate key of the context and the message, and optionally 32 bytes of auxiliary randomness. Returns this signer's public nonce, to send with the partial signature, and the partial signature for the session whose aggregate nonce combines the two.

Safe without randomness only if every other signer's public nonce is fixed before this one is revealed: call it only after receiving all other public nonces, never before. The secret nonce never leaves this function, and the same inputs always give the same output.

Fails with InvalidAuxRandLength, DeterministicNonceIsZero (negligible probability), AggOtherNonceAtInfinity, SignerNotInSession or SelfVerificationFailed.

partialSigVerify :: Session -> PubKey -> PubNonce -> PartialSignature -> Bool Source #

BIP-327 PartialSigVerify for one signer of the session: False if the public key is not one of the session's keys.

Takes no hashing: the session caches \(b\), \(e\) and the coefficients.

partialSigAgg :: Session -> NonEmpty PartialSignature -> Signature Source #

BIP-327 PartialSigAgg: \(s = \sum s_i + e \cdot g \cdot tacc\) with \(g\) from the parity of \(Q\).

Does not check the partial signatures: verify each one with partialSigVerify first, or the result may not be a valid signature.

data Signature Source #

A 64-byte BIP-340 Schnorr signature R.x || s with \(R.x < p\) and \(s < n\).

Eq, Ord and Show use the encoding.

verify :: XOnlyPubKey -> ByteString -> Signature -> Bool Source #

BIP-340 verification of a Schnorr signature.

Errors

data DecodeError Source #

Why a byte string (or a ppad-secp256k1 point) is not a valid value of the requested type.

Constructors

InvalidLength

The input has the wrong length.

Fields

InvalidPoint

Not the encoding of a point on the curve: unknown prefix byte, an x-coordinate that is not below the field size or not on the curve, or (for pubKeyFromPoint) a point that does not satisfy the curve equation.

PointAtInfinity

The point at infinity where a finite point is required.

ScalarOutOfRange

A scalar that is not below the group order \(n\).

ScalarZero

A scalar that must be non-zero (a secret key or nonce) is zero.

data KeyAggError Source #

Key aggregation and tweaking failures.

Constructors

TooManyPublicKeys

More than \(2^{32} - 1\) public keys.

AggPubKeyAtInfinity

The aggregate public key is the point at infinity (the keys cancel out).

TweakResultAtInfinity

Applying a tweak gave the point at infinity.

TaprootTweakOutOfRange

The BIP-341 Taproot tweak hash is not below the group order (negligible probability).

InvalidMerkleRootLength !Int

The Taproot merkle root is not 32 bytes; carries the actual length.

data NonceGenError Source #

Nonce generation failures. nonceGen fails only for invalid inputs; the last two constructors come from the functions of Crypto.Curve.Secp256k1.MuSig2.Unsafe.

Constructors

NonceSecKeyMismatch

The optional secret key does not belong to the signer's public key.

NonceExtraInputTooLong

The extra input is longer than \(2^{32} - 1\) bytes.

NonceMessageTooLong

The message is longer than \(2^{64} - 1\) bytes (BIP-327's limit; a ByteString cannot be that long on 64-bit platforms).

InvalidRandLength !Int

The random bytes are not 32 bytes long; carries the actual length.

NonceIsZero

A derived nonce scalar is zero, so no nonce exists for these inputs. Happens with negligible probability (a hash would have to be \(0\) or \(n\)); nonceGen draws again instead.

data SignError Source #

Signing failures.

sign consumes the secret nonce before any check, so after any of these errors the nonce is used up: generate a new one and start again from the first round.

Constructors

SecNonceAlreadyUsed

The secret nonce was already used, by an earlier sign or an export.

SecNonceKeyMismatch

The secret nonce was generated for a different public key than the secret key's.

SecNonceSessionMismatch

The secret nonce was generated with an aggregate public key or a message (in NonceInputs) that differs from the session's aggXOnlyPubKey or message.

SignerNotInSession

The secret key's public key is not one of the session's public keys.

SelfVerificationFailed

The partial signature did not pass verification before being returned (a bug or a fault, e.g. a bit flip).

InvalidAuxRandLength !Int

deterministicSign: the auxiliary randomness is not 32 bytes long; carries the actual length.

DeterministicNonceIsZero

deterministicSign: a derived nonce scalar is zero. Happens with negligible probability (a hash would have to be \(0\) or \(n\)).

AggOtherNonceAtInfinity

deterministicSign: a half of the other signers' aggregate nonce is the point at infinity. BIP-327 parses it as a public nonce, so it rejects this and blames the nonce aggregator.