{-# OPTIONS_HADDOCK hide #-}

-- |
-- Module: Lightning.Protocol.BOLT4.Codec
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Encodings of the BOLT #4 types.

module Lightning.Protocol.BOLT4.Codec (
    encode_onion_packet
  , decode_onion_packet
  , encode_hop_payload
  , decode_hop_payload
  , encode_blinded_hop_data
  , decode_blinded_hop_data
  , encode_failure_message
  , decode_failure_message
  ) where

import Data.Bifunctor (first)
import qualified Data.ByteString as BS
import Data.Maybe (catMaybes)
import Data.Word (Word16, Word64)
import qualified Lightning.Protocol.BOLT1 as BOLT1
import Lightning.Protocol.BOLT4.Types
import qualified Lightning.Protocol.BOLT9 as BOLT9

-- onion packets --------------------------------------------------------------

-- | Encode an t'OnionPacket' (1366 bytes).
--
--   >>> let Just pk = BOLT1.point (BS.cons 0x02 (BS.replicate 32 0x01))
--   >>> let Just hp = hop_payloads (BS.replicate 1300 0)
--   >>> let Just mac = hmac32 (BS.replicate 32 0)
--   >>> BS.length (encode_onion_packet (OnionPacket 0 pk hp mac))
--   1366
encode_onion_packet :: OnionPacket -> BS.ByteString
encode_onion_packet :: OnionPacket -> ByteString
encode_onion_packet (OnionPacket Word8
v Point
k HopPayloads
hp Hmac32
mac) = [ByteString] -> ByteString
BS.concat
  [Word8 -> ByteString
BS.singleton Word8
v, Point -> ByteString
BOLT1.un_point Point
k, HopPayloads -> ByteString
un_hop_payloads HopPayloads
hp, Hmac32 -> ByteString
un_hmac32 Hmac32
mac]

-- | Decode an t'OnionPacket' from exactly 1366 bytes. The public key must
--   carry a compressed-encoding prefix; the version byte is not checked
--   (see 'Lightning.Protocol.BOLT4.process').
--
--   >>> decode_onion_packet (BS.replicate 1365 0)
--   Left InvalidLength
decode_onion_packet :: BS.ByteString -> Either DecodeError OnionPacket
decode_onion_packet :: ByteString -> Either DecodeError OnionPacket
decode_onion_packet ByteString
bs = case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
bs of
  Just (Word8
v, ByteString
rest) | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1366 -> do
    let (ByteString
k, ByteString
r0)   = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
33 ByteString
rest
        (ByteString
hp, ByteString
mac) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
1300 ByteString
r0
    pk <- Either DecodeError Point
-> (Point -> Either DecodeError Point)
-> Maybe Point
-> Either DecodeError Point
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (DecodeError -> Either DecodeError Point
forall a b. a -> Either a b
Left DecodeError
InvalidPoint) Point -> Either DecodeError Point
forall a b. b -> Either a b
Right (ByteString -> Maybe Point
BOLT1.point ByteString
k)
    pure (OnionPacket v pk (HopPayloads hp) (Hmac32 mac))
  Maybe (Word8, ByteString)
_ -> DecodeError -> Either DecodeError OnionPacket
forall a b. a -> Either a b
Left DecodeError
InvalidLength

-- TLV helpers ----------------------------------------------------------------

-- encode typed records with extra ones, none of which may have a known
-- type
encode_tlvs
  :: [Word64]
  -> [BOLT1.TlvRecord]
  -> BOLT1.TlvStream
  -> Either EncodeError BS.ByteString
encode_tlvs :: [Word64]
-> [TlvRecord] -> TlvStream -> Either EncodeError ByteString
encode_tlvs [Word64]
known [TlvRecord]
typed TlvStream
extra
  | (TlvRecord -> Bool) -> [TlvRecord] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Word64 -> [Word64] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Word64]
known) (Word64 -> Bool) -> (TlvRecord -> Word64) -> TlvRecord -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TlvRecord -> Word64
BOLT1.tlv_type) [TlvRecord]
ex = EncodeError -> Either EncodeError ByteString
forall a b. a -> Either a b
Left EncodeError
ConflictingTlv
  | Bool
otherwise = case [TlvRecord] -> Maybe TlvStream
BOLT1.tlv_stream ([TlvRecord]
typed [TlvRecord] -> [TlvRecord] -> [TlvRecord]
forall a. [a] -> [a] -> [a]
++ [TlvRecord]
ex) of
      Maybe TlvStream
Nothing -> EncodeError -> Either EncodeError ByteString
forall a b. a -> Either a b
Left EncodeError
ConflictingTlv
      Just TlvStream
s  -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (TlvStream -> ByteString
BOLT1.encode_tlv_stream TlvStream
s)
  where
    ex :: [TlvRecord]
ex = TlvStream -> [TlvRecord]
BOLT1.un_tlv_stream TlvStream
extra

record :: Word64 -> (a -> BS.ByteString) -> Maybe a -> Maybe BOLT1.TlvRecord
record :: forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
t a -> ByteString
f = (a -> TlvRecord) -> Maybe a -> Maybe TlvRecord
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Word64 -> ByteString -> TlvRecord
BOLT1.TlvRecord Word64
t (ByteString -> TlvRecord) -> (a -> ByteString) -> a -> TlvRecord
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> ByteString
f)

-- decode a TLV stream with the given known types
decode_tlvs :: [Word64] -> BS.ByteString -> Either DecodeError BOLT1.TlvStream
decode_tlvs :: [Word64] -> ByteString -> Either DecodeError TlvStream
decode_tlvs [Word64]
known =
  (TlvError -> DecodeError)
-> Either TlvError TlvStream -> Either DecodeError TlvStream
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first TlvError -> DecodeError
InvalidTlvStream (Either TlvError TlvStream -> Either DecodeError TlvStream)
-> (ByteString -> Either TlvError TlvStream)
-> ByteString
-> Either DecodeError TlvStream
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Word64 -> Bool) -> ByteString -> Either TlvError TlvStream
BOLT1.decode_tlv_stream (Word64 -> [Word64] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Word64]
known)

-- parse the value of a record, if present
field
  :: Word64
  -> (BS.ByteString -> Maybe a)
  -> BOLT1.TlvStream
  -> Either DecodeError (Maybe a)
field :: forall a.
Word64
-> (ByteString -> Maybe a)
-> TlvStream
-> Either DecodeError (Maybe a)
field Word64
t ByteString -> Maybe a
p TlvStream
s = case Word64 -> TlvStream -> Maybe ByteString
BOLT1.lookup_tlv Word64
t TlvStream
s of
  Maybe ByteString
Nothing -> Maybe a -> Either DecodeError (Maybe a)
forall a b. b -> Either a b
Right Maybe a
forall a. Maybe a
Nothing
  Just ByteString
v  -> Either DecodeError (Maybe a)
-> (a -> Either DecodeError (Maybe a))
-> Maybe a
-> Either DecodeError (Maybe a)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (DecodeError -> Either DecodeError (Maybe a)
forall a b. a -> Either a b
Left (Word64 -> DecodeError
InvalidTlvValue Word64
t)) (Maybe a -> Either DecodeError (Maybe a)
forall a b. b -> Either a b
Right (Maybe a -> Either DecodeError (Maybe a))
-> (a -> Maybe a) -> a -> Either DecodeError (Maybe a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Maybe a
forall a. a -> Maybe a
Just) (ByteString -> Maybe a
p ByteString
v)

-- the unknown records of a stream
extra_tlvs :: [Word64] -> BOLT1.TlvStream -> BOLT1.TlvStream
extra_tlvs :: [Word64] -> TlvStream -> TlvStream
extra_tlvs [Word64]
known = (Word64 -> Bool) -> TlvStream -> TlvStream
BOLT1.filter_tlv_stream (Word64 -> [Word64] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Word64]
known)

-- a decoder that must consume its whole input
whole
  :: (BS.ByteString -> Maybe (a, BS.ByteString))
  -> BS.ByteString
  -> Maybe a
whole :: forall a.
(ByteString -> Maybe (a, ByteString)) -> ByteString -> Maybe a
whole ByteString -> Maybe (a, ByteString)
d ByteString
bs = case ByteString -> Maybe (a, ByteString)
d ByteString
bs of
  Just (a
a, ByteString
r) | ByteString -> Bool
BS.null ByteString
r -> a -> Maybe a
forall a. a -> Maybe a
Just a
a
  Maybe (a, ByteString)
_ -> Maybe a
forall a. Maybe a
Nothing

encode_tu_msat :: BOLT1.MilliSatoshi -> BS.ByteString
encode_tu_msat :: MilliSatoshi -> ByteString
encode_tu_msat = Word64 -> ByteString
BOLT1.encode_tu64 (Word64 -> ByteString)
-> (MilliSatoshi -> Word64) -> MilliSatoshi -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MilliSatoshi -> Word64
BOLT1.un_milli_satoshi

decode_tu_msat :: BS.ByteString -> Maybe BOLT1.MilliSatoshi
decode_tu_msat :: ByteString -> Maybe MilliSatoshi
decode_tu_msat ByteString
v = ByteString -> Maybe Word64
BOLT1.decode_tu64 ByteString
v Maybe Word64
-> (Word64 -> Maybe MilliSatoshi) -> Maybe MilliSatoshi
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Word64 -> Maybe MilliSatoshi
BOLT1.milli_satoshi

-- hop payloads ---------------------------------------------------------------

hop_payload_types :: [Word64]
hop_payload_types :: [Word64]
hop_payload_types = [Word64
2, Word64
4, Word64
6, Word64
8, Word64
10, Word64
12, Word64
16, Word64
18]

-- | Encode a t'HopPayload' as a @payload@ TLV stream (without its length
--   prefix). Fails if 'hp_extra' has a record of a known type.
--
--   >>> let hp = empty_hop_payload { hp_outgoing_cltv_value = Just 144 }
--   >>> encode_hop_payload hp
--   Right "\EOT\SOH\144"
encode_hop_payload :: HopPayload -> Either EncodeError BS.ByteString
encode_hop_payload :: HopPayload -> Either EncodeError ByteString
encode_hop_payload HopPayload
hp = [Word64]
-> [TlvRecord] -> TlvStream -> Either EncodeError ByteString
encode_tlvs [Word64]
hop_payload_types [TlvRecord]
typed (HopPayload -> TlvStream
hp_extra HopPayload
hp)
  where
    typed :: [TlvRecord]
typed = [Maybe TlvRecord] -> [TlvRecord]
forall a. [Maybe a] -> [a]
catMaybes
      [ Word64
-> (MilliSatoshi -> ByteString)
-> Maybe MilliSatoshi
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
2 MilliSatoshi -> ByteString
encode_tu_msat (HopPayload -> Maybe MilliSatoshi
hp_amt_to_forward HopPayload
hp)
      , Word64 -> (Word32 -> ByteString) -> Maybe Word32 -> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
4 Word32 -> ByteString
BOLT1.encode_tu32 (HopPayload -> Maybe Word32
hp_outgoing_cltv_value HopPayload
hp)
      , Word64
-> (ShortChannelId -> ByteString)
-> Maybe ShortChannelId
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
6 ShortChannelId -> ByteString
BOLT1.encode_short_channel_id (HopPayload -> Maybe ShortChannelId
hp_short_channel_id HopPayload
hp)
      , Word64
-> (PaymentData -> ByteString)
-> Maybe PaymentData
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
8 PaymentData -> ByteString
encode_payment_data (HopPayload -> Maybe PaymentData
hp_payment_data HopPayload
hp)
      , Word64
-> (ByteString -> ByteString)
-> Maybe ByteString
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
10 ByteString -> ByteString
forall a. a -> a
id (HopPayload -> Maybe ByteString
hp_encrypted_data HopPayload
hp)
      , Word64 -> (Point -> ByteString) -> Maybe Point -> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
12 Point -> ByteString
BOLT1.un_point (HopPayload -> Maybe Point
hp_current_path_key HopPayload
hp)
      , Word64
-> (ByteString -> ByteString)
-> Maybe ByteString
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
16 ByteString -> ByteString
forall a. a -> a
id (HopPayload -> Maybe ByteString
hp_payment_metadata HopPayload
hp)
      , Word64
-> (MilliSatoshi -> ByteString)
-> Maybe MilliSatoshi
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
18 MilliSatoshi -> ByteString
encode_tu_msat (HopPayload -> Maybe MilliSatoshi
hp_total_amount_msat HopPayload
hp)
      ]

-- | Decode a @payload@ TLV stream (without its length prefix). Fails on
--   a malformed stream, an unknown even type, or a malformed known
--   record.
--
--   >>> fmap hp_outgoing_cltv_value (decode_hop_payload "\EOT\SOH\144")
--   Right (Just 144)
--   >>> decode_hop_payload "\DC4\NUL"
--   Left (InvalidTlvStream (TlvUnknownEvenType 20))
decode_hop_payload :: BS.ByteString -> Either DecodeError HopPayload
decode_hop_payload :: ByteString -> Either DecodeError HopPayload
decode_hop_payload ByteString
bs = do
  s <- [Word64] -> ByteString -> Either DecodeError TlvStream
decode_tlvs [Word64]
hop_payload_types ByteString
bs
  HopPayload
    <$> field 2 decode_tu_msat s
    <*> field 4 BOLT1.decode_tu32 s
    <*> field 6 (whole BOLT1.decode_short_channel_id) s
    <*> field 8 decode_payment_data s
    <*> field 10 Just s
    <*> field 12 BOLT1.point s
    <*> field 16 Just s
    <*> field 18 decode_tu_msat s
    <*> pure (extra_tlvs hop_payload_types s)

encode_payment_data :: PaymentData -> BS.ByteString
encode_payment_data :: PaymentData -> ByteString
encode_payment_data (PaymentData PaymentSecret
s MilliSatoshi
t) = PaymentSecret -> ByteString
un_payment_secret PaymentSecret
s ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> MilliSatoshi -> ByteString
encode_tu_msat MilliSatoshi
t

decode_payment_data :: BS.ByteString -> Maybe PaymentData
decode_payment_data :: ByteString -> Maybe PaymentData
decode_payment_data ByteString
v = do
  let (ByteString
s, ByteString
t) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
32 ByteString
v
  PaymentSecret -> MilliSatoshi -> PaymentData
PaymentData (PaymentSecret -> MilliSatoshi -> PaymentData)
-> Maybe PaymentSecret -> Maybe (MilliSatoshi -> PaymentData)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Maybe PaymentSecret
payment_secret ByteString
s Maybe (MilliSatoshi -> PaymentData)
-> Maybe MilliSatoshi -> Maybe PaymentData
forall a b. Maybe (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ByteString -> Maybe MilliSatoshi
decode_tu_msat ByteString
t

-- blinded hop data -----------------------------------------------------------

blinded_hop_data_types :: [Word64]
blinded_hop_data_types :: [Word64]
blinded_hop_data_types = [Word64
1, Word64
2, Word64
4, Word64
6, Word64
8, Word64
10, Word64
12, Word64
14]

-- | Encode t'BlindedHopData' as an @encrypted_data_tlv@ stream. Fails if
--   'bhd_extra' has a record of a known type.
encode_blinded_hop_data :: BlindedHopData -> Either EncodeError BS.ByteString
encode_blinded_hop_data :: BlindedHopData -> Either EncodeError ByteString
encode_blinded_hop_data BlindedHopData
d =
    [Word64]
-> [TlvRecord] -> TlvStream -> Either EncodeError ByteString
encode_tlvs [Word64]
blinded_hop_data_types [TlvRecord]
typed (BlindedHopData -> TlvStream
bhd_extra BlindedHopData
d)
  where
    typed :: [TlvRecord]
typed = [Maybe TlvRecord] -> [TlvRecord]
forall a. [Maybe a] -> [a]
catMaybes
      [ Word64
-> (ByteString -> ByteString)
-> Maybe ByteString
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
1 ByteString -> ByteString
forall a. a -> a
id (BlindedHopData -> Maybe ByteString
bhd_padding BlindedHopData
d)
      , Word64
-> (ShortChannelId -> ByteString)
-> Maybe ShortChannelId
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
2 ShortChannelId -> ByteString
BOLT1.encode_short_channel_id (BlindedHopData -> Maybe ShortChannelId
bhd_short_channel_id BlindedHopData
d)
      , Word64 -> (Point -> ByteString) -> Maybe Point -> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
4 Point -> ByteString
BOLT1.un_point (BlindedHopData -> Maybe Point
bhd_next_node_id BlindedHopData
d)
      , Word64
-> (ByteString -> ByteString)
-> Maybe ByteString
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
6 ByteString -> ByteString
forall a. a -> a
id (BlindedHopData -> Maybe ByteString
bhd_path_id BlindedHopData
d)
      , Word64 -> (Point -> ByteString) -> Maybe Point -> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
8 Point -> ByteString
BOLT1.un_point (BlindedHopData -> Maybe Point
bhd_next_path_key_override BlindedHopData
d)
      , Word64
-> (PaymentRelay -> ByteString)
-> Maybe PaymentRelay
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
10 PaymentRelay -> ByteString
encode_payment_relay (BlindedHopData -> Maybe PaymentRelay
bhd_payment_relay BlindedHopData
d)
      , Word64
-> (PaymentConstraints -> ByteString)
-> Maybe PaymentConstraints
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
12 PaymentConstraints -> ByteString
encode_payment_constraints (BlindedHopData -> Maybe PaymentConstraints
bhd_payment_constraints BlindedHopData
d)
      , Word64
-> (FeatureVector -> ByteString)
-> Maybe FeatureVector
-> Maybe TlvRecord
forall a. Word64 -> (a -> ByteString) -> Maybe a -> Maybe TlvRecord
record Word64
14 FeatureVector -> ByteString
BOLT9.render (BlindedHopData -> Maybe FeatureVector
bhd_allowed_features BlindedHopData
d)
      ]

-- | Decode an @encrypted_data_tlv@ stream. Fails on a malformed stream,
--   an unknown even type, or a malformed known record.
--
--   >>> fmap bhd_path_id (decode_blinded_hop_data "\ACK\apath id")
--   Right (Just "path id")
decode_blinded_hop_data :: BS.ByteString -> Either DecodeError BlindedHopData
decode_blinded_hop_data :: ByteString -> Either DecodeError BlindedHopData
decode_blinded_hop_data ByteString
bs = do
  s <- [Word64] -> ByteString -> Either DecodeError TlvStream
decode_tlvs [Word64]
blinded_hop_data_types ByteString
bs
  BlindedHopData
    <$> field 1 Just s
    <*> field 2 (whole BOLT1.decode_short_channel_id) s
    <*> field 4 BOLT1.point s
    <*> field 6 Just s
    <*> field 8 BOLT1.point s
    <*> field 10 decode_payment_relay s
    <*> field 12 decode_payment_constraints s
    <*> field 14 (Just . BOLT9.parse) s
    <*> pure (extra_tlvs blinded_hop_data_types s)

encode_payment_relay :: PaymentRelay -> BS.ByteString
encode_payment_relay :: PaymentRelay -> ByteString
encode_payment_relay (PaymentRelay Word16
c Word32
p Word32
b) =
  Word16 -> ByteString
BOLT1.encode_u16 Word16
c ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word32 -> ByteString
BOLT1.encode_u32 Word32
p ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word32 -> ByteString
BOLT1.encode_tu32 Word32
b

decode_payment_relay :: BS.ByteString -> Maybe PaymentRelay
decode_payment_relay :: ByteString -> Maybe PaymentRelay
decode_payment_relay ByteString
v = do
  (c, r0) <- ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
v
  (p, r1) <- BOLT1.decode_u32 r0
  PaymentRelay c p <$> BOLT1.decode_tu32 r1

encode_payment_constraints :: PaymentConstraints -> BS.ByteString
encode_payment_constraints :: PaymentConstraints -> ByteString
encode_payment_constraints (PaymentConstraints Word32
c MilliSatoshi
m) =
  Word32 -> ByteString
BOLT1.encode_u32 Word32
c ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> MilliSatoshi -> ByteString
encode_tu_msat MilliSatoshi
m

decode_payment_constraints :: BS.ByteString -> Maybe PaymentConstraints
decode_payment_constraints :: ByteString -> Maybe PaymentConstraints
decode_payment_constraints ByteString
v = do
  (c, r) <- ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32 ByteString
v
  PaymentConstraints c <$> decode_tu_msat r

-- failure messages -----------------------------------------------------------

-- | Encode a t'FailureMessage': the failure code, its data and the TLV
--   stream. Fails if a @channel_update@ exceeds 65535 bytes.
--
--   >>> let tlvs = BOLT1.empty_tlv_stream
--   >>> encode_failure_message (FailureMessage TemporaryNodeFailure tlvs)
--   Right " \STX"
encode_failure_message :: FailureMessage -> Either EncodeError BS.ByteString
encode_failure_message :: FailureMessage -> Either EncodeError ByteString
encode_failure_message (FailureMessage Failure
f TlvStream
tlvs) = do
  body <- Failure -> Either EncodeError ByteString
encode_failure Failure
f
  pure (BOLT1.encode_u16 (failure_code f) <> body
          <> BOLT1.encode_tlv_stream tlvs)

encode_failure :: Failure -> Either EncodeError BS.ByteString
encode_failure :: Failure -> Either EncodeError ByteString
encode_failure Failure
f = case Failure
f of
  Failure
TemporaryNodeFailure                 -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  Failure
PermanentNodeFailure                 -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  Failure
RequiredNodeFeatureMissing           -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  InvalidOnionVersion OnionHash
h                -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (OnionHash -> ByteString
un_onion_hash OnionHash
h)
  InvalidOnionHmac OnionHash
h                   -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (OnionHash -> ByteString
un_onion_hash OnionHash
h)
  InvalidOnionKey OnionHash
h                    -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (OnionHash -> ByteString
un_onion_hash OnionHash
h)
  TemporaryChannelFailure ByteString
u            -> ByteString -> Either EncodeError ByteString
update ByteString
u
  Failure
PermanentChannelFailure              -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  Failure
RequiredChannelFeatureMissing        -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  Failure
UnknownNextPeer                      -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  AmountBelowMinimum MilliSatoshi
m ByteString
u               -> (MilliSatoshi -> ByteString
msat MilliSatoshi
m ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<>) (ByteString -> ByteString)
-> Either EncodeError ByteString -> Either EncodeError ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either EncodeError ByteString
update ByteString
u
  FeeInsufficient MilliSatoshi
m ByteString
u                  -> (MilliSatoshi -> ByteString
msat MilliSatoshi
m ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<>) (ByteString -> ByteString)
-> Either EncodeError ByteString -> Either EncodeError ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either EncodeError ByteString
update ByteString
u
  IncorrectCltvExpiry Word32
c ByteString
u              -> (Word32 -> ByteString
BOLT1.encode_u32 Word32
c ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<>) (ByteString -> ByteString)
-> Either EncodeError ByteString -> Either EncodeError ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either EncodeError ByteString
update ByteString
u
  ExpiryTooSoon ByteString
u                      -> ByteString -> Either EncodeError ByteString
update ByteString
u
  IncorrectOrUnknownPaymentDetails MilliSatoshi
m Word32
h -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (MilliSatoshi -> ByteString
msat MilliSatoshi
m ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word32 -> ByteString
BOLT1.encode_u32 Word32
h)
  FinalIncorrectCltvExpiry Word32
c           -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (Word32 -> ByteString
BOLT1.encode_u32 Word32
c)
  FinalIncorrectHtlcAmount MilliSatoshi
m           -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (MilliSatoshi -> ByteString
msat MilliSatoshi
m)
  ChannelDisabled Word16
d ByteString
u                  -> (Word16 -> ByteString
BOLT1.encode_u16 Word16
d ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<>) (ByteString -> ByteString)
-> Either EncodeError ByteString -> Either EncodeError ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either EncodeError ByteString
update ByteString
u
  Failure
ExpiryTooFar                         -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  InvalidOnionPayload Maybe (Word64, Word16)
Nothing          -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  InvalidOnionPayload (Just (Word64
t, Word16
o))    ->
    ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (Word64 -> ByteString
BOLT1.encode_bigsize Word64
t ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word16 -> ByteString
BOLT1.encode_u16 Word16
o)
  Failure
MppTimeout                           -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
forall a. Monoid a => a
mempty
  InvalidOnionBlinding OnionHash
h               -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (OnionHash -> ByteString
un_onion_hash OnionHash
h)
  UnknownFailure Word16
_ ByteString
d                   -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right ByteString
d
  where
    msat :: MilliSatoshi -> ByteString
msat = MilliSatoshi -> ByteString
BOLT1.encode_milli_satoshi
    update :: ByteString -> Either EncodeError ByteString
update = Either EncodeError ByteString
-> (ByteString -> Either EncodeError ByteString)
-> Maybe ByteString
-> Either EncodeError ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (EncodeError -> Either EncodeError ByteString
forall a b. a -> Either a b
Left EncodeError
FieldTooLong) ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (Maybe ByteString -> Either EncodeError ByteString)
-> (ByteString -> Maybe ByteString)
-> ByteString
-> Either EncodeError ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe ByteString
BOLT1.encode_u16_prefixed

-- | Decode a failure message.
--
--   Per BOLT #4, bytes following a failure's data are ignored unless
--   they form a valid TLV stream (which, as no failure TLV types are
--   defined, may hold only odd types). The data of an unknown failure
--   code is every byte following it.
--
--   >>> fmap fm_failure (decode_failure_message " \STX")
--   Right TemporaryNodeFailure
--   >>> decode_failure_message "\DLE\r"
--   Left (InvalidFailureData 4109)
decode_failure_message :: BS.ByteString -> Either DecodeError FailureMessage
decode_failure_message :: ByteString -> Either DecodeError FailureMessage
decode_failure_message ByteString
bs = case ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
bs of
  Maybe (Word16, ByteString)
Nothing -> DecodeError -> Either DecodeError FailureMessage
forall a b. a -> Either a b
Left DecodeError
InvalidLength
  Just (Word16
c, ByteString
rest) -> case Word16 -> ByteString -> Maybe (Failure, ByteString)
decode_failure Word16
c ByteString
rest of
    Maybe (Failure, ByteString)
Nothing -> DecodeError -> Either DecodeError FailureMessage
forall a b. a -> Either a b
Left (Word16 -> DecodeError
InvalidFailureData Word16
c)
    Just (Failure
f, ByteString
extra) ->
      let tlvs :: TlvStream
tlvs = (TlvError -> TlvStream)
-> (TlvStream -> TlvStream)
-> Either TlvError TlvStream
-> TlvStream
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (TlvStream -> TlvError -> TlvStream
forall a b. a -> b -> a
const TlvStream
BOLT1.empty_tlv_stream) TlvStream -> TlvStream
forall a. a -> a
id
                   ((Word64 -> Bool) -> ByteString -> Either TlvError TlvStream
BOLT1.decode_tlv_stream (Bool -> Word64 -> Bool
forall a b. a -> b -> a
const Bool
False) ByteString
extra)
      in  FailureMessage -> Either DecodeError FailureMessage
forall a b. b -> Either a b
Right (Failure -> TlvStream -> FailureMessage
FailureMessage Failure
f TlvStream
tlvs)

decode_failure :: Word16 -> BS.ByteString -> Maybe (Failure, BS.ByteString)
decode_failure :: Word16 -> ByteString -> Maybe (Failure, ByteString)
decode_failure Word16
c ByteString
bs = case Word16
c of
  Word16
0x2002 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
TemporaryNodeFailure
  Word16
0x6002 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
PermanentNodeFailure
  Word16
0x6003 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
RequiredNodeFeatureMissing
  Word16
0xc004 -> (OnionHash -> Failure) -> Maybe (Failure, ByteString)
forall {a}. (OnionHash -> a) -> Maybe (a, ByteString)
hashed OnionHash -> Failure
InvalidOnionVersion
  Word16
0xc005 -> (OnionHash -> Failure) -> Maybe (Failure, ByteString)
forall {a}. (OnionHash -> a) -> Maybe (a, ByteString)
hashed OnionHash -> Failure
InvalidOnionHmac
  Word16
0xc006 -> (OnionHash -> Failure) -> Maybe (Failure, ByteString)
forall {a}. (OnionHash -> a) -> Maybe (a, ByteString)
hashed OnionHash -> Failure
InvalidOnionKey
  Word16
0x1007 -> do
    (u, r) <- ByteString -> Maybe (ByteString, ByteString)
update ByteString
bs
    pure (TemporaryChannelFailure u, r)
  Word16
0x4008 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
PermanentChannelFailure
  Word16
0x4009 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
RequiredChannelFeatureMissing
  Word16
0x400a -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
UnknownNextPeer
  Word16
0x100b -> do
    (m, r0) <- ByteString -> Maybe (MilliSatoshi, ByteString)
BOLT1.decode_milli_satoshi ByteString
bs
    (u, r1) <- update r0
    pure (AmountBelowMinimum m u, r1)
  Word16
0x100c -> do
    (m, r0) <- ByteString -> Maybe (MilliSatoshi, ByteString)
BOLT1.decode_milli_satoshi ByteString
bs
    (u, r1) <- update r0
    pure (FeeInsufficient m u, r1)
  Word16
0x100d -> do
    (e, r0) <- ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32 ByteString
bs
    (u, r1) <- update r0
    pure (IncorrectCltvExpiry e u, r1)
  Word16
0x100e -> do
    (u, r) <- ByteString -> Maybe (ByteString, ByteString)
update ByteString
bs
    pure (ExpiryTooSoon u, r)
  Word16
0x400f -> do
    (m, r0) <- ByteString -> Maybe (MilliSatoshi, ByteString)
BOLT1.decode_milli_satoshi ByteString
bs
    (h, r1) <- BOLT1.decode_u32 r0
    pure (IncorrectOrUnknownPaymentDetails m h, r1)
  Word16
0x0012 -> do
    (e, r) <- ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32 ByteString
bs
    pure (FinalIncorrectCltvExpiry e, r)
  Word16
0x0013 -> do
    (m, r) <- ByteString -> Maybe (MilliSatoshi, ByteString)
BOLT1.decode_milli_satoshi ByteString
bs
    pure (FinalIncorrectHtlcAmount m, r)
  Word16
0x1014 -> do
    (d, r0) <- ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
bs
    (u, r1) <- update r0
    pure (ChannelDisabled d u, r1)
  Word16
0x0015 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
ExpiryTooFar
  Word16
0x4016 -> (Failure, ByteString) -> Maybe (Failure, ByteString)
forall a. a -> Maybe a
Just ((Failure, ByteString) -> Maybe (Failure, ByteString))
-> (Failure, ByteString) -> Maybe (Failure, ByteString)
forall a b. (a -> b) -> a -> b
$ case ByteString -> Maybe (Word64, ByteString)
BOLT1.decode_bigsize ByteString
bs of
    Just (Word64
t, ByteString
r0) | Just (Word16
o, ByteString
r1) <- ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16 ByteString
r0 ->
      (Maybe (Word64, Word16) -> Failure
InvalidOnionPayload ((Word64, Word16) -> Maybe (Word64, Word16)
forall a. a -> Maybe a
Just (Word64
t, Word16
o)), ByteString
r1)
    Maybe (Word64, ByteString)
_ -> (Maybe (Word64, Word16) -> Failure
InvalidOnionPayload Maybe (Word64, Word16)
forall a. Maybe a
Nothing, ByteString
bs)
  Word16
0x0017 -> Failure -> Maybe (Failure, ByteString)
forall {a}. a -> Maybe (a, ByteString)
plain Failure
MppTimeout
  Word16
0xc018 -> (OnionHash -> Failure) -> Maybe (Failure, ByteString)
forall {a}. (OnionHash -> a) -> Maybe (a, ByteString)
hashed OnionHash -> Failure
InvalidOnionBlinding
  Word16
_      -> (Failure, ByteString) -> Maybe (Failure, ByteString)
forall a. a -> Maybe a
Just (Word16 -> ByteString -> Failure
UnknownFailure Word16
c ByteString
bs, ByteString
BS.empty)
  where
    plain :: a -> Maybe (a, ByteString)
plain a
f = (a, ByteString) -> Maybe (a, ByteString)
forall a. a -> Maybe a
Just (a
f, ByteString
bs)
    hashed :: (OnionHash -> a) -> Maybe (a, ByteString)
hashed OnionHash -> a
g
      | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
32 = Maybe (a, ByteString)
forall a. Maybe a
Nothing
      | Bool
otherwise =
          let (ByteString
h, ByteString
r) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
32 ByteString
bs
          in  (a, ByteString) -> Maybe (a, ByteString)
forall a. a -> Maybe a
Just (OnionHash -> a
g (ByteString -> OnionHash
OnionHash ByteString
h), ByteString
r)
    update :: ByteString -> Maybe (ByteString, ByteString)
update = ByteString -> Maybe (ByteString, ByteString)
BOLT1.decode_u16_prefixed