{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE DeriveGeneric #-}

-- |
-- Module: Lightning.Protocol.BOLT4.Process
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Onion packet processing.

module Lightning.Protocol.BOLT4.Process (
    ProcessResult(..)
  , ForwardInfo(..)
  , ReceiveInfo(..)
  , process
  ) where

import Control.DeepSeq (NFData)
import qualified Crypto.Curve.Secp256k1 as Secp256k1
import qualified Data.ByteString as BS
import GHC.Generics (Generic)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT4.Blinding (unblind)
import Lightning.Protocol.BOLT4.Codec (decode_hop_payload)
import Lightning.Protocol.BOLT4.Prim
import Lightning.Protocol.BOLT4.Types

-- | The result of processing an onion packet.
data ProcessResult
  = Forward !ForwardInfo
    -- ^ forward the onion to the next hop
  | Receive !ReceiveInfo
    -- ^ this node is the onion's final hop
  deriving (ProcessResult -> ProcessResult -> Bool
(ProcessResult -> ProcessResult -> Bool)
-> (ProcessResult -> ProcessResult -> Bool) -> Eq ProcessResult
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ProcessResult -> ProcessResult -> Bool
== :: ProcessResult -> ProcessResult -> Bool
$c/= :: ProcessResult -> ProcessResult -> Bool
/= :: ProcessResult -> ProcessResult -> Bool
Eq, Int -> ProcessResult -> ShowS
[ProcessResult] -> ShowS
ProcessResult -> String
(Int -> ProcessResult -> ShowS)
-> (ProcessResult -> String)
-> ([ProcessResult] -> ShowS)
-> Show ProcessResult
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProcessResult -> ShowS
showsPrec :: Int -> ProcessResult -> ShowS
$cshow :: ProcessResult -> String
show :: ProcessResult -> String
$cshowList :: [ProcessResult] -> ShowS
showList :: [ProcessResult] -> ShowS
Show, (forall x. ProcessResult -> Rep ProcessResult x)
-> (forall x. Rep ProcessResult x -> ProcessResult)
-> Generic ProcessResult
forall x. Rep ProcessResult x -> ProcessResult
forall x. ProcessResult -> Rep ProcessResult x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ProcessResult -> Rep ProcessResult x
from :: forall x. ProcessResult -> Rep ProcessResult x
$cto :: forall x. Rep ProcessResult x -> ProcessResult
to :: forall x. Rep ProcessResult x -> ProcessResult
Generic)

instance NFData ProcessResult

-- | What a forwarding node learns from an onion.
data ForwardInfo = ForwardInfo
  { ForwardInfo -> HopPayload
fwd_payload       :: !HopPayload
    -- ^ this node's payload
  , ForwardInfo -> Maybe BlindedInfo
fwd_blinded       :: !(Maybe BlindedInfo)
    -- ^ the decrypted @encrypted_recipient_data@ and next path key, in
    --   a blinded route
  , ForwardInfo -> OnionPacket
fwd_next_packet   :: !OnionPacket
    -- ^ the onion for the next hop
  , ForwardInfo -> SharedSecret
fwd_shared_secret :: !SharedSecret
    -- ^ the shared secret, to wrap returned errors with
  } deriving (ForwardInfo -> ForwardInfo -> Bool
(ForwardInfo -> ForwardInfo -> Bool)
-> (ForwardInfo -> ForwardInfo -> Bool) -> Eq ForwardInfo
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ForwardInfo -> ForwardInfo -> Bool
== :: ForwardInfo -> ForwardInfo -> Bool
$c/= :: ForwardInfo -> ForwardInfo -> Bool
/= :: ForwardInfo -> ForwardInfo -> Bool
Eq, Int -> ForwardInfo -> ShowS
[ForwardInfo] -> ShowS
ForwardInfo -> String
(Int -> ForwardInfo -> ShowS)
-> (ForwardInfo -> String)
-> ([ForwardInfo] -> ShowS)
-> Show ForwardInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ForwardInfo -> ShowS
showsPrec :: Int -> ForwardInfo -> ShowS
$cshow :: ForwardInfo -> String
show :: ForwardInfo -> String
$cshowList :: [ForwardInfo] -> ShowS
showList :: [ForwardInfo] -> ShowS
Show, (forall x. ForwardInfo -> Rep ForwardInfo x)
-> (forall x. Rep ForwardInfo x -> ForwardInfo)
-> Generic ForwardInfo
forall x. Rep ForwardInfo x -> ForwardInfo
forall x. ForwardInfo -> Rep ForwardInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ForwardInfo -> Rep ForwardInfo x
from :: forall x. ForwardInfo -> Rep ForwardInfo x
$cto :: forall x. Rep ForwardInfo x -> ForwardInfo
to :: forall x. Rep ForwardInfo x -> ForwardInfo
Generic)

instance NFData ForwardInfo

-- | What the final node learns from an onion.
data ReceiveInfo = ReceiveInfo
  { ReceiveInfo -> HopPayload
rcv_payload       :: !HopPayload
    -- ^ this node's payload
  , ReceiveInfo -> Maybe BlindedInfo
rcv_blinded       :: !(Maybe BlindedInfo)
    -- ^ the decrypted @encrypted_recipient_data@, in a blinded route
  , ReceiveInfo -> SharedSecret
rcv_shared_secret :: !SharedSecret
    -- ^ the shared secret, to construct errors with
  } deriving (ReceiveInfo -> ReceiveInfo -> Bool
(ReceiveInfo -> ReceiveInfo -> Bool)
-> (ReceiveInfo -> ReceiveInfo -> Bool) -> Eq ReceiveInfo
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ReceiveInfo -> ReceiveInfo -> Bool
== :: ReceiveInfo -> ReceiveInfo -> Bool
$c/= :: ReceiveInfo -> ReceiveInfo -> Bool
/= :: ReceiveInfo -> ReceiveInfo -> Bool
Eq, Int -> ReceiveInfo -> ShowS
[ReceiveInfo] -> ShowS
ReceiveInfo -> String
(Int -> ReceiveInfo -> ShowS)
-> (ReceiveInfo -> String)
-> ([ReceiveInfo] -> ShowS)
-> Show ReceiveInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ReceiveInfo -> ShowS
showsPrec :: Int -> ReceiveInfo -> ShowS
$cshow :: ReceiveInfo -> String
show :: ReceiveInfo -> String
$cshowList :: [ReceiveInfo] -> ShowS
showList :: [ReceiveInfo] -> ShowS
Show, (forall x. ReceiveInfo -> Rep ReceiveInfo x)
-> (forall x. Rep ReceiveInfo x -> ReceiveInfo)
-> Generic ReceiveInfo
forall x. Rep ReceiveInfo x -> ReceiveInfo
forall x. ReceiveInfo -> Rep ReceiveInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ReceiveInfo -> Rep ReceiveInfo x
from :: forall x. ReceiveInfo -> Rep ReceiveInfo x
$cto :: forall x. Rep ReceiveInfo x -> ReceiveInfo
to :: forall x. Rep ReceiveInfo x -> ReceiveInfo
Generic)

instance NFData ReceiveInfo

-- | Process an onion packet, given this node's private key, the packet,
--   its associated data (the payment hash, for a payment), and the
--   @path_key@ received with it (in @update_add_htlc@), if any.
--
--   In a blinded route, the onion is encrypted to this node's blinded
--   node id: given a @path_key@, the matching private key is derived
--   from it. The @encrypted_recipient_data@ in the payload is decrypted
--   with the @path_key@, or, at the introduction node, with the
--   payload's @current_path_key@; a path key without
--   @encrypted_recipient_data@, or both kinds of path key, are
--   rejected.
--
--   The payload is otherwise returned as is. The caller must apply the
--   remaining reader requirements of BOLT #4: the presence of the
--   fields required for forwarding or receiving, the HTLC amount and
--   expiry checks (in a blinded route, against @payment_relay@ and
--   @payment_constraints@), @allowed_features@, the rule that
--   @encrypted_recipient_data@ hold only one of @short_channel_id@ and
--   @next_node_id@, and the rejection of replayed HMACs.
--
--   >>> let Just session = secret_key (BS.replicate 32 0x41)
--   >>> let Just node = secret_key (BS.replicate 32 0x42)
--   >>> let pl = empty_hop_payload { hp_outgoing_cltv_value = Just 144 }
--   >>> let ad = BS.replicate 32 0
--   >>> let Right (pkt, _) = construct session [Hop (public_key node) pl] ad
--   >>> let Right (Receive info) = process node pkt ad Nothing
--   >>> hp_outgoing_cltv_value (rcv_payload info)
--   Just 144
process
  :: SecretKey
  -> OnionPacket
  -> BS.ByteString
  -> Maybe BOLT1.Point
  -> Either ProcessError ProcessResult
process :: SecretKey
-> OnionPacket
-> ByteString
-> Maybe Point
-> Either ProcessError ProcessResult
process SecretKey
sk OnionPacket
pkt ByteString
ad Maybe Point
mpk = do
  let ver :: Word8
ver = OnionPacket -> Word8
onion_version OnionPacket
pkt
  if Word8
ver Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
0 then ProcessError -> Either ProcessError ()
forall a b. a -> Either a b
Left (Word8 -> ProcessError
InvalidVersion Word8
ver) else () -> Either ProcessError ()
forall a b. b -> Either a b
Right ()
  eph <- ProcessError -> Maybe Projective -> Either ProcessError Projective
forall a. ProcessError -> Maybe a -> Either ProcessError a
note ProcessError
InvalidPublicKey (Point -> Maybe Projective
from_point (OnionPacket -> Point
onion_public_key OnionPacket
pkt))
  -- with a path_key, the onion is encrypted to the blinded node id
  blinding <- traverse path_secret mpk
  key <- case blinding of
    Maybe (Projective, SharedSecret)
Nothing -> ByteString -> Either ProcessError ByteString
forall a b. b -> Either a b
Right (SecretKey -> ByteString
sk_bytes SecretKey
sk)
    Just (Projective
_, SharedSecret
bss) ->
      ProcessError -> Maybe ByteString -> Either ProcessError ByteString
forall a. ProcessError -> Maybe a -> Either ProcessError a
note ProcessError
InvalidPathKey (ByteString -> ByteString -> Maybe ByteString
blind_scalar (SecretKey -> ByteString
sk_bytes SecretKey
sk) (SharedSecret -> ByteString
blinded_node_tweak SharedSecret
bss))
  ss <- note InvalidPublicKey (ecdh key eph)
  let payloads = HopPayloads -> ByteString
un_hop_payloads (OnionPacket -> HopPayloads
onion_hop_payloads OnionPacket
pkt)
      mac = DerivedKey -> ByteString -> ByteString
hmac (SharedSecret -> DerivedKey
derive_mu SharedSecret
ss) (ByteString
payloads ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
ad)
  if   ct_eq mac (un_hmac32 (onion_hmac pkt))
  then Right ()
  else Left HmacMismatch
  let plain = ByteString -> ByteString -> ByteString
xor_bytes (ByteString
payloads ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Int -> Word8 -> ByteString
BS.replicate Int
1300 Word8
0)
                        (DerivedKey -> Int -> ByteString
keystream (SharedSecret -> DerivedKey
derive_rho SharedSecret
ss) Int
2600)
  (pl, next_mac, rest) <- split_payload plain
  hp <- either (Left . InvalidPayload) Right (decode_hop_payload pl)
  binfo <- case (hp_encrypted_data hp, blinding, hp_current_path_key hp) of
    (Maybe ByteString
Nothing, Maybe (Projective, SharedSecret)
Nothing, Maybe Point
Nothing) -> Maybe BlindedInfo -> Either ProcessError (Maybe BlindedInfo)
forall a b. b -> Either a b
Right Maybe BlindedInfo
forall a. Maybe a
Nothing
    (Maybe ByteString
Nothing, Maybe (Projective, SharedSecret)
_, Maybe Point
_)             -> ProcessError -> Either ProcessError (Maybe BlindedInfo)
forall a b. a -> Either a b
Left ProcessError
UnexpectedPathKey
    (Just ByteString
_, Just (Projective, SharedSecret)
_, Just Point
_)    -> ProcessError -> Either ProcessError (Maybe BlindedInfo)
forall a b. a -> Either a b
Left ProcessError
UnexpectedPathKey
    (Just ByteString
_, Maybe (Projective, SharedSecret)
Nothing, Maybe Point
Nothing)  -> ProcessError -> Either ProcessError (Maybe BlindedInfo)
forall a b. a -> Either a b
Left ProcessError
MissingPathKey
    (Just ByteString
enc, Just (Projective
e, SharedSecret
bss), Maybe Point
Nothing) -> BlindedInfo -> Maybe BlindedInfo
forall a. a -> Maybe a
Just (BlindedInfo -> Maybe BlindedInfo)
-> Either ProcessError BlindedInfo
-> Either ProcessError (Maybe BlindedInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SharedSecret
-> Projective -> ByteString -> Either ProcessError BlindedInfo
unblind SharedSecret
bss Projective
e ByteString
enc
    (Just ByteString
enc, Maybe (Projective, SharedSecret)
Nothing, Just Point
cpk) -> do
      (e, bss) <- Point -> Either ProcessError (Projective, SharedSecret)
path_secret Point
cpk
      Just <$> unblind bss e enc
  if BS.all (== 0) next_mac
    then Right (Receive (ReceiveInfo hp binfo ss))
    else do
      eph' <- note InvalidPublicKey
                (blind_pub eph (blinding_factor eph ss) >>= to_point)
      let next = Word8 -> Point -> HopPayloads -> Hmac32 -> OnionPacket
OnionPacket Word8
0 Point
eph' (ByteString -> HopPayloads
HopPayloads ByteString
rest) (ByteString -> Hmac32
Hmac32 ByteString
next_mac)
      Right (Forward (ForwardInfo hp binfo next ss))
  where
    note :: ProcessError -> Maybe a -> Either ProcessError a
    note :: forall a. ProcessError -> Maybe a -> Either ProcessError a
note ProcessError
e = Either ProcessError a
-> (a -> Either ProcessError a) -> Maybe a -> Either ProcessError a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProcessError -> Either ProcessError a
forall a b. a -> Either a b
Left ProcessError
e) a -> Either ProcessError a
forall a b. b -> Either a b
Right

    -- a path key, and its shared secret with this node
    path_secret
      :: BOLT1.Point
      -> Either ProcessError (Secp256k1.Projective, SharedSecret)
    path_secret :: Point -> Either ProcessError (Projective, SharedSecret)
path_secret Point
pk = do
      e <- ProcessError -> Maybe Projective -> Either ProcessError Projective
forall a. ProcessError -> Maybe a -> Either ProcessError a
note ProcessError
InvalidPathKey (Point -> Maybe Projective
from_point Point
pk)
      bss <- note InvalidPathKey (ecdh (sk_bytes sk) e)
      Right (e, bss)

-- Split the decrypted 2600-byte buffer into the payload, the next HMAC
-- and the next hop_payloads. The length prefix, payload and HMAC must
-- fit in the 1300-byte hop_payloads.
split_payload
  :: BS.ByteString
  -> Either ProcessError (BS.ByteString, BS.ByteString, BS.ByteString)
split_payload :: ByteString
-> Either ProcessError (ByteString, ByteString, ByteString)
split_payload ByteString
plain = case ByteString -> Maybe (Word64, ByteString)
BOLT1.decode_bigsize ByteString
plain of
  Maybe (Word64, ByteString)
Nothing -> ProcessError
-> Either ProcessError (ByteString, ByteString, ByteString)
forall a b. a -> Either a b
Left ProcessError
InvalidPayloadLength
  Just (Word64
len, ByteString
r0)
    | Word64
len Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
2   -> ProcessError
-> Either ProcessError (ByteString, ByteString, ByteString)
forall a b. a -> Either a b
Left ProcessError
InvalidPayloadLength
    | Word64
len Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int
1300 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
prefix Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
32) -> ProcessError
-> Either ProcessError (ByteString, ByteString, ByteString)
forall a b. a -> Either a b
Left ProcessError
InvalidPayloadLength
    | Bool
otherwise ->
        let (ByteString
pl, ByteString
r1)  = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
len) ByteString
r0
            (ByteString
mac, ByteString
r2) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
32 ByteString
r1
        in  (ByteString, ByteString, ByteString)
-> Either ProcessError (ByteString, ByteString, ByteString)
forall a b. b -> Either a b
Right (ByteString
pl, ByteString
mac, Int -> ByteString -> ByteString
BS.take Int
1300 ByteString
r2)
    where
      prefix :: Int
prefix = ByteString -> Int
BS.length ByteString
plain Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
r0