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

-- |
-- Module: Lightning.Protocol.BOLT4.Error
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Returning errors: construction, wrapping and attribution of return
-- packets.

module Lightning.Protocol.BOLT4.Error (
    ErrorPacket(..)
  , Attribution(..)
  , construct_error
  , wrap_error
  , unwrap_error
  ) where

import Control.DeepSeq (NFData)
import qualified Data.ByteString as BS
import GHC.Generics (Generic)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT4.Codec
import Lightning.Protocol.BOLT4.Prim
import Lightning.Protocol.BOLT4.Types

-- | An obfuscated return packet (the @reason@ of @update_fail_htlc@).
newtype ErrorPacket = ErrorPacket BS.ByteString
  deriving (ErrorPacket -> ErrorPacket -> Bool
(ErrorPacket -> ErrorPacket -> Bool)
-> (ErrorPacket -> ErrorPacket -> Bool) -> Eq ErrorPacket
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ErrorPacket -> ErrorPacket -> Bool
== :: ErrorPacket -> ErrorPacket -> Bool
$c/= :: ErrorPacket -> ErrorPacket -> Bool
/= :: ErrorPacket -> ErrorPacket -> Bool
Eq, Int -> ErrorPacket -> ShowS
[ErrorPacket] -> ShowS
ErrorPacket -> String
(Int -> ErrorPacket -> ShowS)
-> (ErrorPacket -> String)
-> ([ErrorPacket] -> ShowS)
-> Show ErrorPacket
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ErrorPacket -> ShowS
showsPrec :: Int -> ErrorPacket -> ShowS
$cshow :: ErrorPacket -> String
show :: ErrorPacket -> String
$cshowList :: [ErrorPacket] -> ShowS
showList :: [ErrorPacket] -> ShowS
Show, (forall x. ErrorPacket -> Rep ErrorPacket x)
-> (forall x. Rep ErrorPacket x -> ErrorPacket)
-> Generic ErrorPacket
forall x. Rep ErrorPacket x -> ErrorPacket
forall x. ErrorPacket -> Rep ErrorPacket x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ErrorPacket -> Rep ErrorPacket x
from :: forall x. ErrorPacket -> Rep ErrorPacket x
$cto :: forall x. Rep ErrorPacket x -> ErrorPacket
to :: forall x. Rep ErrorPacket x -> ErrorPacket
Generic)

instance NFData ErrorPacket

-- | The origin of a return packet, as found by 'unwrap_error'.
data Attribution
  = Attributed {-# UNPACK #-} !Int !FailureMessage
    -- ^ the hop with this index (from 0, in route order) returned the
    --   failure
  | MalformedFailure {-# UNPACK #-} !Int
    -- ^ the hop with this index returned the packet, but its failure
    --   message can't be decoded
  | UnknownOrigin
    -- ^ no hop's HMAC matches
  deriving (Attribution -> Attribution -> Bool
(Attribution -> Attribution -> Bool)
-> (Attribution -> Attribution -> Bool) -> Eq Attribution
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Attribution -> Attribution -> Bool
== :: Attribution -> Attribution -> Bool
$c/= :: Attribution -> Attribution -> Bool
/= :: Attribution -> Attribution -> Bool
Eq, Int -> Attribution -> ShowS
[Attribution] -> ShowS
Attribution -> String
(Int -> Attribution -> ShowS)
-> (Attribution -> String)
-> ([Attribution] -> ShowS)
-> Show Attribution
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Attribution -> ShowS
showsPrec :: Int -> Attribution -> ShowS
$cshow :: Attribution -> String
show :: Attribution -> String
$cshowList :: [Attribution] -> ShowS
showList :: [Attribution] -> ShowS
Show, (forall x. Attribution -> Rep Attribution x)
-> (forall x. Rep Attribution x -> Attribution)
-> Generic Attribution
forall x. Rep Attribution x -> Attribution
forall x. Attribution -> Rep Attribution x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Attribution -> Rep Attribution x
from :: forall x. Attribution -> Rep Attribution x
$cto :: forall x. Rep Attribution x -> Attribution
to :: forall x. Rep Attribution x -> Attribution
Generic)

instance NFData Attribution

-- | Construct a return packet at the failing node, given the shared
--   secret from processing the onion and the failure.
--
--   The failure message is padded so that its length plus that of the
--   padding is at least 256 bytes. Fails if the failure message can't
--   be encoded, or exceeds 65535 bytes.
--
--   >>> let Just ss = shared_secret (BS.replicate 32 0x01)
--   >>> let fm = FailureMessage TemporaryNodeFailure BOLT1.empty_tlv_stream
--   >>> let Right (ErrorPacket pkt) = construct_error ss fm
--   >>> BS.length pkt
--   292
construct_error
  :: SharedSecret
  -> FailureMessage
  -> Either EncodeError ErrorPacket
construct_error :: SharedSecret -> FailureMessage -> Either EncodeError ErrorPacket
construct_error SharedSecret
ss FailureMessage
fm = do
  msg <- FailureMessage -> Either EncodeError ByteString
encode_failure_message FailureMessage
fm
  let len = ByteString -> Int
BS.length ByteString
msg
  if len > 65535
    then Left FieldTooLong
    else do
      let pad  = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
256 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
len)
          body = [ByteString] -> ByteString
BS.concat
            [ Word16 -> ByteString
BOLT1.encode_u16 (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
len), ByteString
msg
            , Word16 -> ByteString
BOLT1.encode_u16 (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
pad), Int -> Word8 -> ByteString
BS.replicate Int
pad Word8
0 ]
          mac  = DerivedKey -> ByteString -> ByteString
hmac (SharedSecret -> DerivedKey
derive_um SharedSecret
ss) ByteString
body
      pure (wrap_error ss (ErrorPacket (mac <> body)))

-- | Wrap a return packet from downstream at an intermediate node, given
--   the shared secret from processing the onion.
--
--   >>> let Just ss = shared_secret (BS.replicate 32 0x01)
--   >>> wrap_error ss (wrap_error ss (ErrorPacket "packet"))
--   ErrorPacket "packet"
wrap_error :: SharedSecret -> ErrorPacket -> ErrorPacket
wrap_error :: SharedSecret -> ErrorPacket -> ErrorPacket
wrap_error SharedSecret
ss (ErrorPacket ByteString
p) =
  ByteString -> ErrorPacket
ErrorPacket (ByteString -> ByteString -> ByteString
xor_bytes ByteString
p (DerivedKey -> Int -> ByteString
keystream (SharedSecret -> DerivedKey
derive_ammag SharedSecret
ss) (ByteString -> Int
BS.length ByteString
p)))

-- | Find the origin of a return packet at the origin node, given the
--   shared secrets from 'Lightning.Protocol.BOLT4.construct', in route
--   order.
--
--   >>> let Just ss0 = shared_secret (BS.replicate 32 0x01)
--   >>> let Just ss1 = shared_secret (BS.replicate 32 0x02)
--   >>> let fm = FailureMessage TemporaryNodeFailure BOLT1.empty_tlv_stream
--   >>> let Right pkt = construct_error ss1 fm
--   >>> unwrap_error [ss0, ss1] (wrap_error ss0 pkt) == Attributed 1 fm
--   True
--   >>> unwrap_error [ss0] (wrap_error ss0 pkt)
--   UnknownOrigin
unwrap_error :: [SharedSecret] -> ErrorPacket -> Attribution
unwrap_error :: [SharedSecret] -> ErrorPacket -> Attribution
unwrap_error = Int -> [SharedSecret] -> ErrorPacket -> Attribution
go Int
0
  where
    go :: Int -> [SharedSecret] -> ErrorPacket -> Attribution
go Int
_ [] ErrorPacket
_ = Attribution
UnknownOrigin
    go Int
i (SharedSecret
ss : [SharedSecret]
rest) ErrorPacket
p =
      let ErrorPacket ByteString
q = SharedSecret -> ErrorPacket -> ErrorPacket
wrap_error SharedSecret
ss ErrorPacket
p
          (ByteString
mac, ByteString
body) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
32 ByteString
q
      in  if   ByteString -> ByteString -> Bool
ct_eq ByteString
mac (DerivedKey -> ByteString -> ByteString
hmac (SharedSecret -> DerivedKey
derive_um SharedSecret
ss) ByteString
body)
          then (DecodeError -> Attribution)
-> (FailureMessage -> Attribution)
-> Either DecodeError FailureMessage
-> Attribution
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Attribution -> DecodeError -> Attribution
forall a b. a -> b -> a
const (Int -> Attribution
MalformedFailure Int
i)) (Int -> FailureMessage -> Attribution
Attributed Int
i)
                 (ByteString -> Either DecodeError FailureMessage
failure_message ByteString
body)
          else Int -> [SharedSecret] -> ErrorPacket -> Attribution
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [SharedSecret]
rest (ByteString -> ErrorPacket
ErrorPacket ByteString
q)

-- The failure message of a return packet (after its HMAC).
failure_message :: BS.ByteString -> Either DecodeError FailureMessage
failure_message :: ByteString -> Either DecodeError FailureMessage
failure_message ByteString
body = case ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
body of
  Just (Word16
len, ByteString
r0)
    | ByteString -> Int
BS.length ByteString
r0 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
len
    , let (ByteString
msg, ByteString
r1) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
len) ByteString
r0
    , Just (Word16
pad, ByteString
r2) <- ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
r1
    , ByteString -> Int
BS.length ByteString
r2 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
pad
    -> ByteString -> Either DecodeError FailureMessage
decode_failure_message ByteString
msg
  Maybe (Word16, ByteString)
_ -> DecodeError -> Either DecodeError FailureMessage
forall a b. a -> Either a b
Left DecodeError
InvalidLength