{-# LANGUAGE BangPatterns #-}

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

BIP-327 @NonceGen@, @NonceAgg@ and the nonce derivation of
@DeterministicSign@, and the one-shot t'SecNonce'.

The representation of t'SecNonce' is private to this module: everything else
reads its public parts through 'secNoncePubKey', 'secNoncePubNonce',
'secNonceAggPubKey' and 'secNonceMessage', and its secret scalars only
through 'claimSecNonce', which consumes it.

Not part of the public API.
-}
module Crypto.Curve.Secp256k1.MuSig2.Internal.Nonce (
  -- * Secret nonces
  SecNonce,
  secNoncePubKey,
  secNoncePubNonce,
  secNonceAggPubKey,
  secNonceMessage,
  claimSecNonce,
  secNonceIsUsed,
  peekSecNonce,
  newSecNonce,
  secNonceFromScalars,
  secNonceFromBytes,
  secNonceToBytes,
  pubNonceFromScalars,

  -- * Generation
  NonceInputs (..),
  noNonceInputs,
  validateNonceInputs,
  nonceGen,
  nonceGenWithRand,
  nonceGenCounter,
  nonceGenScalars,
  deterministicNonceScalars,

  -- * Aggregation
  nonceAgg,
) where

import Control.DeepSeq (NFData (..), rwhnf)
import Control.Monad (when)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Error (DecodeError (..), NonceGenError (..))
import Crypto.Curve.Secp256k1.MuSig2.Internal.Hash (hashAux, hashDetNonce, hashNonce)
import Crypto.Curve.Secp256k1.MuSig2.Internal.OneShot (OneShot, claimOneShot, isClaimed, newOneShot, peekOneShot)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Point (mulGSecret, sumPoints)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Scalar (SecScalar, secScalarFromBytes, secScalarFromBytesModQ, secScalarToBytes)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Types (
  AggNonce (..),
  Encode (..),
  PubKey (..),
  PubNonce (..),
  SecKey (..),
  XOnlyPubKey (..),
  expectLength,
  mkAggNonce,
  mkPubNonce,
 )
import Data.Bits (Bits, shiftR, xor)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe (fromMaybe)
import Data.Word (Word64, Word8)
import System.Entropy (getEntropy)

{- | 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
t'SecNonce' 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.
-}
data SecNonce = MkSecNonce
  { SecNonce -> OneShot
snSecret :: !OneShot
  -- ^ @bytes(32, k1) || bytes(32, k2)@.
  , SecNonce -> PubKey
snPubKey :: !PubKey
  , SecNonce -> PubNonce
snPubNonce :: !PubNonce
  , SecNonce -> Maybe XOnlyPubKey
snAggPubKey :: !(Maybe XOnlyPubKey)
  -- ^ The aggregate key the nonce was generated for, if any.
  , SecNonce -> Maybe ByteString
snMessage :: !(Maybe ByteString)
  -- ^ The message the nonce was generated for, if any.
  }

instance NFData SecNonce where
  rnf :: SecNonce -> ()
rnf (MkSecNonce OneShot
s PubKey
pk PubNonce
pn Maybe XOnlyPubKey
apk Maybe ByteString
m) = OneShot -> ()
forall a. a -> ()
rwhnf OneShot
s () -> () -> ()
forall a b. a -> b -> b
`seq` PubKey -> ()
forall a. NFData a => a -> ()
rnf PubKey
pk () -> () -> ()
forall a b. a -> b -> b
`seq` PubNonce -> ()
forall a. NFData a => a -> ()
rnf PubNonce
pn () -> () -> ()
forall a b. a -> b -> b
`seq` Maybe XOnlyPubKey -> ()
forall a. NFData a => a -> ()
rnf Maybe XOnlyPubKey
apk () -> () -> ()
forall a b. a -> b -> b
`seq` Maybe ByteString -> ()
forall a. NFData a => a -> ()
rnf Maybe ByteString
m

-- | The public key the nonce was generated for.
secNoncePubKey :: SecNonce -> PubKey
secNoncePubKey :: SecNonce -> PubKey
secNoncePubKey = SecNonce -> PubKey
snPubKey

-- | The public nonce \((k_1 \cdot G, k_2 \cdot G)\).
secNoncePubNonce :: SecNonce -> PubNonce
secNoncePubNonce :: SecNonce -> PubNonce
secNoncePubNonce = SecNonce -> PubNonce
snPubNonce

-- | The aggregate key given to nonce generation, if any.
secNonceAggPubKey :: SecNonce -> Maybe XOnlyPubKey
secNonceAggPubKey :: SecNonce -> Maybe XOnlyPubKey
secNonceAggPubKey = SecNonce -> Maybe XOnlyPubKey
snAggPubKey

-- | The message given to nonce generation, if any.
secNonceMessage :: SecNonce -> Maybe ByteString
secNonceMessage :: SecNonce -> Maybe ByteString
secNonceMessage = SecNonce -> Maybe ByteString
snMessage

{- | Consumes the nonce: atomically marks it used, zero-fills its buffer and
returns the scalars \((k_1, k_2)\). 'Nothing' if it was used before (through
any copy, from any thread).

The bytes go straight to constant-time t'SecScalar's (they are below \(n\),
so the reduction leaves them unchanged).
-}
claimSecNonce :: SecNonce -> IO (Maybe (SecScalar, SecScalar))
claimSecNonce :: SecNonce -> IO (Maybe (SecScalar, SecScalar))
claimSecNonce SecNonce
sn = do
  claimed <- OneShot -> IO (Maybe ByteString)
claimOneShot (SecNonce -> OneShot
snSecret SecNonce
sn)
  case claimed of
    Maybe ByteString
Nothing -> Maybe (SecScalar, SecScalar) -> IO (Maybe (SecScalar, SecScalar))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (SecScalar, SecScalar)
forall a. Maybe a
Nothing
    Just ByteString
bytes -> do
      let !k1 :: SecScalar
k1 = ByteString -> SecScalar
secScalarFromBytesModQ (Int -> ByteString -> ByteString
BS.take Int
32 ByteString
bytes)
          !k2 :: SecScalar
k2 = ByteString -> SecScalar
secScalarFromBytesModQ (Int -> ByteString -> ByteString
BS.drop Int
32 ByteString
bytes)
      Maybe (SecScalar, SecScalar) -> IO (Maybe (SecScalar, SecScalar))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((SecScalar, SecScalar) -> Maybe (SecScalar, SecScalar)
forall a. a -> Maybe a
Just (SecScalar
k1, SecScalar
k2))

-- | Whether the nonce has been used.
secNonceIsUsed :: SecNonce -> IO Bool
secNonceIsUsed :: SecNonce -> IO Bool
secNonceIsUsed = OneShot -> IO Bool
isClaimed (OneShot -> IO Bool)
-> (SecNonce -> OneShot) -> SecNonce -> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SecNonce -> OneShot
snSecret

{- | The 64 bytes of the nonce's buffer, without consuming it (all zero after
use). For tests only.
-}
peekSecNonce :: SecNonce -> IO ByteString
peekSecNonce :: SecNonce -> IO ByteString
peekSecNonce = OneShot -> IO ByteString
peekOneShot (OneShot -> IO ByteString)
-> (SecNonce -> OneShot) -> SecNonce -> IO ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SecNonce -> OneShot
snSecret

{- | A fresh secret nonce from its parts, unchecked.

Precondition: \(0 < k_1, k_2 < n\) and the public nonce is
\((k_1 \cdot G, k_2 \cdot G)\).
-}
newSecNonce :: SecScalar -> SecScalar -> PubKey -> PubNonce -> Maybe XOnlyPubKey -> Maybe ByteString -> IO SecNonce
newSecNonce :: SecScalar
-> SecScalar
-> PubKey
-> PubNonce
-> Maybe XOnlyPubKey
-> Maybe ByteString
-> IO SecNonce
newSecNonce SecScalar
k1 SecScalar
k2 PubKey
pk PubNonce
pn Maybe XOnlyPubKey
apk Maybe ByteString
m = do
  secret <- ByteString -> IO OneShot
newOneShot (SecScalar -> ByteString
secScalarToBytes SecScalar
k1 ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> SecScalar -> ByteString
secScalarToBytes SecScalar
k2)
  pure (MkSecNonce secret pk pn apk m)

-- | The public nonce \((k_1 \cdot G, k_2 \cdot G)\); 'Nothing' if either scalar is zero.
pubNonceFromScalars :: SecScalar -> SecScalar -> Maybe PubNonce
pubNonceFromScalars :: SecScalar -> SecScalar -> Maybe PubNonce
pubNonceFromScalars SecScalar
k1 SecScalar
k2 = Projective -> Projective -> PubNonce
mkPubNonce (Projective -> Projective -> PubNonce)
-> Maybe Projective -> Maybe (Projective -> PubNonce)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SecScalar -> Maybe Projective
mulGSecret SecScalar
k1 Maybe (Projective -> PubNonce)
-> Maybe Projective -> Maybe PubNonce
forall a b. Maybe (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> SecScalar -> Maybe Projective
mulGSecret SecScalar
k2

-- | A fresh secret nonce from its scalars (both must be non-zero), not bound to a session.
secNonceFromScalars :: SecScalar -> SecScalar -> PubKey -> IO (Either DecodeError SecNonce)
secNonceFromScalars :: SecScalar
-> SecScalar -> PubKey -> IO (Either DecodeError SecNonce)
secNonceFromScalars SecScalar
k1 SecScalar
k2 PubKey
pk = case SecScalar -> SecScalar -> Maybe PubNonce
pubNonceFromScalars SecScalar
k1 SecScalar
k2 of
  Maybe PubNonce
Nothing -> Either DecodeError SecNonce -> IO (Either DecodeError SecNonce)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DecodeError -> Either DecodeError SecNonce
forall a b. a -> Either a b
Left DecodeError
ScalarZero)
  Just PubNonce
pn -> SecNonce -> Either DecodeError SecNonce
forall a b. b -> Either a b
Right (SecNonce -> Either DecodeError SecNonce)
-> IO SecNonce -> IO (Either DecodeError SecNonce)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SecScalar
-> SecScalar
-> PubKey
-> PubNonce
-> Maybe XOnlyPubKey
-> Maybe ByteString
-> IO SecNonce
newSecNonce SecScalar
k1 SecScalar
k2 PubKey
pk PubNonce
pn Maybe XOnlyPubKey
forall a. Maybe a
Nothing Maybe ByteString
forall a. Maybe a
Nothing

{- | A fresh secret nonce from the 97-byte BIP-327 encoding
@bytes(32, k1) || bytes(32, k2) || pk@. The scalars are range-checked in
constant time (see 'secScalarFromBytes').
-}
secNonceFromBytes :: ByteString -> IO (Either DecodeError SecNonce)
secNonceFromBytes :: ByteString -> IO (Either DecodeError SecNonce)
secNonceFromBytes ByteString
b = case Either DecodeError (SecScalar, SecScalar, PubKey)
parts of
  Left DecodeError
err -> Either DecodeError SecNonce -> IO (Either DecodeError SecNonce)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DecodeError -> Either DecodeError SecNonce
forall a b. a -> Either a b
Left DecodeError
err)
  Right (SecScalar
k1, SecScalar
k2, PubKey
pk) -> SecScalar
-> SecScalar -> PubKey -> IO (Either DecodeError SecNonce)
secNonceFromScalars SecScalar
k1 SecScalar
k2 PubKey
pk
 where
  parts :: Either DecodeError (SecScalar, SecScalar, PubKey)
parts = do
    Int -> ByteString -> Either DecodeError ()
expectLength Int
97 ByteString
b
    pk <- ByteString -> Either DecodeError PubKey
forall a. Encode a => ByteString -> Either DecodeError a
decode (Int -> ByteString -> ByteString
BS.drop Int
64 ByteString
b)
    k1 <- secScalarFromBytes (BS.take 32 b)
    k2 <- secScalarFromBytes (BS.take 32 (BS.drop 32 b))
    Right (k1, k2, pk)

{- | Consumes the nonce and returns its 97-byte BIP-327 encoding; 'Nothing' if
it was used before.
-}
secNonceToBytes :: SecNonce -> IO (Maybe ByteString)
secNonceToBytes :: SecNonce -> IO (Maybe ByteString)
secNonceToBytes SecNonce
sn = (ByteString -> ByteString) -> Maybe ByteString -> Maybe ByteString
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> PubKey -> ByteString
pubKeyBytes (SecNonce -> PubKey
snPubKey SecNonce
sn)) (Maybe ByteString -> Maybe ByteString)
-> IO (Maybe ByteString) -> IO (Maybe ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> OneShot -> IO (Maybe ByteString)
claimOneShot (SecNonce -> OneShot
snSecret SecNonce
sn)

{- | 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.
-}
data NonceInputs = NonceInputs
  { NonceInputs -> Maybe SecKey
nonceSecKey :: !(Maybe SecKey)
  {- ^ The signer's secret key. Stricter than BIP-327, which hashes in any 32
  bytes: it must be a valid secret key (as every t'SecKey' is) belonging to
  the public key passed to 'nonceGen', or nonce generation fails with
  'NonceSecKeyMismatch'.
  -}
  , NonceInputs -> Maybe XOnlyPubKey
nonceAggPubKey :: !(Maybe XOnlyPubKey)
  {- ^ The x-only aggregate public key. When given, the nonce can only sign
  in a session whose 'Crypto.Curve.Secp256k1.MuSig2.aggXOnlyPubKey' is this
  key.
  -}
  , NonceInputs -> Maybe ByteString
nonceMessage :: !(Maybe ByteString)
  {- ^ The message to be signed. When given, the nonce can only sign this
  message.
  -}
  , NonceInputs -> Maybe ByteString
nonceExtraInput :: !(Maybe ByteString)
  -- ^ Any other data, e.g. a session identifier or a counter.
  }

-- | No optional inputs: the nonce depends only on fresh randomness and the public key.
noNonceInputs :: NonceInputs
noNonceInputs :: NonceInputs
noNonceInputs = Maybe SecKey
-> Maybe XOnlyPubKey
-> Maybe ByteString
-> Maybe ByteString
-> NonceInputs
NonceInputs Maybe SecKey
forall a. Maybe a
Nothing Maybe XOnlyPubKey
forall a. Maybe a
Nothing Maybe ByteString
forall a. Maybe a
Nothing Maybe ByteString
forall a. Maybe a
Nothing

-- | Checks the inputs of @NonceGen@.
validateNonceInputs :: PubKey -> NonceInputs -> Either NonceGenError ()
validateNonceInputs :: PubKey -> NonceInputs -> Either NonceGenError ()
validateNonceInputs PubKey
pk NonceInputs
inputs = do
  case NonceInputs -> Maybe SecKey
nonceSecKey NonceInputs
inputs of
    Just SecKey
sk | SecKey -> PubKey
secKeyPub SecKey
sk PubKey -> PubKey -> Bool
forall a. Eq a => a -> a -> Bool
/= PubKey
pk -> NonceGenError -> Either NonceGenError ()
forall a b. a -> Either a b
Left NonceGenError
NonceSecKeyMismatch
    Maybe SecKey
_ -> () -> Either NonceGenError ()
forall a b. b -> Either a b
Right ()
  Bool -> Either NonceGenError () -> Either NonceGenError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> (ByteString -> Bool) -> Maybe ByteString -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0xFFFFFFFFFFFFFFFF) (Integer -> Bool) -> (ByteString -> Integer) -> ByteString -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Integer) -> (ByteString -> Int) -> ByteString -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Int
BS.length) (NonceInputs -> Maybe ByteString
nonceMessage NonceInputs
inputs)) (NonceGenError -> Either NonceGenError ()
forall a b. a -> Either a b
Left NonceGenError
NonceMessageTooLong)
  Bool -> Either NonceGenError () -> Either NonceGenError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> (ByteString -> Bool) -> Maybe ByteString -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0xFFFFFFFF) (Integer -> Bool) -> (ByteString -> Integer) -> ByteString -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Integer) -> (ByteString -> Int) -> ByteString -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Int
BS.length) (NonceInputs -> Maybe ByteString
nonceExtraInput NonceInputs
inputs)) (NonceGenError -> Either NonceGenError ()
forall a b. a -> Either a b
Left NonceGenError
NonceExtraInputTooLong)

{- | BIP-327 @NonceGen@ with fresh randomness from the operating system
(@getrandom@ on Linux, via the @entropy@ package).
-}
nonceGen :: PubKey -> NonceInputs -> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGen :: PubKey
-> NonceInputs -> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGen PubKey
pk NonceInputs
inputs = case PubKey -> NonceInputs -> Either NonceGenError ()
validateNonceInputs PubKey
pk NonceInputs
inputs of
  Left NonceGenError
err -> Either NonceGenError (SecNonce, PubNonce)
-> IO (Either NonceGenError (SecNonce, PubNonce))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NonceGenError -> Either NonceGenError (SecNonce, PubNonce)
forall a b. a -> Either a b
Left NonceGenError
err)
  Right () -> IO (Either NonceGenError (SecNonce, PubNonce))
forall {a}. IO (Either a (SecNonce, PubNonce))
loop
 where
  loop :: IO (Either a (SecNonce, PubNonce))
loop = do
    rand <- Int -> IO ByteString
getEntropy Int
32
    let (k1, k2) = nonceGenScalars rand pk inputs
    case pubNonceFromScalars k1 k2 of
      -- k1 = 0 or k2 = 0: probability ~2^-127, draw again.
      Maybe PubNonce
Nothing -> IO (Either a (SecNonce, PubNonce))
loop
      Just PubNonce
pn -> do
        sn <- SecScalar
-> SecScalar
-> PubKey
-> PubNonce
-> Maybe XOnlyPubKey
-> Maybe ByteString
-> IO SecNonce
newSecNonce SecScalar
k1 SecScalar
k2 PubKey
pk PubNonce
pn (NonceInputs -> Maybe XOnlyPubKey
nonceAggPubKey NonceInputs
inputs) (NonceInputs -> Maybe ByteString
nonceMessage NonceInputs
inputs)
        pure (Right (sn, pn))

{- | BIP-327 @NonceGen@ with the given 32 random bytes. Deterministic: the
same bytes and inputs give the same nonce scalars.

In 'IO' although deterministic: each call creates exactly one fresh
t'SecNonce'. A pure version would build the handle inside a thunk, and GHC
may evaluate a thunk twice when two threads force it at the same time,
creating two independent handles for the same scalars.
-}
nonceGenWithRand :: ByteString -> PubKey -> NonceInputs -> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGenWithRand :: ByteString
-> PubKey
-> NonceInputs
-> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGenWithRand ByteString
rand PubKey
pk NonceInputs
inputs = case Either NonceGenError (SecScalar, SecScalar, PubNonce)
scalars of
  Left NonceGenError
err -> Either NonceGenError (SecNonce, PubNonce)
-> IO (Either NonceGenError (SecNonce, PubNonce))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NonceGenError -> Either NonceGenError (SecNonce, PubNonce)
forall a b. a -> Either a b
Left NonceGenError
err)
  Right (SecScalar
k1, SecScalar
k2, PubNonce
pn) -> do
    sn <- SecScalar
-> SecScalar
-> PubKey
-> PubNonce
-> Maybe XOnlyPubKey
-> Maybe ByteString
-> IO SecNonce
newSecNonce SecScalar
k1 SecScalar
k2 PubKey
pk PubNonce
pn (NonceInputs -> Maybe XOnlyPubKey
nonceAggPubKey NonceInputs
inputs) (NonceInputs -> Maybe ByteString
nonceMessage NonceInputs
inputs)
    pure (Right (sn, pn))
 where
  scalars :: Either NonceGenError (SecScalar, SecScalar, PubNonce)
scalars = do
    PubKey -> NonceInputs -> Either NonceGenError ()
validateNonceInputs PubKey
pk NonceInputs
inputs
    Bool -> Either NonceGenError () -> Either NonceGenError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Int
BS.length ByteString
rand Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32) (NonceGenError -> Either NonceGenError ()
forall a b. a -> Either a b
Left (Int -> NonceGenError
InvalidRandLength (ByteString -> Int
BS.length ByteString
rand)))
    let (SecScalar
k1, SecScalar
k2) = ByteString -> PubKey -> NonceInputs -> (SecScalar, SecScalar)
nonceGenScalars ByteString
rand PubKey
pk NonceInputs
inputs
    pn <- Either NonceGenError PubNonce
-> (PubNonce -> Either NonceGenError PubNonce)
-> Maybe PubNonce
-> Either NonceGenError PubNonce
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (NonceGenError -> Either NonceGenError PubNonce
forall a b. a -> Either a b
Left NonceGenError
NonceIsZero) PubNonce -> Either NonceGenError PubNonce
forall a b. b -> Either a b
Right (SecScalar -> SecScalar -> Maybe PubNonce
pubNonceFromScalars SecScalar
k1 SecScalar
k2)
    Right (k1, k2, pn)

{- | Counter-based nonce generation, as libsecp256k1's
@secp256k1_musig_nonce_gen_counter@ (BIP-327 @CounterNonceGen@): @NonceGen@
with the secret key always hashed in and the random bytes
@bytes(8, counter) || bytes(24, 0)@. The 'nonceSecKey' of the inputs is
ignored.
-}
nonceGenCounter :: SecKey -> Word64 -> NonceInputs -> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGenCounter :: SecKey
-> Word64
-> NonceInputs
-> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGenCounter SecKey
sk Word64
counter NonceInputs
inputs =
  ByteString
-> PubKey
-> NonceInputs
-> IO (Either NonceGenError (SecNonce, PubNonce))
nonceGenWithRand (Int -> Word64 -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
8 Word64
counter ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int -> Word8 -> ByteString
BS.replicate Int
24 Word8
0) (SecKey -> PubKey
secKeyPub SecKey
sk) NonceInputs
inputs{nonceSecKey = Just sk}

{- | The scalars \((k_1, k_2)\) of BIP-327 @NonceGen@ (reduced modulo \(n\),
possibly zero) for 32 random bytes and validated inputs.
-}
nonceGenScalars :: ByteString -> PubKey -> NonceInputs -> (SecScalar, SecScalar)
nonceGenScalars :: ByteString -> PubKey -> NonceInputs -> (SecScalar, SecScalar)
nonceGenScalars ByteString
rand PubKey
pk NonceInputs
inputs = (Word8 -> SecScalar
k Word8
0, Word8 -> SecScalar
k Word8
1)
 where
  rand' :: ByteString
rand' = case NonceInputs -> Maybe SecKey
nonceSecKey NonceInputs
inputs of
    Maybe SecKey
Nothing -> ByteString
rand
    Just SecKey
sk -> (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
BS.packZipWith Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
xor (SecScalar -> ByteString
secScalarToBytes (SecKey -> SecScalar
secKeyScalar SecKey
sk)) ([ByteString] -> ByteString
hashAux [ByteString
rand])
  pkBytes :: ByteString
pkBytes = PubKey -> ByteString
pubKeyBytes PubKey
pk
  aggpk :: ByteString
aggpk = ByteString
-> (XOnlyPubKey -> ByteString) -> Maybe XOnlyPubKey -> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ByteString
BS.empty XOnlyPubKey -> ByteString
xOnlyBytes (NonceInputs -> Maybe XOnlyPubKey
nonceAggPubKey NonceInputs
inputs)
  msgPrefixed :: [ByteString]
msgPrefixed = case NonceInputs -> Maybe ByteString
nonceMessage NonceInputs
inputs of
    Maybe ByteString
Nothing -> [Word8 -> ByteString
BS.singleton Word8
0]
    Just ByteString
m -> [Word8 -> ByteString
BS.singleton Word8
1, Int -> Int -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
8 (ByteString -> Int
BS.length ByteString
m), ByteString
m]
  extra :: ByteString
extra = ByteString -> Maybe ByteString -> ByteString
forall a. a -> Maybe a -> a
fromMaybe ByteString
BS.empty (NonceInputs -> Maybe ByteString
nonceExtraInput NonceInputs
inputs)
  -- Chunks, not one concatenation: the message and the extra input may be
  -- long, and are hashed twice.
  prefix :: [ByteString]
prefix =
    [ ByteString
rand'
    , Int -> Int -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
1 (ByteString -> Int
BS.length ByteString
pkBytes)
    , ByteString
pkBytes
    , Int -> Int -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
1 (ByteString -> Int
BS.length ByteString
aggpk)
    , ByteString
aggpk
    ]
      [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ [ByteString]
msgPrefixed
      [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ [Int -> Int -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
4 (ByteString -> Int
BS.length ByteString
extra), ByteString
extra]
  k :: Word8 -> SecScalar
  k :: Word8 -> SecScalar
k Word8
i = ByteString -> SecScalar
secScalarFromBytesModQ ([ByteString] -> ByteString
hashNonce ([ByteString]
prefix [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ [Word8 -> ByteString
BS.singleton Word8
i]))

{- | The scalars \((k_1, k_2)\) of BIP-327 @DeterministicSign@ (reduced
modulo \(n\), possibly zero):

\[
k_i = int(hash_{MuSig/deterministic/nonce}(sk' \| aggothernonce \| aggpk \| bytes(8, len(m)) \| m \| bytes(1, i - 1))) \bmod n
\]

where \(sk' = sk \oplus hash_{MuSig/aux}(rand)\) if the 32 bytes @rand@
are given and \(sk\) otherwise.
-}
deterministicNonceScalars ::
  -- | \(sk\).
  SecKey ->
  -- | @aggothernonce@.
  AggNonce ->
  -- | @aggpk@: the x-only aggregate key, after the tweaks.
  XOnlyPubKey ->
  -- | \(m\).
  ByteString ->
  -- | @rand@ (32 bytes).
  Maybe ByteString ->
  (SecScalar, SecScalar)
deterministicNonceScalars :: SecKey
-> AggNonce
-> XOnlyPubKey
-> ByteString
-> Maybe ByteString
-> (SecScalar, SecScalar)
deterministicNonceScalars SecKey
sk AggNonce
aggOther XOnlyPubKey
aggpk ByteString
msg Maybe ByteString
rand = (Word8 -> SecScalar
k Word8
0, Word8 -> SecScalar
k Word8
1)
 where
  skBytes :: ByteString
skBytes = SecScalar -> ByteString
secScalarToBytes (SecKey -> SecScalar
secKeyScalar SecKey
sk)
  sk' :: ByteString
sk' = ByteString
-> (ByteString -> ByteString) -> Maybe ByteString -> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ByteString
skBytes ((Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
BS.packZipWith Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
xor ByteString
skBytes (ByteString -> ByteString)
-> (ByteString -> ByteString) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ByteString] -> ByteString
hashAux ([ByteString] -> ByteString)
-> (ByteString -> [ByteString]) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure) Maybe ByteString
rand
  prefix :: [ByteString]
prefix = [ByteString
sk', AggNonce -> ByteString
aggNonceBytes AggNonce
aggOther, XOnlyPubKey -> ByteString
xOnlyBytes XOnlyPubKey
aggpk, Int -> Int -> ByteString
forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
8 (ByteString -> Int
BS.length ByteString
msg), ByteString
msg]
  k :: Word8 -> SecScalar
  k :: Word8 -> SecScalar
k Word8
i = ByteString -> SecScalar
secScalarFromBytesModQ ([ByteString] -> ByteString
hashDetNonce ([ByteString]
prefix [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ [Word8 -> ByteString
BS.singleton Word8
i]))

-- | @bytes(n, x)@: the \(n\)-byte big-endian encoding of a length or counter.
bigEndian :: (Integral a, Bits a) => Int -> a -> ByteString
bigEndian :: forall a. (Integral a, Bits a) => Int -> a -> ByteString
bigEndian Int
n a
x = [Word8] -> ByteString
BS.pack [a -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` (Int
8 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
j)) | Int
j <- [Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1, Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
2 .. Int
0]]

-- | BIP-327 @NonceAgg@: sums the first and the second points. Either sum may be infinity.
nonceAgg :: NonEmpty PubNonce -> AggNonce
nonceAgg :: NonEmpty PubNonce -> AggNonce
nonceAgg NonEmpty PubNonce
pns = Projective -> Projective -> AggNonce
mkAggNonce (NonEmpty Projective -> Projective
forall (f :: * -> *). Foldable f => f Projective -> Projective
sumPoints ((PubNonce -> Projective)
-> NonEmpty PubNonce -> NonEmpty Projective
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PubNonce -> Projective
pubNonceR1 NonEmpty PubNonce
pns)) (NonEmpty Projective -> Projective
forall (f :: * -> *). Foldable f => f Projective -> Projective
sumPoints ((PubNonce -> Projective)
-> NonEmpty PubNonce -> NonEmpty Projective
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PubNonce -> Projective
pubNonceR2 NonEmpty PubNonce
pns))