{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

-- |
-- Module: Lightning.Protocol.BOLT4.Prim
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Keys, secrets and the cryptographic primitives of BOLT #4.

module Lightning.Protocol.BOLT4.Prim (
  -- * Secret keys
    SecretKey
  , secret_key
  , public_key
  , sk_bytes
  , sk_pub

  -- * Shared secrets
  , SharedSecret
  , shared_secret
  , un_shared_secret
  , ecdh

  -- * Derived keys
  , DerivedKey
  , un_derived_key
  , derive_rho
  , derive_mu
  , derive_um
  , derive_ammag
  , derive_pad

  -- * Blinding
  , blinding_factor
  , blinded_node_tweak
  , blind_pub
  , blind_scalar

  -- * Points
  , to_point
  , from_point

  -- * Streams and MACs
  , keystream
  , hmac
  , ct_eq
  , xor_bytes
  ) where

import Control.DeepSeq (NFData(..))
import qualified Crypto.Cipher.ChaCha20 as ChaCha
import qualified Crypto.Curve.Secp256k1 as Secp256k1
import qualified Crypto.Hash.SHA256 as SHA256
import Data.Bits (xor)
import qualified Data.ByteString as BS
import qualified Lightning.Protocol.BOLT1 as BOLT1
import qualified Numeric.Montgomery.Secp256k1.Scalar as S

-- secret keys ----------------------------------------------------------------

-- | A secp256k1 secret key: a session key, a node's private key, or the
--   seed of a blinded path.
--
--   This is secret material: its 'Show' instance is redacted and it
--   has no 'Eq' instance.
data SecretKey = SecretKey
  !BS.ByteString         -- the key
  !Secp256k1.Projective  -- its public key
  !BOLT1.Point           -- its serialized public key

instance Show SecretKey where
  showsPrec :: Int -> SecretKey -> ShowS
showsPrec Int
d SecretKey
_ = 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
"SecretKey <redacted>"

instance NFData SecretKey where
  rnf :: SecretKey -> ()
rnf (SecretKey ByteString
k Projective
p Point
q) = ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
k () -> () -> ()
forall a b. a -> b -> b
`seq` Projective
p Projective -> () -> ()
forall a b. a -> b -> b
`seq` Point -> ()
forall a. NFData a => a -> ()
rnf Point
q

-- | Construct a t'SecretKey' from exactly 32 big-endian bytes encoding an
--   integer in [1, n - 1], where n is the secp256k1 group order.
--
--   >>> secret_key (BS.replicate 32 0x41)
--   Just (SecretKey <redacted>)
--   >>> secret_key (BS.replicate 32 0x00)
--   Nothing
--   >>> secret_key (BS.replicate 31 0x41)
--   Nothing
secret_key :: BS.ByteString -> Maybe SecretKey
secret_key :: ByteString -> Maybe SecretKey
secret_key ByteString
bs
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 = Maybe SecretKey
forall a. Maybe a
Nothing
  | Bool
otherwise = do
      pub <- Wider -> Maybe Projective
Secp256k1.derive_pub (ByteString -> Wider
Secp256k1.unsafe_roll32 ByteString
bs)
      pt <- to_point pub
      pure $! SecretKey bs pub pt

-- | The public key of a t'SecretKey'.
--
--   >>> let Just sk = secret_key (BS.replicate 32 0x41)
--   >>> BS.length (BOLT1.un_point (public_key sk))
--   33
public_key :: SecretKey -> BOLT1.Point
public_key :: SecretKey -> Point
public_key (SecretKey ByteString
_ Projective
_ Point
p) = Point
p
{-# INLINE public_key #-}

sk_bytes :: SecretKey -> BS.ByteString
sk_bytes :: SecretKey -> ByteString
sk_bytes (SecretKey ByteString
k Projective
_ Point
_) = ByteString
k
{-# INLINE sk_bytes #-}

sk_pub :: SecretKey -> Secp256k1.Projective
sk_pub :: SecretKey -> Projective
sk_pub (SecretKey ByteString
_ Projective
p Point
_) = Projective
p
{-# INLINE sk_pub #-}

-- shared secrets -------------------------------------------------------------

-- | A 32-byte shared secret, established between the origin of an onion
--   and one of its hops.
--
--   This is secret material: its 'Show' instance is redacted and its
--   'Eq' instance runs in constant time.
newtype SharedSecret = SharedSecret BS.ByteString

instance Eq SharedSecret where
  SharedSecret ByteString
a == :: SharedSecret -> SharedSecret -> Bool
== SharedSecret ByteString
b = ByteString -> ByteString -> Bool
ct_eq ByteString
a ByteString
b

instance Show SharedSecret where
  showsPrec :: Int -> SharedSecret -> ShowS
showsPrec Int
d SharedSecret
_ = 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
"SharedSecret <redacted>"

instance NFData SharedSecret where
  rnf :: SharedSecret -> ()
rnf (SharedSecret ByteString
bs) = ByteString -> ()
forall a. NFData a => a -> ()
rnf ByteString
bs

-- | Construct a t'SharedSecret' from exactly 32 bytes (e.g. to restore one
--   that was stored with 'un_shared_secret').
--
--   >>> let Just ss = shared_secret (BS.replicate 32 0x01)
--   >>> BS.length (un_shared_secret ss)
--   32
--   >>> shared_secret "too short"
--   Nothing
shared_secret :: BS.ByteString -> Maybe SharedSecret
shared_secret :: ByteString -> Maybe SharedSecret
shared_secret ByteString
bs
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
32 = SharedSecret -> Maybe SharedSecret
forall a. a -> Maybe a
Just (ByteString -> SharedSecret
SharedSecret ByteString
bs)
  | Bool
otherwise          = Maybe SharedSecret
forall a. Maybe a
Nothing
{-# INLINE shared_secret #-}

-- | The bytes of a t'SharedSecret'.
un_shared_secret :: SharedSecret -> BS.ByteString
un_shared_secret :: SharedSecret -> ByteString
un_shared_secret (SharedSecret ByteString
bs) = ByteString
bs
{-# INLINE un_shared_secret #-}

-- | ECDH per BOLT #4: SHA256 of the compressed product of a point and a
--   32-byte scalar. Fails if the scalar is not in [1, n - 1].
ecdh :: BS.ByteString -> Secp256k1.Projective -> Maybe SharedSecret
ecdh :: ByteString -> Projective -> Maybe SharedSecret
ecdh ByteString
k Projective
pub = do
  pt <- Projective -> Wider -> Maybe Projective
Secp256k1.mul Projective
pub (ByteString -> Wider
Secp256k1.unsafe_roll32 ByteString
k)
  pure $! SharedSecret (SHA256.hash (Secp256k1.serialize_point pt))

-- derived keys ---------------------------------------------------------------

-- A 32-byte key derived from a shared secret.
newtype DerivedKey = DerivedKey BS.ByteString

un_derived_key :: DerivedKey -> BS.ByteString
un_derived_key :: DerivedKey -> ByteString
un_derived_key (DerivedKey ByteString
k) = ByteString
k
{-# INLINE un_derived_key #-}

derive :: BS.ByteString -> BS.ByteString -> DerivedKey
derive :: ByteString -> ByteString -> DerivedKey
derive ByteString
label ByteString
ss =
  let SHA256.MAC ByteString
k = ByteString -> ByteString -> MAC
SHA256.hmac ByteString
label ByteString
ss
  in  ByteString -> DerivedKey
DerivedKey ByteString
k
{-# INLINE derive #-}

derive_rho :: SharedSecret -> DerivedKey
derive_rho :: SharedSecret -> DerivedKey
derive_rho (SharedSecret ByteString
ss) = ByteString -> ByteString -> DerivedKey
derive ByteString
"rho" ByteString
ss

derive_mu :: SharedSecret -> DerivedKey
derive_mu :: SharedSecret -> DerivedKey
derive_mu (SharedSecret ByteString
ss) = ByteString -> ByteString -> DerivedKey
derive ByteString
"mu" ByteString
ss

derive_um :: SharedSecret -> DerivedKey
derive_um :: SharedSecret -> DerivedKey
derive_um (SharedSecret ByteString
ss) = ByteString -> ByteString -> DerivedKey
derive ByteString
"um" ByteString
ss

derive_ammag :: SharedSecret -> DerivedKey
derive_ammag :: SharedSecret -> DerivedKey
derive_ammag (SharedSecret ByteString
ss) = ByteString -> ByteString -> DerivedKey
derive ByteString
"ammag" ByteString
ss

-- The pad key is derived from the session key itself.
derive_pad :: SecretKey -> DerivedKey
derive_pad :: SecretKey -> DerivedKey
derive_pad (SecretKey ByteString
k Projective
_ Point
_) = ByteString -> ByteString -> DerivedKey
derive ByteString
"pad" ByteString
k

-- blinding -------------------------------------------------------------------

-- SHA256(E || ss), the factor by which ephemeral keys are blinded.
blinding_factor :: Secp256k1.Projective -> SharedSecret -> BS.ByteString
blinding_factor :: Projective -> SharedSecret -> ByteString
blinding_factor Projective
e (SharedSecret ByteString
ss) =
  ByteString -> ByteString
SHA256.hash (Projective -> ByteString
Secp256k1.serialize_point Projective
e ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ss)

-- HMAC256("blinded_node_id", ss), the factor by which node ids are
-- blinded in a blinded route.
blinded_node_tweak :: SharedSecret -> BS.ByteString
blinded_node_tweak :: SharedSecret -> ByteString
blinded_node_tweak (SharedSecret ByteString
ss) =
  let SHA256.MAC ByteString
t = ByteString -> ByteString -> MAC
SHA256.hmac ByteString
"blinded_node_id" ByteString
ss
  in  ByteString
t

-- Multiply a point by a 32-byte factor.
blind_pub
  :: Secp256k1.Projective -> BS.ByteString -> Maybe Secp256k1.Projective
blind_pub :: Projective -> ByteString -> Maybe Projective
blind_pub Projective
p ByteString
t = Projective -> Wider -> Maybe Projective
Secp256k1.mul Projective
p (ByteString -> Wider
Secp256k1.unsafe_roll32 ByteString
t)

-- Multiply a 32-byte scalar by a 32-byte factor, mod n. Fails if the
-- product is zero.
blind_scalar :: BS.ByteString -> BS.ByteString -> Maybe BS.ByteString
blind_scalar :: ByteString -> ByteString -> Maybe ByteString
blind_scalar ByteString
k ByteString
t =
  let !r :: Wider
r = Montgomery -> Wider
S.retr (Montgomery -> Montgomery -> Montgomery
S.mul (Wider -> Montgomery
S.to (ByteString -> Wider
Secp256k1.unsafe_roll32 ByteString
k))
                         (Wider -> Montgomery
S.to (ByteString -> Wider
Secp256k1.unsafe_roll32 ByteString
t)))
  in  if   Wider -> Bool
Secp256k1.ge Wider
r
      then ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (ByteString -> Maybe ByteString) -> ByteString -> Maybe ByteString
forall a b. (a -> b) -> a -> b
$! Wider -> ByteString
Secp256k1.unroll32 Wider
r
      else Maybe ByteString
forall a. Maybe a
Nothing

-- points ---------------------------------------------------------------------

to_point :: Secp256k1.Projective -> Maybe BOLT1.Point
to_point :: Projective -> Maybe Point
to_point = ByteString -> Maybe Point
BOLT1.point (ByteString -> Maybe Point)
-> (Projective -> ByteString) -> Projective -> Maybe Point
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Projective -> ByteString
Secp256k1.serialize_point
{-# INLINE to_point #-}

from_point :: BOLT1.Point -> Maybe Secp256k1.Projective
from_point :: Point -> Maybe Projective
from_point = ByteString -> Maybe Projective
Secp256k1.parse_point (ByteString -> Maybe Projective)
-> (Point -> ByteString) -> Point -> Maybe Projective
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Point -> ByteString
BOLT1.un_point
{-# INLINE from_point #-}

-- streams and MACs -----------------------------------------------------------

-- The ChaCha20 keystream of the given length under a derived key, with
-- an all-zero nonce. The cipher fails only for a key or nonce of the
-- wrong length, or past 256 GiB of output, none of which can occur
-- here; the empty result in that case truncates any output XORed with
-- it, rather than leaving it unencrypted.
keystream :: DerivedKey -> Int -> BS.ByteString
keystream :: DerivedKey -> Int -> ByteString
keystream (DerivedKey ByteString
k) Int
n =
  case ByteString
-> Word32 -> ByteString -> ByteString -> Either Error ByteString
ChaCha.cipher ByteString
k Word32
0 (Int -> Word8 -> ByteString
BS.replicate Int
12 Word8
0) (Int -> Word8 -> ByteString
BS.replicate Int
n Word8
0) of
    Right ByteString
s -> ByteString
s
    Left Error
_  -> ByteString
BS.empty

-- HMAC-SHA256 under a derived key.
hmac :: DerivedKey -> BS.ByteString -> BS.ByteString
hmac :: DerivedKey -> ByteString -> ByteString
hmac (DerivedKey ByteString
k) ByteString
m =
  let SHA256.MAC ByteString
h = ByteString -> ByteString -> MAC
SHA256.hmac ByteString
k ByteString
m
  in  ByteString
h
{-# INLINE hmac #-}

-- Constant-time equality (variable-time only in the lengths).
ct_eq :: BS.ByteString -> BS.ByteString -> Bool
ct_eq :: ByteString -> ByteString -> Bool
ct_eq ByteString
a ByteString
b = ByteString -> MAC
SHA256.MAC ByteString
a MAC -> MAC -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString -> MAC
SHA256.MAC ByteString
b
{-# INLINE ct_eq #-}

-- XOR, truncated to the shorter input.
xor_bytes :: BS.ByteString -> BS.ByteString -> BS.ByteString
xor_bytes :: ByteString -> ByteString -> ByteString
xor_bytes = (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
BS.packZipWith Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
xor
{-# INLINE xor_bytes #-}