{-# LANGUAGE RecordWildCards #-}

module Crypto.HPKE.Context (
    -- * Sender
    ContextS,
    newContextS,
    seal,
    exportS,

    -- * Receiver
    ContextR,
    newContextR,
    open,
    exportR,
) where

import Control.Concurrent.MVar (MVar, modifyMVar, newMVar)
import qualified Control.Exception as E
import Data.ByteArray (xor)
import qualified Data.ByteString as BS
import Data.IORef (IORef, atomicModifyIORef', newIORef)

import Crypto.HPKE.Types

----------------------------------------------------------------

-- | Context for senders.
data ContextS = ContextS
    { ContextS -> IORef Integer
seqRefS :: IORef Integer
    , ContextS -> Seal
sealS :: Seal
    , ContextS -> ByteString
nonceBaseS :: Nonce
    , ContextS -> ByteString -> Int -> Either HPKEError ByteString
expandS :: Info -> Int -> Either HPKEError Key
    }

-- | Context for receivers.
data ContextR = ContextR
    { ContextR -> MVar Integer
seqVarR :: MVar Integer
    , ContextR -> Seal
openR :: Open
    , ContextR -> ByteString
nonceBaseR :: Nonce
    , ContextR -> ByteString -> Int -> Either HPKEError ByteString
expandR :: Info -> Int -> Either HPKEError Key
    }

----------------------------------------------------------------

-- | Encryption.
--   This throws 'HPKEError'.
--   Safe to call from multiple threads: each call gets its own nonce.
seal :: ContextS -> AAD -> PlainText -> IO CipherText
seal :: ContextS -> ByteString -> ByteString -> IO ByteString
seal ContextS{ByteString
IORef Integer
ByteString -> Int -> Either HPKEError ByteString
Seal
seqRefS :: ContextS -> IORef Integer
sealS :: ContextS -> Seal
nonceBaseS :: ContextS -> ByteString
expandS :: ContextS -> ByteString -> Int -> Either HPKEError ByteString
seqRefS :: IORef Integer
sealS :: Seal
nonceBaseS :: ByteString
expandS :: ByteString -> Int -> Either HPKEError ByteString
..} ByteString
aad ByteString
pt = do
    seqI <- IORef Integer -> (Integer -> (Integer, Integer)) -> IO Integer
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef Integer
seqRefS ((Integer -> (Integer, Integer)) -> IO Integer)
-> (Integer -> (Integer, Integer)) -> IO Integer
forall a b. (a -> b) -> a -> b
$ \Integer
i -> (Integer
i Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1, Integer
i)
    checkLimit nonceBaseS seqI
    either E.throwIO return $ sealS (computeNonce nonceBaseS seqI) aad pt

-- | Decryption.
--   This throws 'HPKEError'.
--   The sequence number advances only when decryption succeeds.
open
    :: ContextR -> AAD -> CipherText -> IO PlainText
open :: ContextR -> ByteString -> ByteString -> IO ByteString
open ContextR{ByteString
MVar Integer
ByteString -> Int -> Either HPKEError ByteString
Seal
seqVarR :: ContextR -> MVar Integer
openR :: ContextR -> Seal
nonceBaseR :: ContextR -> ByteString
expandR :: ContextR -> ByteString -> Int -> Either HPKEError ByteString
seqVarR :: MVar Integer
openR :: Seal
nonceBaseR :: ByteString
expandR :: ByteString -> Int -> Either HPKEError ByteString
..} ByteString
aad ByteString
ct = MVar Integer
-> (Integer -> IO (Integer, ByteString)) -> IO ByteString
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar Integer
seqVarR ((Integer -> IO (Integer, ByteString)) -> IO ByteString)
-> (Integer -> IO (Integer, ByteString)) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \Integer
seqI -> do
    ByteString -> Integer -> IO ()
checkLimit ByteString
nonceBaseR Integer
seqI
    case Seal
openR (ByteString -> Integer -> ByteString
computeNonce ByteString
nonceBaseR Integer
seqI) ByteString
aad ByteString
ct of
        Left HPKEError
err -> HPKEError -> IO (Integer, ByteString)
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO HPKEError
err
        Right ByteString
pt -> (Integer, ByteString) -> IO (Integer, ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Integer
seqI Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1, ByteString
pt)

computeNonce :: Nonce -> Integer -> Nonce
computeNonce :: ByteString -> Integer -> ByteString
computeNonce ByteString
nonce_base Integer
seqI = ByteString
seqBS ByteString -> ByteString -> ByteString
forall a b c.
(ByteArrayAccess a, ByteArrayAccess b, ByteArray c) =>
a -> b -> c
`xor` ByteString
nonce_base
  where
    seqBS :: ByteString
seqBS = Int -> Integer -> ByteString
forall ba. ByteArray ba => Int -> Integer -> ba
i2ospOf_ (ByteString -> Int
BS.length ByteString
nonce_base) Integer
seqI :: ByteString

-- RFC 9180 section 5.2: the sequence number must not wrap around.
checkLimit :: Nonce -> Integer -> IO ()
checkLimit :: ByteString -> Integer -> IO ()
checkLimit ByteString
nonce_base Integer
seqI
    | Integer
seqI Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
8 Int -> Int -> Int
forall a. Num a => a -> a -> a
* ByteString -> Int
BS.length ByteString
nonce_base) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1 =
        HPKEError -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO (HPKEError -> IO ()) -> HPKEError -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> HPKEError
MessageLimitReachedError String
"sequence number overflow"
    | Bool
otherwise = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

----------------------------------------------------------------

-- | Exporting secret.
--
-- RFC 9180 section 5.3 allows a length of at most @255 * Nh@, where @Nh@ is
-- the output of the KDF's hash; a longer one is 'Left' 'ExportError'.
exportS :: ContextS -> Info -> Int -> Either HPKEError Key
exportS :: ContextS -> ByteString -> Int -> Either HPKEError ByteString
exportS ContextS{ByteString
IORef Integer
ByteString -> Int -> Either HPKEError ByteString
Seal
seqRefS :: ContextS -> IORef Integer
sealS :: ContextS -> Seal
nonceBaseS :: ContextS -> ByteString
expandS :: ContextS -> ByteString -> Int -> Either HPKEError ByteString
seqRefS :: IORef Integer
sealS :: Seal
nonceBaseS :: ByteString
expandS :: ByteString -> Int -> Either HPKEError ByteString
..} ByteString
exporter_context Int
len =
    ByteString -> Int -> Either HPKEError ByteString
expandS ByteString
exporter_context Int
len

-- | Exporting secret.
--
-- RFC 9180 section 5.3 allows a length of at most @255 * Nh@, where @Nh@ is
-- the output of the KDF's hash; a longer one is 'Left' 'ExportError'.
exportR :: ContextR -> Info -> Int -> Either HPKEError Key
exportR :: ContextR -> ByteString -> Int -> Either HPKEError ByteString
exportR ContextR{ByteString
MVar Integer
ByteString -> Int -> Either HPKEError ByteString
Seal
seqVarR :: ContextR -> MVar Integer
openR :: ContextR -> Seal
nonceBaseR :: ContextR -> ByteString
expandR :: ContextR -> ByteString -> Int -> Either HPKEError ByteString
seqVarR :: MVar Integer
openR :: Seal
nonceBaseR :: ByteString
expandR :: ByteString -> Int -> Either HPKEError ByteString
..} ByteString
exporter_context Int
len =
    ByteString -> Int -> Either HPKEError ByteString
expandR ByteString
exporter_context Int
len

----------------------------------------------------------------

newContextS
    :: Key
    -> Nonce
    -> (Key -> Seal)
    -> (Info -> Int -> Either HPKEError Key)
    -> IO ContextS
newContextS :: ByteString
-> ByteString
-> (ByteString -> Seal)
-> (ByteString -> Int -> Either HPKEError ByteString)
-> IO ContextS
newContextS ByteString
key ByteString
nonce_base ByteString -> Seal
seal' ByteString -> Int -> Either HPKEError ByteString
expand = do
    seqref <- Integer -> IO (IORef Integer)
forall a. a -> IO (IORef a)
newIORef Integer
0
    return $
        ContextS
            { seqRefS = seqref
            , sealS = seal' key
            , nonceBaseS = nonce_base
            , expandS = expand
            }

----------------------------------------------------------------

newContextR
    :: Key
    -> Nonce
    -> (Key -> Open)
    -> (Info -> Int -> Either HPKEError Key)
    -> IO ContextR
newContextR :: ByteString
-> ByteString
-> (ByteString -> Seal)
-> (ByteString -> Int -> Either HPKEError ByteString)
-> IO ContextR
newContextR ByteString
key ByteString
nonce_base ByteString -> Seal
open' ByteString -> Int -> Either HPKEError ByteString
expand = do
    seqvar <- Integer -> IO (MVar Integer)
forall a. a -> IO (MVar a)
newMVar Integer
0
    return $
        ContextR
            { seqVarR = seqvar
            , openR = open' key
            , nonceBaseR = nonce_base
            , expandR = expand
            }