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

A coordinator for BIP-327 signing sessions: it collects the signers'
contributions as bytes from the network, decodes and verifies each one as it
arrives, and blames the signer responsible for anything wrong.

The coordinator can be one of the signers or a separate party. It runs two
rounds:

1. __Public nonces.__ 'newNonceRound' on the session's key aggregation
   context (with all tweaks applied), 'receivePubNonce' for each signer's
   encoded t'PubNonce', then 'finishNonceRound', which gives the aggregate
   nonce to send back to every signer.
2. __Partial signatures.__ 'newSigRound' on the collected nonces and the
   message, 'receivePartialSig' for each signer's encoded
   t'PartialSignature' (each one is checked with 'partialSigVerify'), then
   'finishSigRound', which aggregates them and checks the final BIP-340
   signature.

Signers are identified by their index in 'keyAggPubKeys', from \(0\). A
public key that appears more than once in the key list belongs to as many
signers, each with its own index, nonce and partial signature.

Every function is pure and every value is immutable, so the rounds are safe
to share between threads. To receive from several threads, keep the round in
an @IORef@ (updated with @atomicModifyIORef'@), an @MVar@ or a @TVar@.

== Blame

'receivePubNonce' and 'receivePartialSig' return a t'Blame' naming the
signer and the reason, and leave the round unchanged: the caller decides
whether to abort the session or wait for the signer to send a valid
contribution. A signer may send the same bytes again (a network retry is not
an error), but a different contribution from a signer whose contribution was
accepted is a 'DuplicateContribution'. The finishing functions blame every
signer whose contribution is still missing. Blames carry no secrets.

The signer index passed to 'receivePubNonce' and 'receivePartialSig' is
trusted: take it from the authenticated connection the bytes arrived on (for
example, a roster that maps each signer's authenticated identity to its
index), never from the message itself. A participant that can choose the
index can send a valid nonce in an honest signer's slot first: the honest
signer's own nonce is then blamed as a 'DuplicateContribution', and its
partial signature, checked against the wrong nonce, as invalid. It cannot
make the coordinator accept an invalid signature, but it can make the
session fail with an honest signer blamed.

== Trust

The coordinator learns nothing secret and cannot forge signatures, so the
signers need not trust it: BIP-327 treats the nonce aggregator as untrusted,
and a coordinator that sends a wrong aggregate nonce can only make the
session fail. Its blame, however, is only as reliable as the coordinator
itself: a signer that wants to check the other signers must receive their
public nonces and partial signatures and run 'nonceAgg' and
'partialSigVerify' itself.

Signers who receive the aggregate nonce from a coordinator 'decode' it as an
t'AggNonce', open the session with 'newSession' on the same key aggregation
context and message, and 'Crypto.Curve.Secp256k1.MuSig2.sign'.

The coordinator does not support
'Crypto.Curve.Secp256k1.MuSig2.deterministicSign', whose signer sends its
public nonce together with its partial signature, after the other signers'
nonces are aggregated.

== Example

A coordinator collects the contributions of three signers. This example is
compiled and run by the test suite; it needs the @OverloadedStrings@
language extension and uses @orThrow@ from the example in
"Crypto.Curve.Secp256k1.MuSig2".

> import Control.Monad (foldM)
> import qualified Crypto.Curve.Secp256k1.MuSig2 as MuSig2
> import qualified Crypto.Curve.Secp256k1.MuSig2.Coordinator as Coordinator
> import Data.Bifunctor (first)
> import qualified Data.ByteString as BS
> import Data.List.NonEmpty (NonEmpty (..))
> import qualified Data.List.NonEmpty as NE

> -- | A coordinator collects three signers' nonces and partial signatures as bytes.
> coordinatorExample :: IO Bool
> coordinatorExample = do
>   sks <- traverse (orThrow . MuSig2.secKeyFromBytes . BS.replicate 32) (0x66 :| [0x77, 0x88])
>   -- Signer i is the one with the i-th public key of the context.
>   keyAggCtx <- orThrow (MuSig2.keyAgg (fmap MuSig2.secKeyPubKey sks))
>   let msg = "pay Carol 1 BTC"
>
>   -- Round one: each signer sends its encoded public nonce, in any order.
>   nonces <- traverse (\sk -> MuSig2.nonceGen (MuSig2.secKeyPubKey sk) MuSig2.noNonceInputs >>= orThrow) (NE.toList sks)
>   nonceRound <-
>     orThrow $
>       foldM
>         (\r (i, (_, pubNonce)) -> Coordinator.receivePubNonce i (MuSig2.encode pubNonce) r)
>         (Coordinator.newNonceRound keyAggCtx)
>         (zip [0 ..] nonces)
>   -- Fails if a nonce is missing (here reporting only the first such signer).
>   collected <- orThrow (first NE.head (Coordinator.finishNonceRound nonceRound))
>
>   -- The coordinator sends the aggregate nonce to every signer, who decodes it
>   -- and opens the session.
>   aggNonce <- orThrow (MuSig2.decode (MuSig2.encode (Coordinator.collectedAggNonce collected)))
>   let session = MuSig2.newSession keyAggCtx aggNonce msg
>
>   -- Round two: each signer sends its encoded partial signature. The
>   -- coordinator verifies each one and blames the signer of an invalid one.
>   psigs <- traverse (\(sk, (secNonce, _)) -> MuSig2.sign secNonce sk session >>= orThrow) (zip (NE.toList sks) nonces)
>   sigRound <-
>     orThrow $
>       foldM
>         (\r (i, psig) -> Coordinator.receivePartialSig i (MuSig2.encode psig) r)
>         (Coordinator.newSigRound collected msg)
>         (zip [0 ..] psigs)
>   -- Aggregates the partial signatures and verifies the result.
>   signature <- orThrow (Coordinator.finishSigRound sigRound)
>   pure (MuSig2.verify (MuSig2.aggXOnlyPubKey keyAggCtx) msg signature)
-}
module Crypto.Curve.Secp256k1.MuSig2.Coordinator (
  -- * Blame
  Blame (..),
  BlameReason (..),

  -- * Round one: public nonces
  NonceRound,
  newNonceRound,
  receivePubNonce,
  nonceRoundMissing,
  finishNonceRound,
  CollectedNonces,
  collectedKeyAgg,
  collectedPubNonces,
  collectedAggNonce,

  -- * Round two: partial signatures
  SigRound,
  newSigRound,
  sigRoundSession,
  receivePartialSig,
  sigRoundMissing,
  finishSigRound,
  SigRoundError (..),
) where

import Control.DeepSeq (NFData (..), rwhnf)
import Control.Exception (Exception)
import Crypto.Curve.Secp256k1.MuSig2 (
  AggNonce,
  DecodeError,
  Encode (..),
  KeyAggContext,
  PartialSignature,
  PubKey,
  PubNonce,
  Session,
  Signature,
  aggXOnlyPubKey,
  keyAggPubKeys,
  newSession,
  nonceAgg,
  partialSigAgg,
  partialSigVerify,
  sessionKeyAgg,
  verify,
 )
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.Foldable (toList)
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq

-- Blame ----------------------------------------------------------------------

-- | A signer who misbehaved, and how.
data Blame = Blame
  { Blame -> Int
blameSigner :: !Int
  -- ^ The signer's index in 'keyAggPubKeys' (for 'UnknownSigner', the index it claimed).
  , Blame -> BlameReason
blameReason :: !BlameReason
  -- ^ What the signer did wrong.
  }
  deriving (Blame -> Blame -> Bool
(Blame -> Blame -> Bool) -> (Blame -> Blame -> Bool) -> Eq Blame
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Blame -> Blame -> Bool
== :: Blame -> Blame -> Bool
$c/= :: Blame -> Blame -> Bool
/= :: Blame -> Blame -> Bool
Eq, Int -> Blame -> ShowS
[Blame] -> ShowS
Blame -> String
(Int -> Blame -> ShowS)
-> (Blame -> String) -> ([Blame] -> ShowS) -> Show Blame
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Blame -> ShowS
showsPrec :: Int -> Blame -> ShowS
$cshow :: Blame -> String
show :: Blame -> String
$cshowList :: [Blame] -> ShowS
showList :: [Blame] -> ShowS
Show)

instance Exception Blame

instance NFData Blame where
  rnf :: Blame -> ()
rnf = Blame -> ()
forall a. a -> ()
rwhnf

-- | Why a signer is blamed.
data BlameReason
  = -- | The signer's public nonce does not decode (wrong length, invalid or infinite point).
    InvalidPubNonceEncoding !DecodeError
  | -- | The signer's partial signature does not decode (wrong length, not below \(n\)).
    InvalidPartialSigEncoding !DecodeError
  | {- | The signer's partial signature fails 'partialSigVerify' for its
    public key and public nonce: it is wrong, or it is another signer's.
    -}
    InvalidPartialSignature
  | -- | The signer already sent a different, accepted contribution in this round.
    DuplicateContribution
  | -- | The index is not a signer of the session (negative, or not below the number of keys).
    UnknownSigner
  | -- | The round was finished without the signer's contribution.
    MissingContribution
  deriving (BlameReason -> BlameReason -> Bool
(BlameReason -> BlameReason -> Bool)
-> (BlameReason -> BlameReason -> Bool) -> Eq BlameReason
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BlameReason -> BlameReason -> Bool
== :: BlameReason -> BlameReason -> Bool
$c/= :: BlameReason -> BlameReason -> Bool
/= :: BlameReason -> BlameReason -> Bool
Eq, Int -> BlameReason -> ShowS
[BlameReason] -> ShowS
BlameReason -> String
(Int -> BlameReason -> ShowS)
-> (BlameReason -> String)
-> ([BlameReason] -> ShowS)
-> Show BlameReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> BlameReason -> ShowS
showsPrec :: Int -> BlameReason -> ShowS
$cshow :: BlameReason -> String
show :: BlameReason -> String
$cshowList :: [BlameReason] -> ShowS
showList :: [BlameReason] -> ShowS
Show)

instance NFData BlameReason where
  rnf :: BlameReason -> ()
rnf = BlameReason -> ()
forall a. a -> ()
rwhnf

-- | Contributions by signer index: all of them, or the blame of every missing one.
collect :: Int -> IntMap a -> Either (NonEmpty Blame) (NonEmpty a)
collect :: forall a. Int -> IntMap a -> Either (NonEmpty Blame) (NonEmpty a)
collect Int
size IntMap a
received = case [Blame] -> Maybe (NonEmpty Blame)
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty [Int -> BlameReason -> Blame
Blame Int
i BlameReason
MissingContribution | Left Int
i <- NonEmpty (Either Int a) -> [Either Int a]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty (Either Int a)
entries] of
  Just NonEmpty Blame
missing -> NonEmpty Blame -> Either (NonEmpty Blame) (NonEmpty a)
forall a b. a -> Either a b
Left NonEmpty Blame
missing
  Maybe (NonEmpty Blame)
Nothing -> (Either Int a -> Either (NonEmpty Blame) a)
-> NonEmpty (Either Int a) -> Either (NonEmpty Blame) (NonEmpty a)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> NonEmpty a -> f (NonEmpty b)
traverse ((Int -> NonEmpty Blame)
-> Either Int a -> Either (NonEmpty Blame) a
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (\Int
i -> Int -> BlameReason -> Blame
Blame Int
i BlameReason
MissingContribution Blame -> [Blame] -> NonEmpty Blame
forall a. a -> [a] -> NonEmpty a
:| [])) NonEmpty (Either Int a)
entries
 where
  entries :: NonEmpty (Either Int a)
entries = (Int -> Either Int a) -> NonEmpty Int -> NonEmpty (Either Int a)
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\Int
i -> Either Int a -> (a -> Either Int a) -> Maybe a -> Either Int a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int -> Either Int a
forall a b. a -> Either a b
Left Int
i) a -> Either Int a
forall a b. b -> Either a b
Right (Int -> IntMap a -> Maybe a
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
i IntMap a
received)) (Int
0 Int -> [Int] -> NonEmpty Int
forall a. a -> [a] -> NonEmpty a
:| [Int
1 .. Int
size Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1])

-- | The indices in \([0, size)\) without a contribution.
missingFrom :: Int -> IntMap a -> [Int]
missingFrom :: forall a. Int -> IntMap a -> [Int]
missingFrom Int
size IntMap a
received = (Int -> Bool) -> [Int] -> [Int]
forall a. (a -> Bool) -> [a] -> [a]
filter (Int -> IntMap a -> Bool
forall a. Int -> IntMap a -> Bool
`IntMap.notMember` IntMap a
received) [Int
0 .. Int
size Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]

-- Round one ---------------------------------------------------------------------

{- | Round one in progress: the public nonces received so far, by signer
index.
-}
data NonceRound = NonceRound
  { NonceRound -> KeyAggContext
nrKeyAgg :: !KeyAggContext
  , NonceRound -> Int
nrSize :: !Int
  , NonceRound -> IntMap PubNonce
nrNonces :: !(IntMap PubNonce)
  }

instance NFData NonceRound where
  rnf :: NonceRound -> ()
rnf (NonceRound KeyAggContext
ctx Int
size IntMap PubNonce
nonces) = KeyAggContext -> ()
forall a. NFData a => a -> ()
rnf KeyAggContext
ctx () -> () -> ()
forall a b. a -> b -> b
`seq` Int -> ()
forall a. NFData a => a -> ()
rnf Int
size () -> () -> ()
forall a b. a -> b -> b
`seq` IntMap PubNonce -> ()
forall a. NFData a => a -> ()
rnf IntMap PubNonce
nonces

{- | Starts round one for the signers of a key aggregation context, with no
nonce received yet.

Pass the context the session will use, with all tweaks applied:
'newSigRound' opens the session on it.
-}
newNonceRound :: KeyAggContext -> NonceRound
newNonceRound :: KeyAggContext -> NonceRound
newNonceRound KeyAggContext
ctx = KeyAggContext -> Int -> IntMap PubNonce -> NonceRound
NonceRound KeyAggContext
ctx (NonEmpty PubKey -> Int
forall a. NonEmpty a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (KeyAggContext -> NonEmpty PubKey
keyAggPubKeys KeyAggContext
ctx)) IntMap PubNonce
forall a. IntMap a
IntMap.empty

{- | Receives a signer's encoded public nonce (66 bytes).

Blames the signer with 'UnknownSigner', 'DuplicateContribution' (a
different nonce was already accepted from it; the same bytes again are
accepted and change nothing) or 'InvalidPubNonceEncoding'. On 'Left' the
round is unchanged.
-}
receivePubNonce ::
  -- | Signer index, from the authenticated connection the bytes arrived on.
  Int ->
  -- | The encoded public nonce.
  ByteString ->
  NonceRound ->
  Either Blame NonceRound
receivePubNonce :: Int -> ByteString -> NonceRound -> Either Blame NonceRound
receivePubNonce Int
i ByteString
bytes NonceRound
nr
  | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 Bool -> Bool -> Bool
|| Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= NonceRound -> Int
nrSize NonceRound
nr = BlameReason -> Either Blame NonceRound
forall {b}. BlameReason -> Either Blame b
blame BlameReason
UnknownSigner
  | Just PubNonce
prev <- Int -> IntMap PubNonce -> Maybe PubNonce
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
i (NonceRound -> IntMap PubNonce
nrNonces NonceRound
nr) =
      if PubNonce -> ByteString
forall a. Encode a => a -> ByteString
encode PubNonce
prev ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
bytes then NonceRound -> Either Blame NonceRound
forall a b. b -> Either a b
Right NonceRound
nr else BlameReason -> Either Blame NonceRound
forall {b}. BlameReason -> Either Blame b
blame BlameReason
DuplicateContribution
  | Bool
otherwise = case ByteString -> Either DecodeError PubNonce
forall a. Encode a => ByteString -> Either DecodeError a
decode ByteString
bytes of
      Left DecodeError
err -> BlameReason -> Either Blame NonceRound
forall {b}. BlameReason -> Either Blame b
blame (DecodeError -> BlameReason
InvalidPubNonceEncoding DecodeError
err)
      Right PubNonce
pn -> NonceRound -> Either Blame NonceRound
forall a b. b -> Either a b
Right NonceRound
nr{nrNonces = IntMap.insert i pn (nrNonces nr)}
 where
  blame :: BlameReason -> Either Blame b
blame = Blame -> Either Blame b
forall a b. a -> Either a b
Left (Blame -> Either Blame b)
-> (BlameReason -> Blame) -> BlameReason -> Either Blame b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> BlameReason -> Blame
Blame Int
i

-- | The signers whose public nonce has not been received yet, in increasing order.
nonceRoundMissing :: NonceRound -> [Int]
nonceRoundMissing :: NonceRound -> [Int]
nonceRoundMissing NonceRound
nr = Int -> IntMap PubNonce -> [Int]
forall a. Int -> IntMap a -> [Int]
missingFrom (NonceRound -> Int
nrSize NonceRound
nr) (NonceRound -> IntMap PubNonce
nrNonces NonceRound
nr)

{- | Ends round one: aggregates the public nonces (BIP-327 @NonceAgg@).
Blames every signer whose nonce is missing with 'MissingContribution', in
increasing index order.
-}
finishNonceRound :: NonceRound -> Either (NonEmpty Blame) CollectedNonces
finishNonceRound :: NonceRound -> Either (NonEmpty Blame) CollectedNonces
finishNonceRound NonceRound
nr = do
  pns <- Int
-> IntMap PubNonce -> Either (NonEmpty Blame) (NonEmpty PubNonce)
forall a. Int -> IntMap a -> Either (NonEmpty Blame) (NonEmpty a)
collect (NonceRound -> Int
nrSize NonceRound
nr) (NonceRound -> IntMap PubNonce
nrNonces NonceRound
nr)
  Right (CollectedNonces (nrKeyAgg nr) pns (nonceAgg pns))

{- | The result of round one: every signer's public nonce and their
aggregate.
-}
data CollectedNonces = CollectedNonces
  { CollectedNonces -> KeyAggContext
cnKeyAgg :: !KeyAggContext
  , CollectedNonces -> NonEmpty PubNonce
cnPubNonces :: !(NonEmpty PubNonce)
  , CollectedNonces -> AggNonce
cnAggNonce :: !AggNonce
  }

instance NFData CollectedNonces where
  rnf :: CollectedNonces -> ()
rnf (CollectedNonces KeyAggContext
ctx NonEmpty PubNonce
pns AggNonce
agg) = KeyAggContext -> ()
forall a. NFData a => a -> ()
rnf KeyAggContext
ctx () -> () -> ()
forall a b. a -> b -> b
`seq` NonEmpty PubNonce -> ()
forall a. NFData a => a -> ()
rnf NonEmpty PubNonce
pns () -> () -> ()
forall a b. a -> b -> b
`seq` AggNonce -> ()
forall a. NFData a => a -> ()
rnf AggNonce
agg

-- | The key aggregation context the round was started with.
collectedKeyAgg :: CollectedNonces -> KeyAggContext
collectedKeyAgg :: CollectedNonces -> KeyAggContext
collectedKeyAgg = CollectedNonces -> KeyAggContext
cnKeyAgg

-- | Every signer's public nonce, in signer order.
collectedPubNonces :: CollectedNonces -> NonEmpty PubNonce
collectedPubNonces :: CollectedNonces -> NonEmpty PubNonce
collectedPubNonces = CollectedNonces -> NonEmpty PubNonce
cnPubNonces

-- | The aggregate nonce, to send to every signer ('encode' it).
collectedAggNonce :: CollectedNonces -> AggNonce
collectedAggNonce :: CollectedNonces -> AggNonce
collectedAggNonce = CollectedNonces -> AggNonce
cnAggNonce

-- Round two --------------------------------------------------------------------

{- | Round two in progress: the session, and the verified partial signatures
received so far, by signer index.
-}
data SigRound = SigRound
  { SigRound -> Session
srSession :: !Session
  , SigRound -> ByteString
srMessage :: !ByteString
  , SigRound -> Seq (PubKey, PubNonce)
srSigners :: !(Seq (PubKey, PubNonce))
  , SigRound -> IntMap PartialSignature
srPsigs :: !(IntMap PartialSignature)
  }

instance NFData SigRound where
  rnf :: SigRound -> ()
rnf (SigRound Session
ses ByteString
msg Seq (PubKey, PubNonce)
signers IntMap PartialSignature
psigs) = Session -> ()
forall a. NFData a => a -> ()
rnf Session
ses () -> () -> ()
forall a b. a -> b -> b
`seq` ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
msg () -> () -> ()
forall a b. a -> b -> b
`seq` Seq (PubKey, PubNonce) -> ()
forall a. NFData a => a -> ()
rnf Seq (PubKey, PubNonce)
signers () -> () -> ()
forall a b. a -> b -> b
`seq` IntMap PartialSignature -> ()
forall a. NFData a => a -> ()
rnf IntMap PartialSignature
psigs

{- | Starts round two: opens the session ('newSession') on the key
aggregation context and aggregate nonce of round one, for the message.
-}
newSigRound :: CollectedNonces -> ByteString -> SigRound
newSigRound :: CollectedNonces -> ByteString -> SigRound
newSigRound CollectedNonces
cn ByteString
msg =
  SigRound
    { srSession :: Session
srSession = KeyAggContext -> AggNonce -> ByteString -> Session
newSession (CollectedNonces -> KeyAggContext
cnKeyAgg CollectedNonces
cn) (CollectedNonces -> AggNonce
cnAggNonce CollectedNonces
cn) ByteString
msg
    , srMessage :: ByteString
srMessage = ByteString
msg
    , srSigners :: Seq (PubKey, PubNonce)
srSigners = [(PubKey, PubNonce)] -> Seq (PubKey, PubNonce)
forall a. [a] -> Seq a
Seq.fromList ([PubKey] -> [PubNonce] -> [(PubKey, PubNonce)]
forall a b. [a] -> [b] -> [(a, b)]
zip (NonEmpty PubKey -> [PubKey]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (KeyAggContext -> NonEmpty PubKey
keyAggPubKeys (CollectedNonces -> KeyAggContext
cnKeyAgg CollectedNonces
cn))) (NonEmpty PubNonce -> [PubNonce]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (CollectedNonces -> NonEmpty PubNonce
cnPubNonces CollectedNonces
cn)))
    , srPsigs :: IntMap PartialSignature
srPsigs = IntMap PartialSignature
forall a. IntMap a
IntMap.empty
    }

-- | The session the partial signatures are verified in (the coordinator can sign in it too).
sigRoundSession :: SigRound -> Session
sigRoundSession :: SigRound -> Session
sigRoundSession = SigRound -> Session
srSession

{- | Receives a signer's encoded partial signature (32 bytes) and verifies it
with 'partialSigVerify' against the signer's public key and public nonce.

Blames the signer with 'UnknownSigner', 'DuplicateContribution' (a
different partial signature was already accepted from it; the same bytes
again are accepted and change nothing), 'InvalidPartialSigEncoding' or
'InvalidPartialSignature'. On 'Left' the round is unchanged.
-}
receivePartialSig ::
  -- | Signer index, from the authenticated connection the bytes arrived on.
  Int ->
  -- | The encoded partial signature.
  ByteString ->
  SigRound ->
  Either Blame SigRound
receivePartialSig :: Int -> ByteString -> SigRound -> Either Blame SigRound
receivePartialSig Int
i ByteString
bytes SigRound
sr = case Int -> Seq (PubKey, PubNonce) -> Maybe (PubKey, PubNonce)
forall a. Int -> Seq a -> Maybe a
Seq.lookup Int
i (SigRound -> Seq (PubKey, PubNonce)
srSigners SigRound
sr) of
  Maybe (PubKey, PubNonce)
Nothing -> BlameReason -> Either Blame SigRound
forall {b}. BlameReason -> Either Blame b
blame BlameReason
UnknownSigner
  Just (PubKey
pk, PubNonce
pn) -> case Int -> IntMap PartialSignature -> Maybe PartialSignature
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
i (SigRound -> IntMap PartialSignature
srPsigs SigRound
sr) of
    Just PartialSignature
prev -> if PartialSignature -> ByteString
forall a. Encode a => a -> ByteString
encode PartialSignature
prev ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
bytes then SigRound -> Either Blame SigRound
forall a b. b -> Either a b
Right SigRound
sr else BlameReason -> Either Blame SigRound
forall {b}. BlameReason -> Either Blame b
blame BlameReason
DuplicateContribution
    Maybe PartialSignature
Nothing -> case ByteString -> Either DecodeError PartialSignature
forall a. Encode a => ByteString -> Either DecodeError a
decode ByteString
bytes of
      Left DecodeError
err -> BlameReason -> Either Blame SigRound
forall {b}. BlameReason -> Either Blame b
blame (DecodeError -> BlameReason
InvalidPartialSigEncoding DecodeError
err)
      Right PartialSignature
psig
        | Session -> PubKey -> PubNonce -> PartialSignature -> Bool
partialSigVerify (SigRound -> Session
srSession SigRound
sr) PubKey
pk PubNonce
pn PartialSignature
psig -> SigRound -> Either Blame SigRound
forall a b. b -> Either a b
Right SigRound
sr{srPsigs = IntMap.insert i psig (srPsigs sr)}
        | Bool
otherwise -> BlameReason -> Either Blame SigRound
forall {b}. BlameReason -> Either Blame b
blame BlameReason
InvalidPartialSignature
 where
  blame :: BlameReason -> Either Blame b
blame = Blame -> Either Blame b
forall a b. a -> Either a b
Left (Blame -> Either Blame b)
-> (BlameReason -> Blame) -> BlameReason -> Either Blame b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> BlameReason -> Blame
Blame Int
i

-- | The signers whose partial signature has not been accepted yet, in increasing order.
sigRoundMissing :: SigRound -> [Int]
sigRoundMissing :: SigRound -> [Int]
sigRoundMissing SigRound
sr = Int -> IntMap PartialSignature -> [Int]
forall a. Int -> IntMap a -> [Int]
missingFrom (Seq (PubKey, PubNonce) -> Int
forall a. Seq a -> Int
Seq.length (SigRound -> Seq (PubKey, PubNonce)
srSigners SigRound
sr)) (SigRound -> IntMap PartialSignature
srPsigs SigRound
sr)

-- | Why round two cannot produce a signature.
data SigRoundError
  = -- | Partial signatures are missing: blames each of those signers with 'MissingContribution'.
    SigRoundBlame !(NonEmpty Blame)
  | {- | Every partial signature verified, but their aggregate is not a valid
    BIP-340 signature. This happens if the final nonce is the point at
    infinity, for which BIP-327 substitutes the generator: the signers'
    nonces cancel out, which takes every signer colluding (an honest signer's
    nonce is unpredictable) or negligible luck. Otherwise the coordinator
    itself is faulty (a bug or, e.g., a bit flip). No single signer can be
    blamed.
    -}
    FinalSignatureInvalid
  deriving (SigRoundError -> SigRoundError -> Bool
(SigRoundError -> SigRoundError -> Bool)
-> (SigRoundError -> SigRoundError -> Bool) -> Eq SigRoundError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SigRoundError -> SigRoundError -> Bool
== :: SigRoundError -> SigRoundError -> Bool
$c/= :: SigRoundError -> SigRoundError -> Bool
/= :: SigRoundError -> SigRoundError -> Bool
Eq, Int -> SigRoundError -> ShowS
[SigRoundError] -> ShowS
SigRoundError -> String
(Int -> SigRoundError -> ShowS)
-> (SigRoundError -> String)
-> ([SigRoundError] -> ShowS)
-> Show SigRoundError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SigRoundError -> ShowS
showsPrec :: Int -> SigRoundError -> ShowS
$cshow :: SigRoundError -> String
show :: SigRoundError -> String
$cshowList :: [SigRoundError] -> ShowS
showList :: [SigRoundError] -> ShowS
Show)

instance Exception SigRoundError

instance NFData SigRoundError where
  rnf :: SigRoundError -> ()
rnf = SigRoundError -> ()
forall a. a -> ()
rwhnf

{- | Ends round two: aggregates the partial signatures (BIP-327
@PartialSigAgg@) and checks the result with 'verify' against the session's
'aggXOnlyPubKey' before returning it.
-}
finishSigRound :: SigRound -> Either SigRoundError Signature
finishSigRound :: SigRound -> Either SigRoundError Signature
finishSigRound SigRound
sr = do
  psigs <- (NonEmpty Blame -> SigRoundError)
-> Either (NonEmpty Blame) (NonEmpty PartialSignature)
-> Either SigRoundError (NonEmpty PartialSignature)
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first NonEmpty Blame -> SigRoundError
SigRoundBlame (Int
-> IntMap PartialSignature
-> Either (NonEmpty Blame) (NonEmpty PartialSignature)
forall a. Int -> IntMap a -> Either (NonEmpty Blame) (NonEmpty a)
collect (Seq (PubKey, PubNonce) -> Int
forall a. Seq a -> Int
Seq.length (SigRound -> Seq (PubKey, PubNonce)
srSigners SigRound
sr)) (SigRound -> IntMap PartialSignature
srPsigs SigRound
sr))
  let ses = SigRound -> Session
srSession SigRound
sr
      sig = Session -> NonEmpty PartialSignature -> Signature
partialSigAgg Session
ses NonEmpty PartialSignature
psigs
  if verify (aggXOnlyPubKey (sessionKeyAgg ses)) (srMessage sr) sig then Right sig else Left FinalSignatureInvalid