{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}

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

Scalar arithmetic modulo the secp256k1 group order \(n\).

Two representations, kept apart by type:

* Public scalars (key aggregation coefficients, nonce coefficients,
  challenges, tweaks, partial signatures) are 'Integer's. Arithmetic on
  'Integer' takes time that depends on the values, which is fine for values
  everyone knows.

* Secret scalars (secret keys and nonces) are t'SecScalar's: four 64-bit
  limbs in Montgomery form, with the constant-time arithmetic of
  @ppad-fixed@. They are read from and written to bytes in constant time,
  range-checked with constant-time comparisons that are decided only once
  at the end, and never converted to or from 'Integer'.

Not part of the public API.
-}
module Crypto.Curve.Secp256k1.MuSig2.Internal.Scalar (
  -- * Group order
  curveOrder,
  fieldSize,
  modQ,

  -- * Public scalars
  bytesToInteger,
  integerToBytes32,
  hashToScalar,

  -- * Secret scalars
  SecScalar,
  secScalarFromBytes,
  secScalarFromBytesModQ,
  secScalarToBytes,
  secScalarWider,

  -- * Secret arithmetic
  signScalar,

  -- * Constant-time byte conversions
  widerFromBytes,
  widerToBytes,
) where

import Control.DeepSeq (NFData (..))
import Crypto.Curve.Secp256k1.MuSig2.Internal.Error (DecodeError (..))
import Data.Bits (shiftR, unsafeShiftL, unsafeShiftR, (.|.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
import qualified Data.Choice as C
import Data.Word (Word8)
import Data.Word.Limb (Limb (..))
import Data.Word.Wider (Wider (..))
import qualified Data.Word.Wider as W
import Foreign.Ptr (Ptr)
import Foreign.Storable (pokeByteOff)
import GHC.Exts (Word (..))
import qualified Numeric.Montgomery.Secp256k1.Scalar as S

-- Group order ----------------------------------------------------------------

-- | The secp256k1 group order \(n\).
curveOrder :: Integer
curveOrder :: Integer
curveOrder = Integer
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141

-- | The secp256k1 field size \(p\).
fieldSize :: Integer
fieldSize :: Integer
fieldSize = Integer
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F

-- | Reduction modulo \(n\) (variable-time: public values only).
modQ :: Integer -> Integer
modQ :: Integer -> Integer
modQ Integer
x = Integer
x Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`mod` Integer
curveOrder

-- Public scalars -------------------------------------------------------------

-- | Big-endian bytes to a non-negative 'Integer' (variable-time: public values only).
bytesToInteger :: ByteString -> Integer
bytesToInteger :: ByteString -> Integer
bytesToInteger = (Integer -> Word8 -> Integer) -> Integer -> ByteString -> Integer
forall a. (a -> Word8 -> a) -> a -> ByteString -> a
BS.foldl' (\Integer
acc Word8
b -> Integer
acc Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
256 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word8 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
b) Integer
0

-- | A non-negative 'Integer' below \(2^{256}\) to 32 big-endian bytes (variable-time: public values only).
integerToBytes32 :: Integer -> ByteString
integerToBytes32 :: Integer -> ByteString
integerToBytes32 Integer
i = (ByteString, Maybe Int) -> ByteString
forall a b. (a, b) -> a
fst (Int
-> (Int -> Maybe (Word8, Int)) -> Int -> (ByteString, Maybe Int)
forall a.
Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
BS.unfoldrN Int
32 Int -> Maybe (Word8, Int)
step Int
31)
 where
  step :: Int -> Maybe (Word8, Int)
  step :: Int -> Maybe (Word8, Int)
step Int
j = (Word8, Int) -> Maybe (Word8, Int)
forall a. a -> Maybe a
Just (Integer -> Word8
forall a. Num a => Integer -> a
fromInteger (Integer
i Integer -> Int -> Integer
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 -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)

-- | @int(h) mod n@ for a 32-byte hash @h@ that is public (variable-time).
hashToScalar :: ByteString -> Integer
hashToScalar :: ByteString -> Integer
hashToScalar = Integer -> Integer
modQ (Integer -> Integer)
-> (ByteString -> Integer) -> ByteString -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Integer
bytesToInteger

-- Secret scalars -------------------------------------------------------------

{- | A secret scalar modulo \(n\), in the Montgomery form of @ppad-fixed@
(always fully reduced, so in \([0, n)\)).

Every operation on it runs in constant time. Deliberately has no 'Show',
'Eq', 'Ord', 'Num' or other instance that could compare, print or convert it
in variable time.
-}
newtype SecScalar = SecScalar S.Montgomery

instance NFData SecScalar where
  rnf :: SecScalar -> ()
rnf (SecScalar Montgomery
m) = Montgomery -> ()
forall a. NFData a => a -> ()
rnf Montgomery
m

-- | \(n\) as four limbs.
orderWider :: Wider
orderWider :: Wider
orderWider = Word -> Word -> Word -> Word -> Wider
W.wider Word
0xBFD25E8CD0364141 Word
0xBAAEDCE6AF48A03B Word
0xFFFFFFFFFFFFFFFE Word
0xFFFFFFFFFFFFFFFF

-- | Zero as four limbs.
zeroWider :: Wider
zeroWider :: Wider
zeroWider = Word -> Word -> Word -> Word -> Wider
W.wider Word
0 Word
0 Word
0 Word
0

{- | A secret scalar from 32 big-endian bytes in \([1, n)\).

Only the length is checked in variable time. The range check compares the
limbs in constant time and decides once, on the combined result; only the
outcome (valid, zero or out of range) is revealed.
-}
secScalarFromBytes :: ByteString -> Either DecodeError SecScalar
secScalarFromBytes :: ByteString -> Either DecodeError SecScalar
secScalarFromBytes ByteString
b
  | ByteString -> Int
BS.length ByteString
b Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 = DecodeError -> Either DecodeError SecScalar
forall a b. a -> Either a b
Left (Int -> Int -> DecodeError
InvalidLength Int
32 (ByteString -> Int
BS.length ByteString
b))
  | Choice -> Bool
C.decide (Choice -> Choice -> Choice
C.and (Wider -> Wider -> Choice
W.gt Wider
w Wider
zeroWider) (Wider -> Wider -> Choice
W.lt Wider
w Wider
orderWider)) = SecScalar -> Either DecodeError SecScalar
forall a b. b -> Either a b
Right (SecScalar -> Either DecodeError SecScalar)
-> SecScalar -> Either DecodeError SecScalar
forall a b. (a -> b) -> a -> b
$! Montgomery -> SecScalar
SecScalar (Wider -> Montgomery
S.to Wider
w)
  | Choice -> Bool
C.decide (Wider -> Wider -> Choice
W.gt Wider
w Wider
zeroWider) = DecodeError -> Either DecodeError SecScalar
forall a b. a -> Either a b
Left DecodeError
ScalarOutOfRange
  | Bool
otherwise = DecodeError -> Either DecodeError SecScalar
forall a b. a -> Either a b
Left DecodeError
ScalarZero
 where
  w :: Wider
w = ByteString -> Wider
widerFromBytes ByteString
b

{- | @int(b) mod n@ as a secret scalar, for exactly 32 bytes @b@: a hash
that becomes a secret nonce, or the stored bytes of a scalar already in
\([0, n)\) (which the reduction leaves unchanged).

The reduction is the conversion into Montgomery form: a Montgomery
multiplication by \(R^2 \bmod n\) followed by one constant-time conditional
subtraction. It is exact for every 256-bit input because
\(b \cdot (R^2 \bmod n) < R \cdot n\).
-}
secScalarFromBytesModQ :: ByteString -> SecScalar
secScalarFromBytesModQ :: ByteString -> SecScalar
secScalarFromBytesModQ ByteString
b = Montgomery -> SecScalar
SecScalar (Wider -> Montgomery
S.to (ByteString -> Wider
widerFromBytes ByteString
b))

-- | The 32-byte big-endian encoding of a secret scalar, in constant time.
secScalarToBytes :: SecScalar -> ByteString
secScalarToBytes :: SecScalar -> ByteString
secScalarToBytes = Wider -> ByteString
widerToBytes (Wider -> ByteString)
-> (SecScalar -> Wider) -> SecScalar -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SecScalar -> Wider
secScalarWider

-- | A secret scalar as a plain t'Wider' word in \([0, n)\), e.g. for @ppad-secp256k1@'s @mul_wnaf@.
secScalarWider :: SecScalar -> Wider
secScalarWider :: SecScalar -> Wider
secScalarWider (SecScalar Montgomery
m) = Montgomery -> Wider
S.retr Montgomery
m

-- | A public 'Integer' in Montgomery form (variable-time in the 'Integer').
publicMontgomery :: Integer -> S.Montgomery
publicMontgomery :: Integer -> Montgomery
publicMontgomery Integer
x = Wider -> Montgomery
S.to (Integer -> Wider
W.to_vartime (Integer -> Integer
modQ Integer
x))

-- | A public flag as a 'C.Choice'.
choice :: Bool -> C.Choice
choice :: Bool -> Choice
choice Bool
True = () -> Choice
C.true# ()
choice Bool
False = () -> Choice
C.false# ()

-- Secret arithmetic ----------------------------------------------------------

{- | The scalar of a BIP-327 partial signature:

\[
s = k_1' + b \cdot k_2' + e \cdot a \cdot d \pmod n
\]

where \(k_i' = n - k_i\) when the final nonce \(R\) has odd \(y\) and
\(d = g \cdot gacc \cdot d'\), i.e. \(d'\) negated when
\(g \cdot gacc = -1\).

This is the only place where secret scalars are combined. The secrets stay
in Montgomery form throughout: additions, multiplications and the
negations (selected with a constant-time 'S.select', although both flags are
public) run in constant time. Only the result \(s\), the public partial
signature, is converted to an 'Integer'.
-}
signScalar ::
  -- | \(k_1\) (secret).
  SecScalar ->
  -- | \(k_2\) (secret).
  SecScalar ->
  -- | \(d'\), the secret key (secret).
  SecScalar ->
  -- | Negate the nonce (\(R\) has odd \(y\)).
  Bool ->
  -- | Negate the secret key (\(g \cdot gacc = n - 1\)).
  Bool ->
  -- | Nonce coefficient \(b\) (public).
  Integer ->
  -- | \(e \cdot a \bmod n\) (public).
  Integer ->
  -- | \(s\) (public).
  Integer
signScalar :: SecScalar
-> SecScalar
-> SecScalar
-> Bool
-> Bool
-> Integer
-> Integer
-> Integer
signScalar (SecScalar Montgomery
k1) (SecScalar Montgomery
k2) (SecScalar Montgomery
d) Bool
negateNonce Bool
negateKey Integer
b Integer
ea =
  let k :: Montgomery
k = Montgomery -> Montgomery -> Montgomery
S.add Montgomery
k1 (Montgomery -> Montgomery -> Montgomery
S.mul (Integer -> Montgomery
publicMontgomery Integer
b) Montgomery
k2)
      k' :: Montgomery
k' = Montgomery -> Montgomery -> Choice -> Montgomery
S.select Montgomery
k (Montgomery -> Montgomery
S.neg Montgomery
k) (Bool -> Choice
choice Bool
negateNonce)
      d' :: Montgomery
d' = Montgomery -> Montgomery -> Choice -> Montgomery
S.select Montgomery
d (Montgomery -> Montgomery
S.neg Montgomery
d) (Bool -> Choice
choice Bool
negateKey)
   in Wider -> Integer
W.from_vartime (Montgomery -> Wider
S.retr (Montgomery -> Montgomery -> Montgomery
S.add Montgomery
k' (Montgomery -> Montgomery -> Montgomery
S.mul (Integer -> Montgomery
publicMontgomery Integer
ea) Montgomery
d')))

-- Constant-time byte conversions ---------------------------------------------

{- | The first 32 bytes, big-endian, as a t'Wider' word: shifts and ors with
no branch on the data.

These conversions are vendored instead of @ppad-secp256k1@'s
@unsafe_roll32@ and @unroll32@, which that package exports for testing and
benchmarking only. Precondition: at least 32 bytes (checked; the length is
public).
-}
widerFromBytes :: ByteString -> Wider
widerFromBytes :: ByteString -> Wider
widerFromBytes ByteString
b
  | ByteString -> Int
BS.length ByteString
b Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
32 = [Char] -> Wider
forall a. HasCallStack => [Char] -> a
error [Char]
"widerFromBytes: fewer than 32 bytes"
  | Bool
otherwise = Word -> Word -> Word -> Word -> Wider
W.wider (Int -> Word
limbAt Int
24) (Int -> Word
limbAt Int
16) (Int -> Word
limbAt Int
8) (Int -> Word
limbAt Int
0)
 where
  limbAt :: Int -> Word
  limbAt :: Int -> Word
limbAt Int
off =
    Int -> Int -> Word
byteAt Int
off Int
56
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
48
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2) Int
40
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3) Int
32
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4) Int
24
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5) Int
16
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
6) Int
8
      Word -> Word -> Word
forall a. Bits a => a -> a -> a
.|. Int -> Int -> Word
byteAt (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7) Int
0
  byteAt :: Int -> Int -> Word
  byteAt :: Int -> Int -> Word
byteAt Int
i Int
s = Word8 -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int -> Word8
BU.unsafeIndex ByteString
b Int
i) Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftL` Int
s

-- | A t'Wider' word as 32 big-endian bytes, with no branch on the data.
widerToBytes :: Wider -> ByteString
widerToBytes :: Wider -> ByteString
widerToBytes (Wider (# Limb Word#
w0, Limb Word#
w1, Limb Word#
w2, Limb Word#
w3 #)) = Int -> (Ptr Word8 -> IO ()) -> ByteString
BI.unsafeCreate Int
32 ((Ptr Word8 -> IO ()) -> ByteString)
-> (Ptr Word8 -> IO ()) -> ByteString
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
p -> do
  Ptr Word8 -> Int -> Word -> IO ()
pokeLimb Ptr Word8
p Int
0 (Word# -> Word
W# Word#
w3)
  Ptr Word8 -> Int -> Word -> IO ()
pokeLimb Ptr Word8
p Int
8 (Word# -> Word
W# Word#
w2)
  Ptr Word8 -> Int -> Word -> IO ()
pokeLimb Ptr Word8
p Int
16 (Word# -> Word
W# Word#
w1)
  Ptr Word8 -> Int -> Word -> IO ()
pokeLimb Ptr Word8
p Int
24 (Word# -> Word
W# Word#
w0)
 where
  pokeLimb :: Ptr Word8 -> Int -> Word -> IO ()
  pokeLimb :: Ptr Word8 -> Int -> Word -> IO ()
pokeLimb Ptr Word8
p Int
off Word
w = do
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p Int
off (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
56)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
48)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
40)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
32)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
24)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
16)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
6) (Word
w Word -> Int -> Word
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
8)
    Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
7) Word
w
  pokeByte :: Ptr Word8 -> Int -> Word -> IO ()
  pokeByte :: Ptr Word8 -> Int -> Word -> IO ()
pokeByte Ptr Word8
p Int
off Word
x = Ptr Word8 -> Int -> Word8 -> IO ()
forall b. Ptr b -> Int -> Word8 -> IO ()
forall a b. Storable a => Ptr b -> Int -> a -> IO ()
pokeByteOff Ptr Word8
p Int
off (Word -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word
x :: Word8)