{-# OPTIONS_HADDOCK prune #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

-- |
-- Module: Lightning.Protocol.BOLT8
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Encrypted and authenticated transport for the Lightning Network, per
-- [BOLT #8](https://github.com/lightning/bolts/blob/master/08-transport.md):
-- the @Noise_XK_secp256k1_ChaChaPoly_SHA256@ handshake, followed by
-- length-prefixed, authenticated encryption of messages.
--
-- The library is pure; reading from and writing to the network is up
-- to the caller.
--
-- = Handshake
--
-- The /initiator/ knows the responder's static public key in advance.
-- It sends act one ('act1'), receives act two, and replies with act
-- three ('act3'). The /responder/ receives act one, replies with act two
-- ('act2'), and receives act three ('finalize'), which authenticates
-- the initiator's static key. Both sides end up with a t'Handshake'.
--
-- >>> :set -XOverloadedStrings
-- >>> import qualified Data.ByteString as BS
-- >>> let Just i = keypair (BS.replicate 32 0x11)
-- >>> let Just r = keypair (BS.replicate 32 0x21)
-- >>> -- initiator, knowing r's public key; entropy must be random!
-- >>> let Right (msg1, i_hs) = act1 i (keypair_pub r) (BS.replicate 32 0x12)
-- >>> -- responder
-- >>> let Right (msg2, r_hs) = act2 r (BS.replicate 32 0x22) msg1
-- >>> -- initiator
-- >>> let Right (msg3, i_res) = act3 i_hs msg2
-- >>> -- responder
-- >>> let Right r_res = finalize r_hs msg3
-- >>> handshake_remote_static r_res == keypair_pub i
-- True
--
-- = Transport
--
-- A t'Handshake' carries a t'Sender' for outgoing messages and a
-- t'Receiver' for incoming ones. They are independent, so a writer
-- thread can own the t'Sender' and a reader thread the t'Receiver'.
--
-- >>> let Right (ct, i_snd) = encrypt (handshake_sender i_res) "hello"
-- >>> fmap fst (decrypt (handshake_receiver r_res) ct)
-- Right "hello"
--
-- On a byte stream, read exactly 18 bytes and pass them to
-- 'decrypt_header', which returns the number of bytes to read next;
-- then read exactly that many bytes and pass them to 'decrypt_body'.
-- 'decrypt' does both for a buffer holding exactly one frame.
--
-- Keys rotate every 1000 nonces, i.e. every 500 messages in each
-- direction; this is handled internally. Messages are at most 65535
-- bytes.
--
-- = Security
--
-- * __Use each state exactly once.__ Every function that takes an
--   t'Initiator', t'Responder', t'Sender', t'Receiver' or t'Pending'
--   returns the next state, and the caller must continue with that.
--   States are ordinary immutable values, so nothing stops an old one
--   from being used again, and doing so is catastrophic: encrypting
--   twice with the same t'Sender' reuses a nonce, which reveals the XOR
--   of the two plaintexts and allows forgeries, and decrypting with an
--   old t'Receiver' accepts replayed frames.
--
-- * __Ephemeral entropy must be fresh.__ The 32 bytes passed to 'act1'
--   and 'act2' are used directly as the ephemeral secret key. They
--   must come from a cryptographically secure random source, be
--   uniformly random, and never be reused.
--
-- * __Any error is fatal.__ BOLT #8 requires terminating the
--   connection on any handshake or transport failure. Don't retry with
--   the previous state. The one exception is 'encrypt' rejecting an
--   oversized message, which advances nothing.

module Lightning.Protocol.BOLT8 (
    -- * Keys
    Keypair
  , keypair
  , keypair_pub
  , Pub
  , parse_pub
  , serialize_pub

    -- * Handshake
  , Handshake
  , handshake_sender
  , handshake_receiver
  , handshake_remote_static

    -- ** Initiator
  , Initiator
  , act1
  , act3

    -- ** Responder
  , Responder
  , act2
  , finalize

    -- * Transport
  , Sender
  , encrypt
  , Receiver
  , decrypt
  , Pending
  , decrypt_header
  , decrypt_body

    -- * Errors
  , Error(..)
  ) where

import Control.DeepSeq (NFData(..))
import Control.Monad (guard, unless)
import qualified Crypto.AEAD.ChaCha20Poly1305 as AEAD
import qualified Crypto.Curve.Secp256k1 as Secp256k1
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Crypto.KDF.HMAC as HKDF
import Data.Bits (unsafeShiftR, (.&.))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BU
import Data.Word (Word8, Word16, Word64)
import GHC.Generics (Generic)

-- keys -----------------------------------------------------------------------

-- A secret key: 32 bytes encoding a valid secp256k1 scalar.
newtype Sec = Sec BS.ByteString

-- | A secp256k1 public key.
--
--   'Show' renders the 33-byte compressed encoding in hex.
newtype Pub = Pub Secp256k1.Projective

instance Eq Pub where
  Pub Projective
a == :: Pub -> Pub -> Bool
== Pub Projective
b =
    Projective -> ByteString
Secp256k1.serialize_point Projective
a ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== Projective -> ByteString
Secp256k1.serialize_point Projective
b

instance Show Pub where
  showsPrec :: Int -> Pub -> ShowS
showsPrec Int
d Pub
p = Bool -> ShowS -> ShowS
showParen (Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
10) (ShowS -> ShowS) -> ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$
    String -> ShowS
showString String
"Pub " ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> ShowS
forall a. Show a => a -> ShowS
shows (ByteString -> String
hex (Pub -> ByteString
serialize_pub Pub
p))

instance NFData Pub where
  rnf :: Pub -> ()
rnf (Pub Projective
p) = Projective
p Projective -> () -> ()
forall a b. a -> b -> b
`seq` ()

-- | A secp256k1 keypair: a secret key and its public key.
--
--   Has no 'Show' or 'Eq' instance, as it contains secret material.
data Keypair = Keypair !Sec !Pub

instance NFData Keypair where
  rnf :: Keypair -> ()
rnf (Keypair (Sec ByteString
s) Pub
p) = ByteString
s ByteString -> () -> ()
forall a b. a -> b -> b
`seq` Pub -> ()
forall a. NFData a => a -> ()
rnf Pub
p

-- | Construct a keypair from a 32-byte secret key.
--
--   The bytes are used directly as the secret key, so they must be
--   uniformly random and kept secret. Returns 'Nothing' if the input
--   is not 32 bytes, or is not a valid secp256k1 secret key (zero, or
--   not less than the curve order).
--
--   >>> import Data.Maybe (isJust)
--   >>> isJust (keypair (BS.replicate 32 0x11))
--   True
--   >>> isJust (keypair (BS.replicate 32 0x00))
--   False
keypair :: BS.ByteString -> Maybe Keypair
keypair :: ByteString -> Maybe Keypair
keypair ByteString
sec = do
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ByteString -> Int
BS.length ByteString
sec Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
32)
  k <- ByteString -> Maybe Wider
Secp256k1.parse_int256 ByteString
sec
  p <- Secp256k1.derive_pub k
  pure $! Keypair (Sec sec) (Pub p)

-- | The public key of a keypair.
--
--   >>> let Just r = keypair (BS.replicate 32 0x21)
--   >>> keypair_pub r
--   Pub "028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7"
keypair_pub :: Keypair -> Pub
keypair_pub :: Keypair -> Pub
keypair_pub (Keypair Sec
_ Pub
p) = Pub
p

-- | Parse a 33-byte compressed public key.
--
--   >>> let Just r = keypair (BS.replicate 32 0x21)
--   >>> parse_pub (serialize_pub (keypair_pub r)) == Just (keypair_pub r)
--   True
--   >>> parse_pub (BS.replicate 33 0x04)
--   Nothing
parse_pub :: BS.ByteString -> Maybe Pub
parse_pub :: ByteString -> Maybe Pub
parse_pub ByteString
bs = do
  Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
33)
  p <- ByteString -> Maybe Projective
Secp256k1.parse_point ByteString
bs
  pure (Pub p)

-- | Serialize a public key in 33-byte compressed form.
--
--   >>> let Just r = keypair (BS.replicate 32 0x21)
--   >>> BS.length (serialize_pub (keypair_pub r))
--   33
serialize_pub :: Pub -> BS.ByteString
serialize_pub :: Pub -> ByteString
serialize_pub (Pub Projective
p) = Projective -> ByteString
Secp256k1.serialize_point Projective
p

-- handshake state ------------------------------------------------------------

-- | The initiator's handshake state between acts one and three.
--
--   Produced by 'act1' and consumed by 'act3'. Contains secret
--   material; use it once.
data Initiator = Initiator
  {-# UNPACK #-} !BS.ByteString -- handshake hash
  {-# UNPACK #-} !BS.ByteString -- chaining key
  !Sec                          -- ephemeral secret
  !Keypair                      -- local static keypair
  !Pub                          -- remote static public key

instance NFData Initiator where
  rnf :: Initiator -> ()
rnf (Initiator ByteString
h ByteString
ck (Sec ByteString
e) Keypair
s Pub
rs) =
    ByteString
h ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
ck ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
e ByteString -> () -> ()
forall a b. a -> b -> b
`seq` Keypair -> ()
forall a. NFData a => a -> ()
rnf Keypair
s () -> () -> ()
forall a b. a -> b -> b
`seq` Pub -> ()
forall a. NFData a => a -> ()
rnf Pub
rs

-- | The responder's handshake state between acts two and three.
--
--   Produced by 'act2' and consumed by 'finalize'. Contains secret
--   material; use it once.
data Responder = Responder
  {-# UNPACK #-} !BS.ByteString -- handshake hash
  {-# UNPACK #-} !BS.ByteString -- chaining key
  {-# UNPACK #-} !BS.ByteString -- temp_k2
  !Sec                          -- ephemeral secret

instance NFData Responder where
  rnf :: Responder -> ()
rnf (Responder ByteString
h ByteString
ck ByteString
k (Sec ByteString
e)) = ByteString
h ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
ck ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
k ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
e ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ()

-- | The result of a successful handshake: the initial transport
--   states and the remote party's authenticated static public key.
--
--   Take the t'Sender' and t'Receiver' out once, right after the
--   handshake, and don't keep the t'Handshake' around: it always yields
--   the /initial/ states, and encrypting with the initial t'Sender'
--   a second time reuses a nonce.
data Handshake = Handshake !Sender !Receiver !Pub

instance NFData Handshake where
  rnf :: Handshake -> ()
rnf (Handshake Sender
s Receiver
r Pub
p) = Sender -> ()
forall a. NFData a => a -> ()
rnf Sender
s () -> () -> ()
forall a b. a -> b -> b
`seq` Receiver -> ()
forall a. NFData a => a -> ()
rnf Receiver
r () -> () -> ()
forall a b. a -> b -> b
`seq` Pub -> ()
forall a. NFData a => a -> ()
rnf Pub
p

-- | The initial t'Sender', for encrypting outgoing messages.
--
--   Call this once per handshake. Every call returns the same initial
--   state, so encrypting with the result of a second call reuses a
--   nonce.
handshake_sender :: Handshake -> Sender
handshake_sender :: Handshake -> Sender
handshake_sender (Handshake Sender
s Receiver
_ Pub
_) = Sender
s

-- | The initial t'Receiver', for decrypting incoming messages.
--
--   Call this once per handshake. Every call returns the same initial
--   state, so decrypting with the result of a second call accepts
--   replayed frames.
handshake_receiver :: Handshake -> Receiver
handshake_receiver :: Handshake -> Receiver
handshake_receiver (Handshake Sender
_ Receiver
r Pub
_) = Receiver
r

-- | The remote party's static public key, authenticated by the
--   handshake. For the initiator, this is the key passed to 'act1'.
handshake_remote_static :: Handshake -> Pub
handshake_remote_static :: Handshake -> Pub
handshake_remote_static (Handshake Sender
_ Receiver
_ Pub
p) = Pub
p

-- transport state ------------------------------------------------------------

-- One direction's cipher state.
data Cipher = Cipher
  {-# UNPACK #-} !BS.ByteString -- key
  {-# UNPACK #-} !Word64        -- nonce, always < 1000
  {-# UNPACK #-} !BS.ByteString -- chaining key

instance NFData Cipher where
  rnf :: Cipher -> ()
rnf (Cipher ByteString
k Word64
n ByteString
ck) = ByteString
k ByteString -> () -> ()
forall a b. a -> b -> b
`seq` Word64
n Word64 -> () -> ()
forall a b. a -> b -> b
`seq` ByteString
ck ByteString -> () -> ()
forall a b. a -> b -> b
`seq` ()

-- | State for encrypting outgoing messages.
--
--   Each 'encrypt' returns the next t'Sender'. Never use a t'Sender'
--   twice: doing so reuses a nonce.
newtype Sender = Sender Cipher

instance NFData Sender where
  rnf :: Sender -> ()
rnf (Sender Cipher
c) = Cipher -> ()
forall a. NFData a => a -> ()
rnf Cipher
c

-- | State for decrypting incoming messages.
--
--   Each 'decrypt' or 'decrypt_header' consumes the t'Receiver'.
--   Never use a t'Receiver' twice: doing so accepts replayed frames.
newtype Receiver = Receiver Cipher

instance NFData Receiver where
  rnf :: Receiver -> ()
rnf (Receiver Cipher
c) = Cipher -> ()
forall a. NFData a => a -> ()
rnf Cipher
c

-- | A t'Receiver' that has decrypted a frame header and awaits the
--   frame body.
--
--   Produced by 'decrypt_header' and consumed by 'decrypt_body'. Use
--   it once.
data Pending = Pending {-# UNPACK #-} !Int !Cipher

instance NFData Pending where
  rnf :: Pending -> ()
rnf (Pending Int
n Cipher
c) = Int
n Int -> () -> ()
forall a b. a -> b -> b
`seq` Cipher -> ()
forall a. NFData a => a -> ()
rnf Cipher
c

-- errors ---------------------------------------------------------------------

-- | Handshake and transport errors.
--
--   Any error is fatal for the connection.
data Error =
    InvalidEntropy
    -- ^ ephemeral entropy is not a valid secret key
  | InvalidLength
    -- ^ input of the wrong length, or a payload over 65535 bytes
  | InvalidVersion
    -- ^ unknown handshake version
  | InvalidPub
    -- ^ invalid public key in a handshake message
  | InvalidMAC
    -- ^ authentication failed
  deriving (Error -> Error -> Bool
(Error -> Error -> Bool) -> (Error -> Error -> Bool) -> Eq Error
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Error -> Error -> Bool
== :: Error -> Error -> Bool
$c/= :: Error -> Error -> Bool
/= :: Error -> Error -> Bool
Eq, Int -> Error -> ShowS
[Error] -> ShowS
Error -> String
(Int -> Error -> ShowS)
-> (Error -> String) -> ([Error] -> ShowS) -> Show Error
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Error -> ShowS
showsPrec :: Int -> Error -> ShowS
$cshow :: Error -> String
show :: Error -> String
$cshowList :: [Error] -> ShowS
showList :: [Error] -> ShowS
Show, (forall x. Error -> Rep Error x)
-> (forall x. Rep Error x -> Error) -> Generic Error
forall x. Rep Error x -> Error
forall x. Error -> Rep Error x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Error -> Rep Error x
from :: forall x. Error -> Rep Error x
$cto :: forall x. Rep Error x -> Error
to :: forall x. Rep Error x -> Error
Generic)

instance NFData Error

-- protocol constants ---------------------------------------------------------

_PROTOCOL_NAME :: BS.ByteString
_PROTOCOL_NAME :: ByteString
_PROTOCOL_NAME = ByteString
"Noise_XK_secp256k1_ChaChaPoly_SHA256"

_PROLOGUE :: BS.ByteString
_PROLOGUE :: ByteString
_PROLOGUE = ByteString
"lightning"

-- cryptographic primitives ---------------------------------------------------

-- ECDH as specified by BOLT #8: SHA256 of the compressed shared point.
--
-- 'Nothing' is unreachable for a valid secret key and a parsed point.
ecdh :: Sec -> Pub -> Maybe BS.ByteString
ecdh :: Sec -> Pub -> Maybe ByteString
ecdh (Sec ByteString
sec) (Pub Projective
pub) = do
  k <- ByteString -> Maybe Wider
Secp256k1.parse_int256 ByteString
sec
  pt <- Secp256k1.mul pub k
  pure (SHA256.hash (Secp256k1.serialize_point pt))

-- h' = SHA256(h || dat)
mix_hash :: BS.ByteString -> BS.ByteString -> BS.ByteString
mix_hash :: ByteString -> ByteString -> ByteString
mix_hash ByteString
h ByteString
dat = ByteString -> ByteString
SHA256.hash (ByteString
h ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
dat)

-- (ck', k) = HKDF(ck, ikm), with ck as salt and empty info.
--
-- HKDF limits output to 255 * hashlen bytes (8160 for SHA256), so
-- 'Nothing' is impossible for the 64 bytes requested here.
mix_key
  :: BS.ByteString
  -> BS.ByteString
  -> (BS.ByteString, BS.ByteString)
mix_key :: ByteString -> ByteString -> (ByteString, ByteString)
mix_key ByteString
ck ByteString
ikm =
  case (ByteString -> ByteString -> ByteString)
-> ByteString
-> ByteString
-> Word64
-> ByteString
-> Maybe ByteString
HKDF.derive ByteString -> ByteString -> ByteString
hmac ByteString
ck ByteString
forall a. Monoid a => a
mempty Word64
64 ByteString
ikm of
    Maybe ByteString
Nothing ->
      String -> (ByteString, ByteString)
forall a. HasCallStack => String -> a
error String
"ppad-bolt8: internal error, please report a bug!"
    Just ByteString
output -> Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
32 ByteString
output
  where
    hmac :: ByteString -> ByteString -> ByteString
hmac ByteString
k ByteString
b = case ByteString -> ByteString -> MAC
SHA256.hmac ByteString
k ByteString
b of
      SHA256.MAC ByteString
mac -> ByteString
mac

-- ChaCha20-Poly1305 encryption, returning ciphertext || MAC.
--
-- Keys are always 32 bytes (halves of HKDF output), nonces always 12
-- bytes, and plaintexts at most 65535 bytes (far below the ChaCha20
-- counter limit), so encryption cannot fail.
encrypt_with_ad
  :: BS.ByteString -- ^ key (32 bytes)
  -> Word64        -- ^ nonce
  -> BS.ByteString -- ^ associated data
  -> BS.ByteString -- ^ plaintext
  -> BS.ByteString
encrypt_with_ad :: ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
key Word64
n ByteString
ad ByteString
pt =
  case ByteString
-> ByteString
-> ByteString
-> ByteString
-> Either Error (ByteString, ByteString)
AEAD.encrypt ByteString
ad ByteString
key (Word64 -> ByteString
encode_nonce Word64
n) ByteString
pt of
    Left Error
_ ->
      String -> ByteString
forall a. HasCallStack => String -> a
error String
"ppad-bolt8: internal error, please report a bug!"
    Right (ByteString
ct, ByteString
mac) -> ByteString
ct ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
mac

-- ChaCha20-Poly1305 decryption of ciphertext || MAC.
decrypt_with_ad
  :: BS.ByteString       -- ^ key (32 bytes)
  -> Word64              -- ^ nonce
  -> BS.ByteString       -- ^ associated data
  -> BS.ByteString       -- ^ ciphertext || mac
  -> Maybe BS.ByteString -- ^ plaintext
decrypt_with_ad :: ByteString
-> Word64 -> ByteString -> ByteString -> Maybe ByteString
decrypt_with_ad ByteString
key Word64
n ByteString
ad ByteString
ctmac
  | ByteString -> Int
BS.length ByteString
ctmac Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
16 = Maybe ByteString
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let (ByteString
ct, ByteString
mac) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (ByteString -> Int
BS.length ByteString
ctmac Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
16) ByteString
ctmac
      in  case ByteString
-> ByteString
-> ByteString
-> (ByteString, ByteString)
-> Either Error ByteString
AEAD.decrypt ByteString
ad ByteString
key (Word64 -> ByteString
encode_nonce Word64
n) (ByteString
ct, ByteString
mac) of
            Left Error
_   -> Maybe ByteString
forall a. Maybe a
Nothing
            Right ByteString
pt -> ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
pt

-- 96-bit nonce: 4 zero bytes followed by the 64-bit nonce, little-endian
encode_nonce :: Word64 -> BS.ByteString
encode_nonce :: Word64 -> ByteString
encode_nonce Word64
n = Int -> Word8 -> ByteString
BS.replicate Int
4 Word8
0x00 ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> [Word8] -> ByteString
BS.pack [
    Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi Word64
n
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
8)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
16)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
24)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
32)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
40)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
48)
  , Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
n Int
56)
  ]

-- big-endian 16-bit encoding
encode_be16 :: Word16 -> BS.ByteString
encode_be16 :: Word16 -> ByteString
encode_be16 Word16
n = [Word8] -> ByteString
BS.pack [Word16 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi (Word16 -> Int -> Word16
forall a. Bits a => a -> Int -> a
unsafeShiftR Word16
n Int
8), Word16 -> Word8
forall a b. (Integral a, Num b) => a -> b
fi Word16
n]

-- big-endian 16-bit decoding of exactly two bytes
decode_be16 :: BS.ByteString -> Maybe Word16
decode_be16 :: ByteString -> Maybe Word16
decode_be16 ByteString
bs
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
2 = Maybe Word16
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let !b0 :: Word8
b0 = ByteString -> Int -> Word8
BU.unsafeIndex ByteString
bs Int
0
          !b1 :: Word8
b1 = ByteString -> Int -> Word8
BU.unsafeIndex ByteString
bs Int
1
      in  Word16 -> Maybe Word16
forall a. a -> Maybe a
Just (Word8 -> Word16
forall a b. (Integral a, Num b) => a -> b
fi Word8
b0 Word16 -> Word16 -> Word16
forall a. Num a => a -> a -> a
* Word16
0x100 Word16 -> Word16 -> Word16
forall a. Num a => a -> a -> a
+ Word8 -> Word16
forall a b. (Integral a, Num b) => a -> b
fi Word8
b1)

-- handshake ------------------------------------------------------------------

-- Initial (h, ck), given the responder's static public key:
--
--   h = SHA256(protocol_name); ck = h
--   h = SHA256(h || prologue)
--   h = SHA256(h || rs.pub)
initial_state :: Pub -> (BS.ByteString, BS.ByteString)
initial_state :: Pub -> (ByteString, ByteString)
initial_state Pub
rs =
  let !h0 :: ByteString
h0 = ByteString -> ByteString
SHA256.hash ByteString
_PROTOCOL_NAME
      !h1 :: ByteString
h1 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h0 ByteString
_PROLOGUE
      !h2 :: ByteString
h2 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h1 (Pub -> ByteString
serialize_pub Pub
rs)
  in  (ByteString
h2, ByteString
h0)

-- Split a 50-byte act one or act two message into its ephemeral public
-- key and MAC, checking length and version.
parse_act :: BS.ByteString -> Either Error (BS.ByteString, BS.ByteString)
parse_act :: ByteString -> Either Error (ByteString, ByteString)
parse_act ByteString
msg = do
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Int
BS.length ByteString
msg Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
50) Error
InvalidLength
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Word8
BU.unsafeHead ByteString
msg Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0x00) Error
InvalidVersion
  let !(ByteString
e, ByteString
c) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
33 (ByteString -> ByteString
BU.unsafeTail ByteString
msg)
  (ByteString, ByteString) -> Either Error (ByteString, ByteString)
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString
e, ByteString
c)

-- | Initiator: produce act one (50 bytes).
--
--   Takes the local static keypair, the responder's static public key,
--   and 32 bytes of entropy for the ephemeral key. Returns act one and
--   the state for 'act3'.
--
--   The entropy is used directly as the ephemeral secret key. It must
--   be fresh, uniformly random output of a cryptographically secure
--   random source, and must never be reused. Fails with
--   'InvalidEntropy' if it is not a valid secret key.
--
--   >>> let Just i = keypair (BS.replicate 32 0x11)
--   >>> let Just r = keypair (BS.replicate 32 0x21)
--   >>> let ent = BS.replicate 32 0x12 -- use random bytes in practice
--   >>> fmap (BS.length . fst) (act1 i (keypair_pub r) ent)
--   Right 50
act1
  :: Keypair       -- ^ local static keypair
  -> Pub           -- ^ responder's static public key
  -> BS.ByteString -- ^ 32 bytes of fresh entropy
  -> Either Error (BS.ByteString, Initiator)
act1 :: Keypair
-> Pub -> ByteString -> Either Error (ByteString, Initiator)
act1 Keypair
s Pub
rs ByteString
ent = do
  Keypair e_sec e_pub <- Error -> Maybe Keypair -> Either Error Keypair
forall e a. e -> Maybe a -> Either e a
note Error
InvalidEntropy (ByteString -> Maybe Keypair
keypair ByteString
ent)
  let !(h0, ck0) = initial_state rs
      !e_bytes = Pub -> ByteString
serialize_pub Pub
e_pub
      !h1 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h0 ByteString
e_bytes
  es <- note InvalidPub (ecdh e_sec rs)
  let !(ck1, temp_k1) = mix_key ck0 es
      !c = ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
temp_k1 Word64
0 ByteString
h1 ByteString
BS.empty
      !h2 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h1 ByteString
c
      !msg = Word8 -> ByteString -> ByteString
BS.cons Word8
0x00 (ByteString
e_bytes ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
c)
  pure (msg, Initiator h2 ck1 e_sec s rs)

-- | Responder: process act one and produce act two (50 bytes).
--
--   Takes the local static keypair, 32 bytes of entropy for the
--   ephemeral key, and act one. Returns act two and the state for
--   'finalize'.
--
--   The entropy is used directly as the ephemeral secret key. It must
--   be fresh, uniformly random output of a cryptographically secure
--   random source, and must never be reused. Fails with
--   'InvalidEntropy' if it is not a valid secret key.
--
--   Any error means the connection must be terminated.
--
--   >>> let Just i = keypair (BS.replicate 32 0x11)
--   >>> let Just r = keypair (BS.replicate 32 0x21)
--   >>> let Right (msg1, _) = act1 i (keypair_pub r) (BS.replicate 32 0x12)
--   >>> fmap (BS.length . fst) (act2 r (BS.replicate 32 0x22) msg1)
--   Right 50
--   >>> fmap fst (act2 r (BS.replicate 32 0x22) (BS.take 49 msg1))
--   Left InvalidLength
act2
  :: Keypair       -- ^ local static keypair
  -> BS.ByteString -- ^ 32 bytes of fresh entropy
  -> BS.ByteString -- ^ act one
  -> Either Error (BS.ByteString, Responder)
act2 :: Keypair
-> ByteString -> ByteString -> Either Error (ByteString, Responder)
act2 (Keypair Sec
s_sec Pub
s_pub) ByteString
ent ByteString
msg1 = do
  (re_bytes, c) <- ByteString -> Either Error (ByteString, ByteString)
parse_act ByteString
msg1
  re <- note InvalidPub (parse_pub re_bytes)
  Keypair e_sec e_pub <- note InvalidEntropy (keypair ent)
  let !(h0, ck0) = initial_state s_pub
      !h1 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h0 ByteString
re_bytes
  es <- note InvalidPub (ecdh s_sec re)
  let !(ck1, temp_k1) = mix_key ck0 es
  _ <- note InvalidMAC (decrypt_with_ad temp_k1 0 h1 c)
  let !h2 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h1 ByteString
c
      !e_bytes = Pub -> ByteString
serialize_pub Pub
e_pub
      !h3 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h2 ByteString
e_bytes
  ee <- note InvalidPub (ecdh e_sec re)
  let !(ck2, temp_k2) = mix_key ck1 ee
      !c2 = ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
temp_k2 Word64
0 ByteString
h3 ByteString
BS.empty
      !h4 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h3 ByteString
c2
      !msg = Word8 -> ByteString -> ByteString
BS.cons Word8
0x00 (ByteString
e_bytes ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
c2)
  pure (msg, Responder h4 ck2 temp_k2 e_sec)

-- | Initiator: process act two and produce act three (66 bytes),
--   completing the handshake.
--
--   Any error means the connection must be terminated.
--
--   Continuing the module-level example:
--
--   >>> fmap (BS.length . fst) (act3 i_hs msg2)
--   Right 66
act3
  :: Initiator     -- ^ state from 'act1'
  -> BS.ByteString -- ^ act two
  -> Either Error (BS.ByteString, Handshake)
act3 :: Initiator -> ByteString -> Either Error (ByteString, Handshake)
act3 (Initiator ByteString
h ByteString
ck Sec
e_sec (Keypair Sec
s_sec Pub
s_pub) Pub
rs) ByteString
msg2 = do
  (re_bytes, c) <- ByteString -> Either Error (ByteString, ByteString)
parse_act ByteString
msg2
  re <- note InvalidPub (parse_pub re_bytes)
  let !h1 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h ByteString
re_bytes
  ee <- note InvalidPub (ecdh e_sec re)
  let !(ck1, temp_k2) = mix_key ck ee
  _ <- note InvalidMAC (decrypt_with_ad temp_k2 0 h1 c)
  let !h2 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h1 ByteString
c
      !c3 = ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
temp_k2 Word64
1 ByteString
h2 (Pub -> ByteString
serialize_pub Pub
s_pub)
      !h3 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h2 ByteString
c3
  se <- note InvalidPub (ecdh s_sec re)
  let !(ck2, temp_k3) = mix_key ck1 se
      !t = ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
temp_k3 Word64
0 ByteString
h3 ByteString
BS.empty
      !(sk, rk) = mix_key ck2 BS.empty
      !msg = Word8 -> ByteString -> ByteString
BS.cons Word8
0x00 (ByteString
c3 ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
t)
      !hs = Sender -> Receiver -> Pub -> Handshake
Handshake (Cipher -> Sender
Sender (ByteString -> Word64 -> ByteString -> Cipher
Cipher ByteString
sk Word64
0 ByteString
ck2))
                      (Cipher -> Receiver
Receiver (ByteString -> Word64 -> ByteString -> Cipher
Cipher ByteString
rk Word64
0 ByteString
ck2)) Pub
rs
  pure (msg, hs)

-- | Responder: process act three, completing the handshake and
--   authenticating the initiator's static public key.
--
--   Any error means the connection must be terminated.
--
--   Continuing the module-level example:
--
--   >>> let Right r_res' = finalize r_hs msg3
--   >>> handshake_remote_static r_res' == keypair_pub i
--   True
finalize
  :: Responder     -- ^ state from 'act2'
  -> BS.ByteString -- ^ act three
  -> Either Error Handshake
finalize :: Responder -> ByteString -> Either Error Handshake
finalize (Responder ByteString
h ByteString
ck ByteString
temp_k2 Sec
e_sec) ByteString
msg3 = do
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Int
BS.length ByteString
msg3 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
66) Error
InvalidLength
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Word8
BU.unsafeHead ByteString
msg3 Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0x00) Error
InvalidVersion
  let !(ByteString
c, ByteString
t) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
49 (ByteString -> ByteString
BU.unsafeTail ByteString
msg3)
  rs_bytes <- Error -> Maybe ByteString -> Either Error ByteString
forall e a. e -> Maybe a -> Either e a
note Error
InvalidMAC (ByteString
-> Word64 -> ByteString -> ByteString -> Maybe ByteString
decrypt_with_ad ByteString
temp_k2 Word64
1 ByteString
h ByteString
c)
  rs <- note InvalidPub (parse_pub rs_bytes)
  let !h1 = ByteString -> ByteString -> ByteString
mix_hash ByteString
h ByteString
c
  se <- note InvalidPub (ecdh e_sec rs)
  let !(ck1, temp_k3) = mix_key ck se
  _ <- note InvalidMAC (decrypt_with_ad temp_k3 0 h1 t)
  let !(rk, sk) = mix_key ck1 BS.empty
  pure (Handshake (Sender (Cipher sk 0 ck1)) (Receiver (Cipher rk 0 ck1)) rs)

-- transport ------------------------------------------------------------------

-- Encrypt under the current key and nonce, then advance.
seal :: Cipher -> BS.ByteString -> (BS.ByteString, Cipher)
seal :: Cipher -> ByteString -> (ByteString, Cipher)
seal c :: Cipher
c@(Cipher ByteString
k Word64
n ByteString
_) ByteString
pt =
  let !ct :: ByteString
ct = ByteString -> Word64 -> ByteString -> ByteString -> ByteString
encrypt_with_ad ByteString
k Word64
n ByteString
BS.empty ByteString
pt
  in  (ByteString
ct, Cipher -> Cipher
step Cipher
c)

-- Decrypt under the current key and nonce, then advance.
open :: Cipher -> BS.ByteString -> Maybe (BS.ByteString, Cipher)
open :: Cipher -> ByteString -> Maybe (ByteString, Cipher)
open c :: Cipher
c@(Cipher ByteString
k Word64
n ByteString
_) ByteString
ct = do
  pt <- ByteString
-> Word64 -> ByteString -> ByteString -> Maybe ByteString
decrypt_with_ad ByteString
k Word64
n ByteString
BS.empty ByteString
ct
  pure (pt, step c)

-- Increment the nonce, rotating the key once it reaches 1000:
--
--   (ck', k') = HKDF(ck, k), n' = 0
step :: Cipher -> Cipher
step :: Cipher -> Cipher
step (Cipher ByteString
k Word64
n ByteString
ck)
  | Word64
n' Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
1000 =
      let !(ByteString
ck', ByteString
k') = ByteString -> ByteString -> (ByteString, ByteString)
mix_key ByteString
ck ByteString
k
      in  ByteString -> Word64 -> ByteString -> Cipher
Cipher ByteString
k' Word64
0 ByteString
ck'
  | Bool
otherwise = ByteString -> Word64 -> ByteString -> Cipher
Cipher ByteString
k Word64
n' ByteString
ck
  where
    !n' :: Word64
n' = Word64
n Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
1

-- | Encrypt a message of at most 65535 bytes.
--
--   Returns the frame to send (the message length plus 34 bytes) and
--   the next t'Sender', which must be used for the following message.
--   Encrypting with the same t'Sender' twice reuses a nonce and breaks
--   confidentiality and authenticity.
--
--   Fails only with 'InvalidLength', for an oversized message. Nothing
--   is encrypted in that case, so the given t'Sender' remains the
--   current one and the connection can continue.
--
--   Continuing the module-level example:
--
--   >>> fmap (BS.length . fst) (encrypt i_snd "hello")
--   Right 39
--   >>> fmap fst (encrypt i_snd (BS.replicate 65536 0x00))
--   Left InvalidLength
encrypt
  :: Sender        -- ^ current state
  -> BS.ByteString -- ^ message
  -> Either Error (BS.ByteString, Sender)
encrypt :: Sender -> ByteString -> Either Error (ByteString, Sender)
encrypt (Sender Cipher
c0) ByteString
m = do
  let !len :: Int
len = ByteString -> Int
BS.length ByteString
m
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (Int
len Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
65535) Error
InvalidLength
  let !(ByteString
lc, Cipher
c1) = Cipher -> ByteString -> (ByteString, Cipher)
seal Cipher
c0 (Word16 -> ByteString
encode_be16 (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fi Int
len))
      !(ByteString
bc, Cipher
c2) = Cipher -> ByteString -> (ByteString, Cipher)
seal Cipher
c1 ByteString
m
  (ByteString, Sender) -> Either Error (ByteString, Sender)
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString
lc ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
bc, Cipher -> Sender
Sender Cipher
c2)

-- | Decrypt a buffer holding exactly one frame.
--
--   Returns the message and the next t'Receiver'. Fails with
--   'InvalidLength' if the buffer is not exactly one frame, and with
--   'InvalidMAC' if authentication fails. Any error means the
--   connection must be terminated.
--
--   Continuing the module-level example:
--
--   >>> fmap fst (decrypt (handshake_receiver r_res) ct)
--   Right "hello"
--   >>> fmap fst (decrypt (handshake_receiver r_res) (BS.take 38 ct))
--   Left InvalidLength
decrypt
  :: Receiver      -- ^ current state
  -> BS.ByteString -- ^ one frame
  -> Either Error (BS.ByteString, Receiver)
decrypt :: Receiver -> ByteString -> Either Error (ByteString, Receiver)
decrypt Receiver
r ByteString
frame = do
  let !(ByteString
lc, ByteString
c) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
18 ByteString
frame
  (_, p) <- Receiver -> ByteString -> Either Error (Int, Pending)
decrypt_header Receiver
r ByteString
lc
  decrypt_body p c

-- | Decrypt the 18-byte header (encrypted length and its MAC) at the
--   start of a frame.
--
--   Returns the number of bytes in the rest of the frame (the message
--   length plus a 16-byte MAC), which the caller should read exactly,
--   and the state for 'decrypt_body'. Fails with 'InvalidLength' if
--   the input is not 18 bytes, and with 'InvalidMAC' if
--   authentication fails. Any error means the connection must be
--   terminated.
--
--   Continuing the module-level example:
--
--   >>> fmap fst (decrypt_header (handshake_receiver r_res) (BS.take 18 ct))
--   Right 21
decrypt_header
  :: Receiver      -- ^ current state
  -> BS.ByteString -- ^ 18-byte header
  -> Either Error (Int, Pending)
decrypt_header :: Receiver -> ByteString -> Either Error (Int, Pending)
decrypt_header (Receiver Cipher
c0) ByteString
lc = do
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Int
BS.length ByteString
lc Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
18) Error
InvalidLength
  (l, c1) <- Error
-> Maybe (ByteString, Cipher) -> Either Error (ByteString, Cipher)
forall e a. e -> Maybe a -> Either e a
note Error
InvalidMAC (Cipher -> ByteString -> Maybe (ByteString, Cipher)
open Cipher
c0 ByteString
lc)
  len <- note InvalidLength (decode_be16 l)
  let !body = Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fi Word16
len Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
16
  pure (body, Pending body c1)

-- | Decrypt the rest of a frame, following 'decrypt_header'.
--
--   The input must be exactly as long as 'decrypt_header' reported.
--   Returns the message and the next t'Receiver'. Fails with
--   'InvalidLength' on a length mismatch, and with 'InvalidMAC' if
--   authentication fails. Any error means the connection must be
--   terminated.
--
--   Continuing the module-level example:
--
--   >>> let (hdr, rest) = BS.splitAt 18 ct
--   >>> let Right (n, p) = decrypt_header (handshake_receiver r_res) hdr
--   >>> fmap fst (decrypt_body p (BS.take n rest))
--   Right "hello"
decrypt_body
  :: Pending       -- ^ state from 'decrypt_header'
  -> BS.ByteString -- ^ the rest of the frame
  -> Either Error (BS.ByteString, Receiver)
decrypt_body :: Pending -> ByteString -> Either Error (ByteString, Receiver)
decrypt_body (Pending Int
body Cipher
c1) ByteString
c = do
  Bool -> Error -> Either Error ()
forall e. Bool -> e -> Either e ()
require (ByteString -> Int
BS.length ByteString
c Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
body) Error
InvalidLength
  (m, c2) <- Error
-> Maybe (ByteString, Cipher) -> Either Error (ByteString, Cipher)
forall e a. e -> Maybe a -> Either e a
note Error
InvalidMAC (Cipher -> ByteString -> Maybe (ByteString, Cipher)
open Cipher
c1 ByteString
c)
  pure (m, Receiver c2)

-- utilities ------------------------------------------------------------------

-- lowercase hex encoding
hex :: BS.ByteString -> String
hex :: ByteString -> String
hex = (Word8 -> ShowS) -> String -> ByteString -> String
forall a. (Word8 -> a -> a) -> a -> ByteString -> a
BS.foldr (\Word8
w String
acc -> Word8 -> Char
nibble (Word8 -> Int -> Word8
forall a. Bits a => a -> Int -> a
unsafeShiftR Word8
w Int
4) Char -> ShowS
forall a. a -> [a] -> [a]
: Word8 -> Char
nibble (Word8
w Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.&. Word8
15) Char -> ShowS
forall a. a -> [a] -> [a]
: String
acc)
  []
  where
    nibble :: Word8 -> Char
    nibble :: Word8 -> Char
nibble Word8
n
      | Word8
n Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
< Word8
10    = Int -> Char
forall a. Enum a => Int -> a
toEnum (Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fi Word8
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
0x30)
      | Bool
otherwise = Int -> Char
forall a. Enum a => Int -> a
toEnum (Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fi Word8
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
0x57)

note :: e -> Maybe a -> Either e a
note :: forall e a. e -> Maybe a -> Either e a
note e
e = Either e a -> (a -> Either e a) -> Maybe a -> Either e a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (e -> Either e a
forall a b. a -> Either a b
Left e
e) a -> Either e a
forall a b. b -> Either a b
Right
{-# INLINE note #-}

require :: Bool -> e -> Either e ()
require :: forall e. Bool -> e -> Either e ()
require Bool
cond e
e = Bool -> Either e () -> Either e ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
cond (e -> Either e ()
forall a b. a -> Either a b
Left e
e)
{-# INLINE require #-}

fi :: (Integral a, Num b) => a -> b
fi :: forall a b. (Integral a, Num b) => a -> b
fi = a -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral
{-# INLINE fi #-}