{- |
Module: Crypto.Curve.Secp256k1.MuSig2.Internal.Session
Copyright: (c) 2025 Jose Storopoli
License: MIT
Maintainer: Jose Storopoli <jose@storopoli.com>

BIP-327 signing sessions: @GetSessionValues@, @Sign@, @DeterministicSign@,
@PartialSigVerify@ and @PartialSigAgg@, plus BIP-340 verification of the
final signature.

Not part of the public API.
-}
module Crypto.Curve.Secp256k1.MuSig2.Internal.Session (
  Session (..),
  newSession,
  sessionKeyAgg,
  sign,
  signWithoutVerification,
  deterministicSign,
  partialSigVerify,
  partialSigVerifyWith,
  partialSigAgg,
  verify,
) where

import Control.DeepSeq (NFData (..), ($!!))
import Control.Monad (when)
import Crypto.Curve.Secp256k1 (add, neg, serialize_point, verify_schnorr', _CURVE_G)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Error (SignError (..))
import Crypto.Curve.Secp256k1.MuSig2.Internal.Hash (hashChallenge, hashNonceCoef)
import Crypto.Curve.Secp256k1.MuSig2.Internal.KeyAgg (KeyAggContext (..), aggXOnlyPubKey, keyAggCoefficient)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Nonce (
  SecNonce,
  claimSecNonce,
  deterministicNonceScalars,
  pubNonceFromScalars,
  secNonceAggPubKey,
  secNonceMessage,
  secNoncePubKey,
  secNoncePubNonce,
 )
import Crypto.Curve.Secp256k1.MuSig2.Internal.Point (gContext, hasEvenYBytes, isInfinity, mulGPublic, mulPublic)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Scalar (SecScalar, curveOrder, hashToScalar, integerToBytes32, modQ, signScalar)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Types (
  AggNonce (..),
  PartialSignature (..),
  PubKey (..),
  PubNonce (..),
  SecKey (..),
  Signature (..),
  XOnlyPubKey (..),
  mkAggNonce,
  pubKeyHasEvenY,
 )
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Foldable (for_)
import Data.List.NonEmpty (NonEmpty)

{- | A signing session: a key aggregation context, an aggregate nonce and a
message, with the BIP-327 session values computed once.
-}
data Session = Session
  { Session -> KeyAggContext
sesKeyAgg :: !KeyAggContext
  -- ^ Key aggregation context (with tweaks).
  , Session -> AggNonce
sesAggNonce :: !AggNonce
  -- ^ Aggregate nonce.
  , Session -> ByteString
sesMessage :: !ByteString
  -- ^ Message.
  , Session -> Integer
sesB :: !Integer
  -- ^ Nonce coefficient \(b\).
  , Session -> ByteString
sesRx :: !ByteString
  -- ^ \(xbytes(R)\) of the final nonce \(R\).
  , Session -> Bool
sesREven :: !Bool
  -- ^ \(R\) has even \(y\).
  , Session -> Integer
sesE :: !Integer
  -- ^ Challenge \(e\).
  , Session -> Bool
sesQEven :: !Bool
  -- ^ \(Q\) has even \(y\) (\(g = 1\)).
  }

instance NFData Session where
  rnf :: Session -> ()
rnf (Session KeyAggContext
k AggNonce
a ByteString
m Integer
b ByteString
rx Bool
re Integer
e Bool
qe) = KeyAggContext -> ()
forall a. NFData a => a -> ()
rnf KeyAggContext
k () -> () -> ()
forall a b. a -> b -> b
`seq` AggNonce -> ()
forall a. NFData a => a -> ()
rnf AggNonce
a () -> () -> ()
forall a b. a -> b -> b
`seq` ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
m () -> () -> ()
forall a b. a -> b -> b
`seq` Integer -> ()
forall a. NFData a => a -> ()
rnf Integer
b () -> () -> ()
forall a b. a -> b -> b
`seq` ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
rx () -> () -> ()
forall a b. a -> b -> b
`seq` Bool -> ()
forall a. NFData a => a -> ()
rnf Bool
re () -> () -> ()
forall a b. a -> b -> b
`seq` Integer -> ()
forall a. NFData a => a -> ()
rnf Integer
e () -> () -> ()
forall a b. a -> b -> b
`seq` Bool -> ()
forall a. NFData a => a -> ()
rnf Bool
qe

{- | Starts a signing session (BIP-327 @GetSessionValues@): computes \(b\),
\(R = R_1 + b \cdot R_2\) (or \(G\) if that is infinity) and \(e\).
-}
newSession :: KeyAggContext -> AggNonce -> ByteString -> Session
newSession :: KeyAggContext -> AggNonce -> ByteString -> Session
newSession KeyAggContext
ctx AggNonce
aggNonce ByteString
msg =
  Session
    { sesKeyAgg :: KeyAggContext
sesKeyAgg = KeyAggContext
ctx
    , sesAggNonce :: AggNonce
sesAggNonce = AggNonce
aggNonce
    , sesMessage :: ByteString
sesMessage = ByteString
msg
    , sesB :: Integer
sesB = Integer
b
    , sesRx :: ByteString
sesRx = Int -> ByteString -> ByteString
BS.drop Int
1 ByteString
rBytes
    , sesREven :: Bool
sesREven = ByteString -> Bool
hasEvenYBytes ByteString
rBytes
    , sesE :: Integer
sesE = ByteString -> Integer
hashToScalar ([ByteString] -> ByteString
hashChallenge [Int -> ByteString -> ByteString
BS.drop Int
1 ByteString
rBytes, ByteString
qx, ByteString
msg])
    , sesQEven :: Bool
sesQEven = PubKey -> Bool
pubKeyHasEvenY PubKey
q
    }
 where
  q :: PubKey
q = KeyAggContext -> PubKey
kacQ KeyAggContext
ctx
  qx :: ByteString
qx = Int -> ByteString -> ByteString
BS.drop Int
1 (PubKey -> ByteString
pubKeyBytes PubKey
q)
  b :: Integer
b = ByteString -> Integer
hashToScalar ([ByteString] -> ByteString
hashNonceCoef [AggNonce -> ByteString
aggNonceBytes AggNonce
aggNonce, ByteString
qx, ByteString
msg])
  r' :: Projective
r' = Projective -> Projective -> Projective
add (AggNonce -> Projective
aggNonceR1 AggNonce
aggNonce) (Projective -> Integer -> Projective
mulPublic (AggNonce -> Projective
aggNonceR2 AggNonce
aggNonce) Integer
b)
  r :: Projective
r = if Projective -> Bool
isInfinity Projective
r' then Projective
_CURVE_G else Projective
r'
  rBytes :: ByteString
rBytes = Projective -> ByteString
serialize_point Projective
r

-- | The key aggregation context of a session.
sessionKeyAgg :: Session -> KeyAggContext
sessionKeyAgg :: Session -> KeyAggContext
sessionKeyAgg = Session -> KeyAggContext
sesKeyAgg

-- | \(g \cdot gacc = -1\): the secret key (and the signer's key in verification) is negated.
negatesKey :: Session -> Bool
negatesKey :: Session -> Bool
negatesKey Session
ses = Bool -> Bool
not (Session -> Bool
sesQEven Session
ses) Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= KeyAggContext -> Bool
kacGaccNeg (Session -> KeyAggContext
sesKeyAgg Session
ses)

{- | 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 t'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'.
-}
sign :: SecNonce -> SecKey -> Session -> IO (Either SignError PartialSignature)
sign :: SecNonce
-> SecKey -> Session -> IO (Either SignError PartialSignature)
sign = Bool
-> SecNonce
-> SecKey
-> Session
-> IO (Either SignError PartialSignature)
signNonce Bool
True

{- | 'sign' without the verification of the result: a fault during signing
(e.g. a bit flip) may then go unnoticed, and a faulty partial signature can
leak the secret key.
-}
signWithoutVerification :: SecNonce -> SecKey -> Session -> IO (Either SignError PartialSignature)
signWithoutVerification :: SecNonce
-> SecKey -> Session -> IO (Either SignError PartialSignature)
signWithoutVerification = Bool
-> SecNonce
-> SecKey
-> Session
-> IO (Either SignError PartialSignature)
signNonce Bool
False

-- | Consumes the nonce, checks its binding and signs.
signNonce :: Bool -> SecNonce -> SecKey -> Session -> IO (Either SignError PartialSignature)
signNonce :: Bool
-> SecNonce
-> SecKey
-> Session
-> IO (Either SignError PartialSignature)
signNonce Bool
verifyResult SecNonce
sn SecKey
sk Session
ses = do
  claimed <- SecNonce -> IO (Maybe (SecScalar, SecScalar))
claimSecNonce SecNonce
sn
  pure $!! case claimed of
    Maybe (SecScalar, SecScalar)
Nothing -> SignError -> Either SignError PartialSignature
forall a b. a -> Either a b
Left SignError
SecNonceAlreadyUsed
    Just (SecScalar
k1, SecScalar
k2) -> do
      Bool -> Either SignError () -> Either SignError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (SecNonce -> PubKey
secNoncePubKey SecNonce
sn PubKey -> PubKey -> Bool
forall a. Eq a => a -> a -> Bool
/= SecKey -> PubKey
secKeyPub SecKey
sk) (SignError -> Either SignError ()
forall a b. a -> Either a b
Left SignError
SecNonceKeyMismatch)
      Bool -> Either SignError () -> Either SignError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((XOnlyPubKey -> Bool) -> Maybe XOnlyPubKey -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (XOnlyPubKey -> XOnlyPubKey -> Bool
forall a. Eq a => a -> a -> Bool
/= KeyAggContext -> XOnlyPubKey
aggXOnlyPubKey (Session -> KeyAggContext
sesKeyAgg Session
ses)) (SecNonce -> Maybe XOnlyPubKey
secNonceAggPubKey SecNonce
sn) Bool -> Bool -> Bool
|| (ByteString -> Bool) -> Maybe ByteString -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= Session -> ByteString
sesMessage Session
ses) (SecNonce -> Maybe ByteString
secNonceMessage SecNonce
sn)) (Either SignError () -> Either SignError ())
-> Either SignError () -> Either SignError ()
forall a b. (a -> b) -> a -> b
$
        SignError -> Either SignError ()
forall a b. a -> Either a b
Left SignError
SecNonceSessionMismatch
      Bool
-> SecScalar
-> SecScalar
-> PubNonce
-> SecKey
-> Session
-> Either SignError PartialSignature
signScalars Bool
verifyResult SecScalar
k1 SecScalar
k2 (SecNonce -> PubNonce
secNoncePubNonce SecNonce
sn) SecKey
sk Session
ses

{- | BIP-327 @Sign@ with the nonce scalars \(k_1, k_2\) (in \([1, n)\)) and
the matching public nonce, for a nonce bound to the secret key's public key.
-}
signScalars :: Bool -> SecScalar -> SecScalar -> PubNonce -> SecKey -> Session -> Either SignError PartialSignature
signScalars :: Bool
-> SecScalar
-> SecScalar
-> PubNonce
-> SecKey
-> Session
-> Either SignError PartialSignature
signScalars Bool
verifyResult SecScalar
k1 SecScalar
k2 PubNonce
pn SecKey
sk Session
ses = case KeyAggContext -> PubKey -> Maybe Integer
keyAggCoefficient (Session -> KeyAggContext
sesKeyAgg Session
ses) PubKey
pk of
  Maybe Integer
Nothing -> SignError -> Either SignError PartialSignature
forall a b. a -> Either a b
Left SignError
SignerNotInSession
  Just Integer
a
    | Bool -> Bool
not Bool
verifyResult Bool -> Bool -> Bool
|| Session
-> Integer -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerifyWith Session
ses Integer
a PubKey
pk PubNonce
pn PartialSignature
psig -> PartialSignature -> Either SignError PartialSignature
forall a b. b -> Either a b
Right PartialSignature
psig
    | Bool
otherwise -> SignError -> Either SignError PartialSignature
forall a b. a -> Either a b
Left SignError
SelfVerificationFailed
   where
    s :: Integer
s = SecScalar
-> SecScalar
-> SecScalar
-> Bool
-> Bool
-> Integer
-> Integer
-> Integer
signScalar SecScalar
k1 SecScalar
k2 (SecKey -> SecScalar
secKeyScalar SecKey
sk) (Bool -> Bool
not (Session -> Bool
sesREven Session
ses)) (Session -> Bool
negatesKey Session
ses) (Session -> Integer
sesB Session
ses) (Integer -> Integer
modQ (Session -> Integer
sesE Session
ses Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
a))
    psig :: PartialSignature
psig = Integer -> PartialSignature
PartialSignature Integer
s
 where
  pk :: PubKey
pk = SecKey -> PubKey
secKeyPub SecKey
sk

{- | 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 'Crypto.Curve.Secp256k1.MuSig2.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'.
-}
deterministicSign ::
  -- | The signer's secret key.
  SecKey ->
  -- | @aggothernonce@: the aggregate of the other signers' public nonces.
  AggNonce ->
  -- | The key aggregation context, with all tweaks applied.
  KeyAggContext ->
  -- | The message.
  ByteString ->
  -- | Optional auxiliary randomness: 32 bytes.
  Maybe ByteString ->
  Either SignError (PubNonce, PartialSignature)
deterministicSign :: SecKey
-> AggNonce
-> KeyAggContext
-> ByteString
-> Maybe ByteString
-> Either SignError (PubNonce, PartialSignature)
deterministicSign SecKey
sk AggNonce
aggOther KeyAggContext
ctx ByteString
msg Maybe ByteString
rand = do
  Maybe ByteString
-> (ByteString -> Either SignError ()) -> Either SignError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ Maybe ByteString
rand ((ByteString -> Either SignError ()) -> Either SignError ())
-> (ByteString -> Either SignError ()) -> Either SignError ()
forall a b. (a -> b) -> a -> b
$ \ByteString
r -> Bool -> Either SignError () -> Either SignError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Int
BS.length ByteString
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32) (SignError -> Either SignError ()
forall a b. a -> Either a b
Left (Int -> SignError
InvalidAuxRandLength (ByteString -> Int
BS.length ByteString
r)))
  let (SecScalar
k1, SecScalar
k2) = SecKey
-> AggNonce
-> XOnlyPubKey
-> ByteString
-> Maybe ByteString
-> (SecScalar, SecScalar)
deterministicNonceScalars SecKey
sk AggNonce
aggOther (KeyAggContext -> XOnlyPubKey
aggXOnlyPubKey KeyAggContext
ctx) ByteString
msg Maybe ByteString
rand
  pn <- Either SignError PubNonce
-> (PubNonce -> Either SignError PubNonce)
-> Maybe PubNonce
-> Either SignError PubNonce
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (SignError -> Either SignError PubNonce
forall a b. a -> Either a b
Left SignError
DeterministicNonceIsZero) PubNonce -> Either SignError PubNonce
forall a b. b -> Either a b
Right (SecScalar -> SecScalar -> Maybe PubNonce
pubNonceFromScalars SecScalar
k1 SecScalar
k2)
  -- NonceAgg((pubnonce, aggothernonce)) parses aggothernonce as a public nonce.
  when (isInfinity (aggNonceR1 aggOther) || isInfinity (aggNonceR2 aggOther)) (Left AggOtherNonceAtInfinity)
  let aggNonce = Projective -> Projective -> AggNonce
mkAggNonce (Projective -> Projective -> Projective
add (PubNonce -> Projective
pubNonceR1 PubNonce
pn) (AggNonce -> Projective
aggNonceR1 AggNonce
aggOther)) (Projective -> Projective -> Projective
add (PubNonce -> Projective
pubNonceR2 PubNonce
pn) (AggNonce -> Projective
aggNonceR2 AggNonce
aggOther))
  psig <- signScalars True k1 k2 pn sk (newSession ctx aggNonce msg)
  Right (pn, psig)

{- | 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.
-}
partialSigVerify :: Session -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerify :: Session -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerify Session
ses PubKey
pk PubNonce
pn PartialSignature
psig = case KeyAggContext -> PubKey -> Maybe Integer
keyAggCoefficient (Session -> KeyAggContext
sesKeyAgg Session
ses) PubKey
pk of
  Maybe Integer
Nothing -> Bool
False
  Just Integer
a -> Session
-> Integer -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerifyWith Session
ses Integer
a PubKey
pk PubNonce
pn PartialSignature
psig

{- | @PartialSigVerifyInternal@ with the signer's key aggregation coefficient:
\(s \cdot G = R_e + e \cdot a \cdot g' \cdot P\).
-}
partialSigVerifyWith :: Session -> Integer -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerifyWith :: Session
-> Integer -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerifyWith Session
ses Integer
a PubKey
pk PubNonce
pn (PartialSignature Integer
s) = Integer -> Projective
mulGPublic Integer
s Projective -> Projective -> Bool
forall a. Eq a => a -> a -> Bool
== Projective -> Projective -> Projective
add Projective
re (Projective -> Integer -> Projective
mulPublic (PubKey -> Projective
pubKeyPt PubKey
pk) Integer
factor)
 where
  re' :: Projective
re' = Projective -> Projective -> Projective
add (PubNonce -> Projective
pubNonceR1 PubNonce
pn) (Projective -> Integer -> Projective
mulPublic (PubNonce -> Projective
pubNonceR2 PubNonce
pn) (Session -> Integer
sesB Session
ses))
  re :: Projective
re = if Session -> Bool
sesREven Session
ses then Projective
re' else Projective -> Projective
neg Projective
re'
  ea :: Integer
ea = Integer -> Integer
modQ (Session -> Integer
sesE Session
ses Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
a)
  factor :: Integer
factor = if Session -> Bool
negatesKey Session
ses then Integer -> Integer
modQ (Integer
curveOrder Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
ea) else Integer
ea

{- | 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.
-}
partialSigAgg :: Session -> NonEmpty PartialSignature -> Signature
partialSigAgg :: Session -> NonEmpty PartialSignature -> Signature
partialSigAgg Session
ses NonEmpty PartialSignature
psigs = ByteString -> Signature
Signature (Session -> ByteString
sesRx Session
ses ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Integer -> ByteString
integerToBytes32 Integer
s)
 where
  total :: Integer
total = (Integer -> PartialSignature -> Integer)
-> Integer -> NonEmpty PartialSignature -> Integer
forall b a. (b -> a -> b) -> b -> NonEmpty a -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\Integer
acc (PartialSignature Integer
si) -> Integer -> Integer
modQ (Integer
acc Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
si)) Integer
0 NonEmpty PartialSignature
psigs
  g :: Integer
g = if Session -> Bool
sesQEven Session
ses then Integer
1 else Integer
curveOrder Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1
  s :: Integer
s = Integer -> Integer
modQ (Integer
total Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Session -> Integer
sesE Session
ses Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
g Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* KeyAggContext -> Integer
kacTacc (Session -> KeyAggContext
sesKeyAgg Session
ses))

-- | BIP-340 verification of a Schnorr signature.
verify :: XOnlyPubKey -> ByteString -> Signature -> Bool
verify :: XOnlyPubKey -> ByteString -> Signature -> Bool
verify XOnlyPubKey
pk ByteString
msg (Signature ByteString
sig) = Context -> ByteString -> Projective -> ByteString -> Bool
verify_schnorr' Context
gContext ByteString
msg (XOnlyPubKey -> Projective
xOnlyPoint XOnlyPubKey
pk) ByteString
sig