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

BIP-327 @KeySort@, @KeyAgg@ and @ApplyTweak@, plus the BIP-341 Taproot tweak.

Not part of the public API.
-}
module Crypto.Curve.Secp256k1.MuSig2.Internal.KeyAgg (
  KeyAggContext (..),
  keySort,
  keyAgg,
  applyPlainTweak,
  applyXOnlyTweak,
  applyTaprootTweak,
  aggPubKey,
  aggXOnlyPubKey,
  keyAggPubKeys,
  signerIndex,
  keyAggCoefficient,
) where

import Control.DeepSeq (NFData (..), force)
import Crypto.Curve.Secp256k1 (add, neg)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Error (KeyAggError (..))
import Crypto.Curve.Secp256k1.MuSig2.Internal.Hash (hashKeyAggCoef, hashKeyAggList, hashTapTweak)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Point (isInfinity, mulGPublic, mulPublic, sumPoints)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Scalar (bytesToInteger, curveOrder, hashToScalar, modQ)
import Crypto.Curve.Secp256k1.MuSig2.Internal.Types (PubKey (..), Tweak (..), XOnlyPubKey (..), mkPubKey, pubKeyHasEvenY, pubKeyXOnly)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Foldable (toList)
import Data.List (find)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (maybeToList)
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq

{- | 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.
-}
data KeyAggContext = KeyAggContext
  { KeyAggContext -> NonEmpty PubKey
kacPubKeys :: !(NonEmpty PubKey)
  -- ^ Signers' keys, in order.
  , KeyAggContext -> Seq Integer
kacCoefs :: !(Seq Integer)
  -- ^ Key aggregation coefficient \(a_i\) of signer \(i\).
  , KeyAggContext -> Map ByteString Int
kacIndex :: !(Map ByteString Int)
  -- ^ Encoded key to the first index it appears at.
  , KeyAggContext -> PubKey
kacQ :: !PubKey
  -- ^ Aggregate key \(Q\) after the tweaks so far.
  , KeyAggContext -> Bool
kacGaccNeg :: !Bool
  -- ^ \(gacc = n - 1\) (otherwise \(1\)).
  , KeyAggContext -> Integer
kacTacc :: !Integer
  -- ^ \(tacc\).
  }

instance NFData KeyAggContext where
  rnf :: KeyAggContext -> ()
rnf (KeyAggContext NonEmpty PubKey
pks Seq Integer
coefs Map ByteString Int
idx PubKey
q Bool
g Integer
t) = NonEmpty PubKey -> ()
forall a. NFData a => a -> ()
rnf NonEmpty PubKey
pks () -> () -> ()
forall a b. a -> b -> b
`seq` Seq Integer -> ()
forall a. NFData a => a -> ()
rnf Seq Integer
coefs () -> () -> ()
forall a b. a -> b -> b
`seq` Map ByteString Int -> ()
forall a. NFData a => a -> ()
rnf Map ByteString Int
idx () -> () -> ()
forall a b. a -> b -> b
`seq` PubKey -> ()
forall a. NFData a => a -> ()
rnf PubKey
q () -> () -> ()
forall a b. a -> b -> b
`seq` Bool -> ()
forall a. NFData a => a -> ()
rnf Bool
g () -> () -> ()
forall a b. a -> b -> b
`seq` Integer -> ()
forall a. NFData a => a -> ()
rnf Integer
t

-- | BIP-327 @KeySort@: sorts keys by their 33-byte encoding.
keySort :: NonEmpty PubKey -> NonEmpty PubKey
keySort :: NonEmpty PubKey -> NonEmpty PubKey
keySort = NonEmpty PubKey -> NonEmpty PubKey
forall a. Ord a => NonEmpty a -> NonEmpty a
NE.sort

{- | 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.
-}
keyAgg :: NonEmpty PubKey -> Either KeyAggError KeyAggContext
keyAgg :: NonEmpty PubKey -> Either KeyAggError KeyAggContext
keyAgg NonEmpty PubKey
pks
  | Int -> Integer
forall a. Integral a => a -> Integer
toInteger (NonEmpty PubKey -> Int
forall a. NonEmpty a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length NonEmpty PubKey
pks) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0xFFFFFFFF = KeyAggError -> Either KeyAggError KeyAggContext
forall a b. a -> Either a b
Left KeyAggError
TooManyPublicKeys
  | Projective -> Bool
isInfinity Projective
q = KeyAggError -> Either KeyAggError KeyAggContext
forall a b. a -> Either a b
Left KeyAggError
AggPubKeyAtInfinity
  | Bool
otherwise =
      KeyAggContext -> Either KeyAggError KeyAggContext
forall a b. b -> Either a b
Right
        KeyAggContext
          { kacPubKeys :: NonEmpty PubKey
kacPubKeys = NonEmpty PubKey
pks
          , kacCoefs :: Seq Integer
kacCoefs = [Integer] -> Seq Integer
forall a. [a] -> Seq a
Seq.fromList ([Integer] -> [Integer]
forall a. NFData a => a -> a
force [Integer]
coefs)
          , kacIndex :: Map ByteString Int
kacIndex = (Int -> Int -> Int) -> [(ByteString, Int)] -> Map ByteString Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith Int -> Int -> Int
forall a. Ord a => a -> a -> a
min ([ByteString] -> [Int] -> [(ByteString, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [ByteString]
encs [Int
0 ..])
          , kacQ :: PubKey
kacQ = Projective -> PubKey
mkPubKey Projective
q
          , kacGaccNeg :: Bool
kacGaccNeg = Bool
False
          , kacTacc :: Integer
kacTacc = Integer
0
          }
 where
  encs :: [ByteString]
encs = (PubKey -> ByteString) -> [PubKey] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map PubKey -> ByteString
pubKeyBytes (NonEmpty PubKey -> [PubKey]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty PubKey
pks)
  l :: ByteString
l = [ByteString] -> ByteString
hashKeyAggList [ByteString]
encs
  pk2 :: Maybe ByteString
pk2 = (ByteString -> Bool) -> [ByteString] -> Maybe ByteString
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= NonEmpty ByteString -> ByteString
forall a. NonEmpty a -> a
NE.head ((PubKey -> ByteString) -> NonEmpty PubKey -> NonEmpty ByteString
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PubKey -> ByteString
pubKeyBytes NonEmpty PubKey
pks)) [ByteString]
encs
  coef :: ByteString -> Integer
coef ByteString
enc
    | ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
enc Maybe ByteString -> Maybe ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe ByteString
pk2 = Integer
1
    | Bool
otherwise = ByteString -> Integer
hashToScalar ([ByteString] -> ByteString
hashKeyAggCoef [ByteString
l, ByteString
enc])
  coefs :: [Integer]
coefs = (ByteString -> Integer) -> [ByteString] -> [Integer]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> Integer
coef [ByteString]
encs
  q :: Projective
q = [Projective] -> Projective
forall (f :: * -> *). Foldable f => f Projective -> Projective
sumPoints ((Integer -> PubKey -> Projective)
-> [Integer] -> [PubKey] -> [Projective]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Integer -> PubKey -> Projective
term [Integer]
coefs (NonEmpty PubKey -> [PubKey]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty PubKey
pks))
  term :: Integer -> PubKey -> Projective
term Integer
a PubKey
pk
    | Integer
a Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
1 = PubKey -> Projective
pubKeyPt PubKey
pk
    | Bool
otherwise = Projective -> Integer -> Projective
mulPublic (PubKey -> Projective
pubKeyPt PubKey
pk) Integer
a

-- | Adds \(t \cdot G\) to \(Q'\) and updates the accumulators.
tweakWith :: Bool -> Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
tweakWith :: Bool -> Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
tweakWith Bool
negateQ (Tweak Integer
t) KeyAggContext
ctx
  | Projective -> Bool
isInfinity Projective
q' = KeyAggError -> Either KeyAggError KeyAggContext
forall a b. a -> Either a b
Left KeyAggError
TweakResultAtInfinity
  | Bool
otherwise =
      KeyAggContext -> Either KeyAggError KeyAggContext
forall a b. b -> Either a b
Right
        KeyAggContext
ctx
          { kacQ = mkPubKey q'
          , kacGaccNeg = kacGaccNeg ctx /= negateQ
          , kacTacc = modQ (t + (if negateQ then curveOrder - kacTacc ctx else kacTacc ctx))
          }
 where
  q :: Projective
q = PubKey -> Projective
pubKeyPt (KeyAggContext -> PubKey
kacQ KeyAggContext
ctx)
  q' :: Projective
q' = Projective -> Projective -> Projective
add (if Bool
negateQ then Projective -> Projective
neg Projective
q else Projective
q) (Integer -> Projective
mulGPublic Integer
t)

{- | BIP-327 @ApplyTweak@ with a plain tweak: \(Q' = Q + t \cdot G\). Use it
for BIP-32 derivation from the aggregate key.
-}
applyPlainTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
applyPlainTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
applyPlainTweak = Bool -> Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
tweakWith Bool
False

{- | BIP-327 @ApplyTweak@ with an x-only tweak: \(Q' = g \cdot Q + t \cdot G\)
where \(g = -1\) if \(Q\) has odd \(y\).
-}
applyXOnlyTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
applyXOnlyTweak :: Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
applyXOnlyTweak Tweak
tw KeyAggContext
ctx = Bool -> Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
tweakWith (Bool -> Bool
not (PubKey -> Bool
pubKeyHasEvenY (KeyAggContext -> PubKey
kacQ KeyAggContext
ctx))) Tweak
tw KeyAggContext
ctx

{- | The BIP-341 Taproot tweak: an x-only tweak by
\(t = hash_{TapTweak}(xbytes(Q) \| merkle\_root)\) (no merkle root for 'Nothing').
-}
applyTaprootTweak :: Maybe ByteString -> KeyAggContext -> Either KeyAggError KeyAggContext
applyTaprootTweak :: Maybe ByteString
-> KeyAggContext -> Either KeyAggError KeyAggContext
applyTaprootTweak Maybe ByteString
root KeyAggContext
ctx = case Maybe ByteString
root of
  Just ByteString
r | ByteString -> Int
BS.length ByteString
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 -> KeyAggError -> Either KeyAggError KeyAggContext
forall a b. a -> Either a b
Left (Int -> KeyAggError
InvalidMerkleRootLength (ByteString -> Int
BS.length ByteString
r))
  Maybe ByteString
_
    | Integer
t Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
curveOrder -> KeyAggError -> Either KeyAggError KeyAggContext
forall a b. a -> Either a b
Left KeyAggError
TaprootTweakOutOfRange
    | Bool
otherwise -> Tweak -> KeyAggContext -> Either KeyAggError KeyAggContext
applyXOnlyTweak (Integer -> Tweak
Tweak Integer
t) KeyAggContext
ctx
 where
  t :: Integer
t = ByteString -> Integer
bytesToInteger ([ByteString] -> ByteString
hashTapTweak (XOnlyPubKey -> ByteString
xOnlyBytes (KeyAggContext -> XOnlyPubKey
aggXOnlyPubKey KeyAggContext
ctx) ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: Maybe ByteString -> [ByteString]
forall a. Maybe a -> [a]
maybeToList Maybe ByteString
root))

-- | The aggregate key \(Q\), including the tweaks applied so far.
aggPubKey :: KeyAggContext -> PubKey
aggPubKey :: KeyAggContext -> PubKey
aggPubKey = KeyAggContext -> PubKey
kacQ

-- | The x-only aggregate key: the key the final signature verifies against.
aggXOnlyPubKey :: KeyAggContext -> XOnlyPubKey
aggXOnlyPubKey :: KeyAggContext -> XOnlyPubKey
aggXOnlyPubKey = PubKey -> XOnlyPubKey
pubKeyXOnly (PubKey -> XOnlyPubKey)
-> (KeyAggContext -> PubKey) -> KeyAggContext -> XOnlyPubKey
forall b c a. (b -> c) -> (a -> b) -> a -> c
. KeyAggContext -> PubKey
kacQ

-- | The signers' public keys, in the order they were aggregated.
keyAggPubKeys :: KeyAggContext -> NonEmpty PubKey
keyAggPubKeys :: KeyAggContext -> NonEmpty PubKey
keyAggPubKeys = KeyAggContext -> NonEmpty PubKey
kacPubKeys

-- | The index of a public key among the signers (its first position if it appears more than once).
signerIndex :: KeyAggContext -> PubKey -> Maybe Int
signerIndex :: KeyAggContext -> PubKey -> Maybe Int
signerIndex KeyAggContext
ctx PubKey
pk = ByteString -> Map ByteString Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (PubKey -> ByteString
pubKeyBytes PubKey
pk) (KeyAggContext -> Map ByteString Int
kacIndex KeyAggContext
ctx)

-- | The key aggregation coefficient of a signer's public key.
keyAggCoefficient :: KeyAggContext -> PubKey -> Maybe Integer
keyAggCoefficient :: KeyAggContext -> PubKey -> Maybe Integer
keyAggCoefficient KeyAggContext
ctx PubKey
pk = KeyAggContext -> PubKey -> Maybe Int
signerIndex KeyAggContext
ctx PubKey
pk Maybe Int -> (Int -> Maybe Integer) -> Maybe Integer
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Int -> Seq Integer -> Maybe Integer
forall a. Int -> Seq a -> Maybe a
`Seq.lookup` KeyAggContext -> Seq Integer
kacCoefs KeyAggContext
ctx)