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

-- |
-- Module: Lightning.Protocol.BOLT7.Codec
-- Copyright: (c) 2025 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Encoding and decoding of BOLT #7 messages.

module Lightning.Protocol.BOLT7.Codec (
    EncodeError(..)
  , DecodeError(..)
  , encode_message
  , decode_message
  , encode_channel_announcement
  , decode_channel_announcement
  , encode_node_announcement
  , decode_node_announcement
  , encode_channel_update
  , decode_channel_update
  , encode_announcement_signatures
  , decode_announcement_signatures
  , encode_query_short_channel_ids
  , decode_query_short_channel_ids
  , encode_reply_short_channel_ids_end
  , decode_reply_short_channel_ids_end
  , encode_query_channel_range
  , decode_query_channel_range
  , encode_reply_channel_range
  , decode_reply_channel_range
  , encode_gossip_timestamp_filter
  , decode_gossip_timestamp_filter
  ) where

import Control.DeepSeq (NFData)
import qualified Data.ByteString as BS
import Data.Word (Word8, Word16, Word32, Word64)
import GHC.Generics (Generic)
import Lightning.Protocol.BOLT1
  ( ChainHash, MilliSatoshi, Point, ShortChannelId, Signature
  , TlvError, TlvRecord(..), TlvStream )
import qualified Lightning.Protocol.BOLT1 as BOLT1
import qualified Lightning.Protocol.BOLT9 as BOLT9
import Lightning.Protocol.BOLT7.Messages
import Lightning.Protocol.BOLT7.Types

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

-- | Why a message failed to encode.
data EncodeError
  = EncodeLengthOverflow
    -- ^ a length-prefixed field exceeds 65535 bytes
  | EncodeInvalidTlvs
    -- ^ a @_tlvs@ field holds a record of a type the message defines
  | EncodeCountMismatch
    -- ^ query flags, timestamps or checksums don't number one per
    --   short channel id
  | EncodeInvalidAddresses
    -- ^ 'na_unknown_addresses' begins with a descriptor of a known type
  deriving (EncodeError -> EncodeError -> Bool
(EncodeError -> EncodeError -> Bool)
-> (EncodeError -> EncodeError -> Bool) -> Eq EncodeError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EncodeError -> EncodeError -> Bool
== :: EncodeError -> EncodeError -> Bool
$c/= :: EncodeError -> EncodeError -> Bool
/= :: EncodeError -> EncodeError -> Bool
Eq, Int -> EncodeError -> ShowS
[EncodeError] -> ShowS
EncodeError -> String
(Int -> EncodeError -> ShowS)
-> (EncodeError -> String)
-> ([EncodeError] -> ShowS)
-> Show EncodeError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodeError -> ShowS
showsPrec :: Int -> EncodeError -> ShowS
$cshow :: EncodeError -> String
show :: EncodeError -> String
$cshowList :: [EncodeError] -> ShowS
showList :: [EncodeError] -> ShowS
Show, (forall x. EncodeError -> Rep EncodeError x)
-> (forall x. Rep EncodeError x -> EncodeError)
-> Generic EncodeError
forall x. Rep EncodeError x -> EncodeError
forall x. EncodeError -> Rep EncodeError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. EncodeError -> Rep EncodeError x
from :: forall x. EncodeError -> Rep EncodeError x
$cto :: forall x. Rep EncodeError x -> EncodeError
to :: forall x. Rep EncodeError x -> EncodeError
Generic)

instance NFData EncodeError

-- | Why a message failed to decode.
data DecodeError
  = DecodeInsufficientBytes
    -- ^ the input ended before a field did
  | DecodeInvalidPoint
    -- ^ a point lacks a compressed-encoding prefix (0x02 or 0x03)
  | DecodeInvalidAmount
    -- ^ an amount exceeds 21 million BTC
  | DecodeInvalidBool
    -- ^ a boolean byte is neither 0 nor 1
  | DecodeInvalidShortChannelIds
    -- ^ @encoded_short_ids@ lacks an encoding type, or isn't a whole
    --   number of short channel ids
  | DecodeUnknownEncoding !Word8
    -- ^ an encoded array uses an unknown encoding type (type 1, zlib,
    --   is no longer allowed)
  | DecodeCountMismatch
    -- ^ query flags, timestamps or checksums don't number one per
    --   short channel id
  | DecodeTlvError !TlvError
    -- ^ the message's TLV stream is malformed
  | DecodeInvalidTlvValue !Word64
    -- ^ a known TLV record (of the given type) has a malformed value
  | DecodeUnknownType !Word16
    -- ^ the message type is not one of BOLT #7's
  deriving (DecodeError -> DecodeError -> Bool
(DecodeError -> DecodeError -> Bool)
-> (DecodeError -> DecodeError -> Bool) -> Eq DecodeError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DecodeError -> DecodeError -> Bool
== :: DecodeError -> DecodeError -> Bool
$c/= :: DecodeError -> DecodeError -> Bool
/= :: DecodeError -> DecodeError -> Bool
Eq, Int -> DecodeError -> ShowS
[DecodeError] -> ShowS
DecodeError -> String
(Int -> DecodeError -> ShowS)
-> (DecodeError -> String)
-> ([DecodeError] -> ShowS)
-> Show DecodeError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DecodeError -> ShowS
showsPrec :: Int -> DecodeError -> ShowS
$cshow :: DecodeError -> String
show :: DecodeError -> String
$cshowList :: [DecodeError] -> ShowS
showList :: [DecodeError] -> ShowS
Show, (forall x. DecodeError -> Rep DecodeError x)
-> (forall x. Rep DecodeError x -> DecodeError)
-> Generic DecodeError
forall x. Rep DecodeError x -> DecodeError
forall x. DecodeError -> Rep DecodeError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DecodeError -> Rep DecodeError x
from :: forall x. DecodeError -> Rep DecodeError x
$cto :: forall x. Rep DecodeError x -> DecodeError
to :: forall x. Rep DecodeError x -> DecodeError
Generic)

instance NFData DecodeError

-- messages -------------------------------------------------------------------

-- | Encode a 'Message' payload (excluding the 2-byte message type; see
--   'message_type'). Frame the result with
--   'Lightning.Protocol.BOLT1.encode_envelope', which enforces the
--   65535-byte message limit.
encode_message :: Message -> Either EncodeError BS.ByteString
encode_message :: Message -> Either EncodeError ByteString
encode_message Message
m = case Message
m of
  MsgChannelAnnouncement ChannelAnnouncement
a     -> ChannelAnnouncement -> Either EncodeError ByteString
encode_channel_announcement ChannelAnnouncement
a
  MsgNodeAnnouncement NodeAnnouncement
a        -> NodeAnnouncement -> Either EncodeError ByteString
encode_node_announcement NodeAnnouncement
a
  MsgChannelUpdate ChannelUpdate
a           -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (ChannelUpdate -> ByteString
encode_channel_update ChannelUpdate
a)
  MsgAnnouncementSignatures AnnouncementSignatures
a  -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (AnnouncementSignatures -> ByteString
encode_announcement_signatures AnnouncementSignatures
a)
  MsgQueryShortChannelIds QueryShortChannelIds
a    -> QueryShortChannelIds -> Either EncodeError ByteString
encode_query_short_channel_ids QueryShortChannelIds
a
  MsgReplyShortChannelIdsEnd ReplyShortChannelIdsEnd
a -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (ReplyShortChannelIdsEnd -> ByteString
encode_reply_short_channel_ids_end ReplyShortChannelIdsEnd
a)
  MsgQueryChannelRange QueryChannelRange
a       -> QueryChannelRange -> Either EncodeError ByteString
encode_query_channel_range QueryChannelRange
a
  MsgReplyChannelRange ReplyChannelRange
a       -> ReplyChannelRange -> Either EncodeError ByteString
encode_reply_channel_range ReplyChannelRange
a
  MsgGossipTimestampFilter GossipTimestampFilter
a   -> ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (GossipTimestampFilter -> ByteString
encode_gossip_timestamp_filter GossipTimestampFilter
a)

-- | Decode a message payload, given its message type (as split off by
--   'Lightning.Protocol.BOLT1.decode_envelope').
--
--   >>> decode_message 260 "\NUL"
--   Left (DecodeUnknownType 260)
decode_message :: Word16 -> BS.ByteString -> Either DecodeError Message
decode_message :: Word16 -> ByteString -> Either DecodeError Message
decode_message Word16
t ByteString
bs = case Word16
t of
  Word16
256 -> ChannelAnnouncement -> Message
MsgChannelAnnouncement (ChannelAnnouncement -> Message)
-> Either DecodeError ChannelAnnouncement
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError ChannelAnnouncement
decode_channel_announcement ByteString
bs
  Word16
257 -> NodeAnnouncement -> Message
MsgNodeAnnouncement (NodeAnnouncement -> Message)
-> Either DecodeError NodeAnnouncement
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError NodeAnnouncement
decode_node_announcement ByteString
bs
  Word16
258 -> ChannelUpdate -> Message
MsgChannelUpdate (ChannelUpdate -> Message)
-> Either DecodeError ChannelUpdate -> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError ChannelUpdate
decode_channel_update ByteString
bs
  Word16
259 -> AnnouncementSignatures -> Message
MsgAnnouncementSignatures (AnnouncementSignatures -> Message)
-> Either DecodeError AnnouncementSignatures
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError AnnouncementSignatures
decode_announcement_signatures ByteString
bs
  Word16
261 -> QueryShortChannelIds -> Message
MsgQueryShortChannelIds (QueryShortChannelIds -> Message)
-> Either DecodeError QueryShortChannelIds
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError QueryShortChannelIds
decode_query_short_channel_ids ByteString
bs
  Word16
262 -> ReplyShortChannelIdsEnd -> Message
MsgReplyShortChannelIdsEnd (ReplyShortChannelIdsEnd -> Message)
-> Either DecodeError ReplyShortChannelIdsEnd
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError ReplyShortChannelIdsEnd
decode_reply_short_channel_ids_end ByteString
bs
  Word16
263 -> QueryChannelRange -> Message
MsgQueryChannelRange (QueryChannelRange -> Message)
-> Either DecodeError QueryChannelRange
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError QueryChannelRange
decode_query_channel_range ByteString
bs
  Word16
264 -> ReplyChannelRange -> Message
MsgReplyChannelRange (ReplyChannelRange -> Message)
-> Either DecodeError ReplyChannelRange
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError ReplyChannelRange
decode_reply_channel_range ByteString
bs
  Word16
265 -> GossipTimestampFilter -> Message
MsgGossipTimestampFilter (GossipTimestampFilter -> Message)
-> Either DecodeError GossipTimestampFilter
-> Either DecodeError Message
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError GossipTimestampFilter
decode_gossip_timestamp_filter ByteString
bs
  Word16
_   -> DecodeError -> Either DecodeError Message
forall a b. a -> Either a b
Left (Word16 -> DecodeError
DecodeUnknownType Word16
t)

-- channel_announcement -------------------------------------------------------

-- | Encode a t'ChannelAnnouncement' payload. Fails if the features exceed
--   65535 bytes.
encode_channel_announcement
  :: ChannelAnnouncement -> Either EncodeError BS.ByteString
encode_channel_announcement :: ChannelAnnouncement -> Either EncodeError ByteString
encode_channel_announcement ChannelAnnouncement
m = do
  f <- ByteString -> Either EncodeError ByteString
prefixed (FeatureVector -> ByteString
BOLT9.render (ChannelAnnouncement -> FeatureVector
ca_features ChannelAnnouncement
m))
  pure $ mconcat
    [ BOLT1.un_signature (ca_node_signature_1 m)
    , BOLT1.un_signature (ca_node_signature_2 m)
    , BOLT1.un_signature (ca_bitcoin_signature_1 m)
    , BOLT1.un_signature (ca_bitcoin_signature_2 m)
    , f
    , BOLT1.un_chain_hash (ca_chain_hash m)
    , BOLT1.encode_short_channel_id (ca_short_channel_id m)
    , BOLT1.un_point (ca_node_id_1 m)
    , BOLT1.un_point (ca_node_id_2 m)
    , BOLT1.un_point (ca_bitcoin_key_1 m)
    , BOLT1.un_point (ca_bitcoin_key_2 m)
    , BOLT1.encode_tlv_stream (ca_tlvs m)
    ]

-- | Decode a t'ChannelAnnouncement' payload.
decode_channel_announcement
  :: BS.ByteString -> Either DecodeError ChannelAnnouncement
decode_channel_announcement :: ByteString -> Either DecodeError ChannelAnnouncement
decode_channel_announcement ByteString
b0 = do
  (ns1, b1)  <- ByteString -> Either DecodeError (Signature, ByteString)
signature ByteString
b0
  (ns2, b2)  <- signature b1
  (bs1, b3)  <- signature b2
  (bs2, b4)  <- signature b3
  (f, b5)    <- u16_prefixed b4
  (ch, b6)   <- chain_hash b5
  (s, b7)    <- short_channel_id b6
  (n1, b8)   <- point b7
  (n2, b9)   <- point b8
  (bk1, b10) <- point b9
  (bk2, b11) <- point b10
  ext        <- extension b11
  pure ChannelAnnouncement
    { ca_node_signature_1    = ns1
    , ca_node_signature_2    = ns2
    , ca_bitcoin_signature_1 = bs1
    , ca_bitcoin_signature_2 = bs2
    , ca_features            = BOLT9.parse f
    , ca_chain_hash          = ch
    , ca_short_channel_id    = s
    , ca_node_id_1           = n1
    , ca_node_id_2           = n2
    , ca_bitcoin_key_1       = bk1
    , ca_bitcoin_key_2       = bk2
    , ca_tlvs                = ext
    }

-- node_announcement ----------------------------------------------------------

-- | Encode a t'NodeAnnouncement' payload. Fails if the features or the
--   addresses exceed 65535 bytes, or if 'na_unknown_addresses' begins
--   with a descriptor of a known type.
encode_node_announcement
  :: NodeAnnouncement -> Either EncodeError BS.ByteString
encode_node_announcement :: NodeAnnouncement -> Either EncodeError ByteString
encode_node_announcement NodeAnnouncement
m = do
  f <- ByteString -> Either EncodeError ByteString
prefixed (FeatureVector -> ByteString
BOLT9.render (NodeAnnouncement -> FeatureVector
na_features NodeAnnouncement
m))
  let unknown = NodeAnnouncement -> ByteString
na_unknown_addresses NodeAnnouncement
m
  case BS.uncons unknown of
    Just (Word8
t, ByteString
_) | Word8
t Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
1 Bool -> Bool -> Bool
&& Word8
t Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
5 -> EncodeError -> Either EncodeError ()
forall a b. a -> Either a b
Left EncodeError
EncodeInvalidAddresses
    Maybe (Word8, ByteString)
_ -> () -> Either EncodeError ()
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  as <- prefixed (foldMap encode_address (na_addresses m) <> unknown)
  let RgbColor r g b = na_rgb_color m
      Alias al = na_alias m
  pure $ mconcat
    [ BOLT1.un_signature (na_signature m)
    , f
    , BOLT1.encode_u32 (na_timestamp m)
    , BOLT1.un_point (na_node_id m)
    , BS.pack [r, g, b]
    , al
    , as
    , BOLT1.encode_tlv_stream (na_tlvs m)
    ]

encode_address :: Address -> BS.ByteString
encode_address :: Address -> ByteString
encode_address Address
a = case Address
a of
  AddrIPv4 (IPv4Addr ByteString
b) Word16
p   -> Word8 -> ByteString -> ByteString
BS.cons Word8
1 (ByteString
b ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word16 -> ByteString
BOLT1.encode_u16 Word16
p)
  AddrIPv6 (IPv6Addr ByteString
b) Word16
p   -> Word8 -> ByteString -> ByteString
BS.cons Word8
2 (ByteString
b ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word16 -> ByteString
BOLT1.encode_u16 Word16
p)
  AddrTorV2 (TorV2Addr ByteString
b)   -> Word8 -> ByteString -> ByteString
BS.cons Word8
3 ByteString
b
  AddrTorV3 (TorV3Addr ByteString
b) Word16
p -> Word8 -> ByteString -> ByteString
BS.cons Word8
4 (ByteString
b ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word16 -> ByteString
BOLT1.encode_u16 Word16
p)
  AddrDNS (Hostname ByteString
h) Word16
p    ->
    Word8 -> ByteString -> ByteString
BS.cons Word8
5 (Word8 -> ByteString -> ByteString
BS.cons (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
h)) (ByteString
h ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word16 -> ByteString
BOLT1.encode_u16 Word16
p))

-- | Decode a t'NodeAnnouncement' payload.
--
--   Address descriptors are parsed up to the first one of an unknown
--   type; it and the bytes after it are kept in 'na_unknown_addresses'.
--   A truncated descriptor of a known type is an error.
decode_node_announcement
  :: BS.ByteString -> Either DecodeError NodeAnnouncement
decode_node_announcement :: ByteString -> Either DecodeError NodeAnnouncement
decode_node_announcement ByteString
b0 = do
  (sig, b1) <- ByteString -> Either DecodeError (Signature, ByteString)
signature ByteString
b0
  (f, b2)   <- u16_prefixed b1
  (ts, b3)  <- u32 b2
  (nid, b4) <- point b3
  (r, b5)   <- u8 b4
  (g, b6)   <- u8 b5
  (b, b7)   <- u8 b6
  (al, b8)  <- bytes 32 b7
  (as, b9)  <- u16_prefixed b8
  (known, unknown) <- addresses as
  ext <- extension b9
  pure NodeAnnouncement
    { na_signature         = sig
    , na_features          = BOLT9.parse f
    , na_timestamp         = ts
    , na_node_id           = nid
    , na_rgb_color         = RgbColor r g b
    , na_alias             = Alias al
    , na_addresses         = known
    , na_unknown_addresses = unknown
    , na_tlvs              = ext
    }

-- parse address descriptors, stopping at the first of an unknown type
addresses
  :: BS.ByteString -> Either DecodeError ([Address], BS.ByteString)
addresses :: ByteString -> Either DecodeError ([Address], ByteString)
addresses = [Address]
-> ByteString -> Either DecodeError ([Address], ByteString)
go []
  where
    go :: [Address]
-> ByteString -> Either DecodeError ([Address], ByteString)
go ![Address]
acc !ByteString
bs = case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
bs of
      Maybe (Word8, ByteString)
Nothing -> ([Address], ByteString)
-> Either DecodeError ([Address], ByteString)
forall a b. b -> Either a b
Right ([Address] -> [Address]
forall a. [a] -> [a]
reverse [Address]
acc, ByteString
BS.empty)
      Just (Word8
t, ByteString
r) -> case Word8
t of
        Word8
1 -> [Address]
-> Int
-> (ByteString -> Word16 -> Address)
-> ByteString
-> Either DecodeError ([Address], ByteString)
with_port [Address]
acc Int
4 (IPv4Addr -> Word16 -> Address
AddrIPv4 (IPv4Addr -> Word16 -> Address)
-> (ByteString -> IPv4Addr) -> ByteString -> Word16 -> Address
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> IPv4Addr
IPv4Addr) ByteString
r
        Word8
2 -> [Address]
-> Int
-> (ByteString -> Word16 -> Address)
-> ByteString
-> Either DecodeError ([Address], ByteString)
with_port [Address]
acc Int
16 (IPv6Addr -> Word16 -> Address
AddrIPv6 (IPv6Addr -> Word16 -> Address)
-> (ByteString -> IPv6Addr) -> ByteString -> Word16 -> Address
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> IPv6Addr
IPv6Addr) ByteString
r
        Word8
3 -> do
          (a, r1) <- Int -> ByteString -> Either DecodeError (ByteString, ByteString)
bytes Int
12 ByteString
r
          go (AddrTorV2 (TorV2Addr a) : acc) r1
        Word8
4 -> [Address]
-> Int
-> (ByteString -> Word16 -> Address)
-> ByteString
-> Either DecodeError ([Address], ByteString)
with_port [Address]
acc Int
35 (TorV3Addr -> Word16 -> Address
AddrTorV3 (TorV3Addr -> Word16 -> Address)
-> (ByteString -> TorV3Addr) -> ByteString -> Word16 -> Address
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> TorV3Addr
TorV3Addr) ByteString
r
        Word8
5 -> do
          (n, r1) <- ByteString -> Either DecodeError (Word8, ByteString)
u8 ByteString
r
          (h, r2) <- bytes (fromIntegral n) r1
          (p, r3) <- u16 r2
          go (AddrDNS (Hostname h) p : acc) r3
        Word8
_ -> ([Address], ByteString)
-> Either DecodeError ([Address], ByteString)
forall a b. b -> Either a b
Right ([Address] -> [Address]
forall a. [a] -> [a]
reverse [Address]
acc, ByteString
bs)

    with_port :: [Address]
-> Int
-> (ByteString -> Word16 -> Address)
-> ByteString
-> Either DecodeError ([Address], ByteString)
with_port [Address]
acc Int
n ByteString -> Word16 -> Address
mk ByteString
r = do
      (a, r1) <- Int -> ByteString -> Either DecodeError (ByteString, ByteString)
bytes Int
n ByteString
r
      (p, r2) <- u16 r1
      go (mk a p : acc) r2

-- channel_update -------------------------------------------------------------

-- | Encode a t'ChannelUpdate' payload.
encode_channel_update :: ChannelUpdate -> BS.ByteString
encode_channel_update :: ChannelUpdate -> ByteString
encode_channel_update ChannelUpdate
m =
  let MessageFlags Word8
mf = ChannelUpdate -> MessageFlags
cu_message_flags ChannelUpdate
m
      ChannelFlags Word8
cf = ChannelUpdate -> ChannelFlags
cu_channel_flags ChannelUpdate
m
  in  [ByteString] -> ByteString
forall a. Monoid a => [a] -> a
mconcat
        [ Signature -> ByteString
BOLT1.un_signature (ChannelUpdate -> Signature
cu_signature ChannelUpdate
m)
        , ChainHash -> ByteString
BOLT1.un_chain_hash (ChannelUpdate -> ChainHash
cu_chain_hash ChannelUpdate
m)
        , ShortChannelId -> ByteString
BOLT1.encode_short_channel_id (ChannelUpdate -> ShortChannelId
cu_short_channel_id ChannelUpdate
m)
        , Word32 -> ByteString
BOLT1.encode_u32 (ChannelUpdate -> Word32
cu_timestamp ChannelUpdate
m)
        , [Word8] -> ByteString
BS.pack [Word8
mf, Word8
cf]
        , Word16 -> ByteString
BOLT1.encode_u16 (ChannelUpdate -> Word16
cu_cltv_expiry_delta ChannelUpdate
m)
        , MilliSatoshi -> ByteString
BOLT1.encode_milli_satoshi (ChannelUpdate -> MilliSatoshi
cu_htlc_minimum_msat ChannelUpdate
m)
        , Word32 -> ByteString
BOLT1.encode_u32 (ChannelUpdate -> Word32
cu_fee_base_msat ChannelUpdate
m)
        , Word32 -> ByteString
BOLT1.encode_u32 (ChannelUpdate -> Word32
cu_fee_proportional_millionths ChannelUpdate
m)
        , MilliSatoshi -> ByteString
BOLT1.encode_milli_satoshi (ChannelUpdate -> MilliSatoshi
cu_htlc_maximum_msat ChannelUpdate
m)
        , TlvStream -> ByteString
BOLT1.encode_tlv_stream (ChannelUpdate -> TlvStream
cu_tlvs ChannelUpdate
m)
        ]

-- | Decode a t'ChannelUpdate' payload.
--
--   @htlc_maximum_msat@ is always present; the @must_be_one@ bit of
--   @message_flags@ is kept but not interpreted.
decode_channel_update :: BS.ByteString -> Either DecodeError ChannelUpdate
decode_channel_update :: ByteString -> Either DecodeError ChannelUpdate
decode_channel_update ByteString
b0 = do
  (sig, b1)   <- ByteString -> Either DecodeError (Signature, ByteString)
signature ByteString
b0
  (ch, b2)    <- chain_hash b1
  (s, b3)     <- short_channel_id b2
  (ts, b4)    <- u32 b3
  (mf, b5)    <- u8 b4
  (cf, b6)    <- u8 b5
  (cltv, b7)  <- u16 b6
  (hmin, b8)  <- milli_satoshi b7
  (fb, b9)    <- u32 b8
  (fp, b10)   <- u32 b9
  (hmax, b11) <- milli_satoshi b10
  ext         <- extension b11
  pure ChannelUpdate
    { cu_signature                   = sig
    , cu_chain_hash                  = ch
    , cu_short_channel_id            = s
    , cu_timestamp                   = ts
    , cu_message_flags               = MessageFlags mf
    , cu_channel_flags               = ChannelFlags cf
    , cu_cltv_expiry_delta           = cltv
    , cu_htlc_minimum_msat           = hmin
    , cu_fee_base_msat               = fb
    , cu_fee_proportional_millionths = fp
    , cu_htlc_maximum_msat           = hmax
    , cu_tlvs                        = ext
    }

-- announcement_signatures ----------------------------------------------------

-- | Encode an t'AnnouncementSignatures' payload.
encode_announcement_signatures :: AnnouncementSignatures -> BS.ByteString
encode_announcement_signatures :: AnnouncementSignatures -> ByteString
encode_announcement_signatures AnnouncementSignatures
m = [ByteString] -> ByteString
forall a. Monoid a => [a] -> a
mconcat
  [ ChannelId -> ByteString
BOLT1.un_channel_id (AnnouncementSignatures -> ChannelId
as_channel_id AnnouncementSignatures
m)
  , ShortChannelId -> ByteString
BOLT1.encode_short_channel_id (AnnouncementSignatures -> ShortChannelId
as_short_channel_id AnnouncementSignatures
m)
  , Signature -> ByteString
BOLT1.un_signature (AnnouncementSignatures -> Signature
as_node_signature AnnouncementSignatures
m)
  , Signature -> ByteString
BOLT1.un_signature (AnnouncementSignatures -> Signature
as_bitcoin_signature AnnouncementSignatures
m)
  , TlvStream -> ByteString
BOLT1.encode_tlv_stream (AnnouncementSignatures -> TlvStream
as_tlvs AnnouncementSignatures
m)
  ]

-- | Decode an t'AnnouncementSignatures' payload.
decode_announcement_signatures
  :: BS.ByteString -> Either DecodeError AnnouncementSignatures
decode_announcement_signatures :: ByteString -> Either DecodeError AnnouncementSignatures
decode_announcement_signatures ByteString
b0 = do
  (cid, b1) <- Maybe (ChannelId, ByteString)
-> Either DecodeError (ChannelId, ByteString)
forall a. Maybe a -> Either DecodeError a
need (ByteString -> Maybe (ChannelId, ByteString)
BOLT1.decode_channel_id ByteString
b0)
  (s, b2)   <- short_channel_id b1
  (ns, b3)  <- signature b2
  (bs, b4)  <- signature b3
  ext       <- extension b4
  pure (AnnouncementSignatures cid s ns bs ext)

-- query_short_channel_ids ----------------------------------------------------

-- | Encode a t'QueryShortChannelIds' payload. Fails if the short channel
--   ids exceed the u16 length limit (8191 of them), if the query flags
--   don't number one per short channel id, or if 'qsci_tlvs' holds a
--   record of type 1.
encode_query_short_channel_ids
  :: QueryShortChannelIds -> Either EncodeError BS.ByteString
encode_query_short_channel_ids :: QueryShortChannelIds -> Either EncodeError ByteString
encode_query_short_channel_ids QueryShortChannelIds
m = do
  let scids :: [ShortChannelId]
scids = QueryShortChannelIds -> [ShortChannelId]
qsci_short_channel_ids QueryShortChannelIds
m
  ids <- ByteString -> Either EncodeError ByteString
prefixed ([ShortChannelId] -> ByteString
encode_short_ids [ShortChannelId]
scids)
  flags <- case qsci_query_flags m of
    Maybe [QueryFlags]
Nothing -> [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    Just [QueryFlags]
fs
      | [QueryFlags] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [QueryFlags]
fs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= [ShortChannelId] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ShortChannelId]
scids -> EncodeError -> Either EncodeError [TlvRecord]
forall a b. a -> Either a b
Left EncodeError
EncodeCountMismatch
      | Bool
otherwise -> [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
          [Word64 -> ByteString -> TlvRecord
TlvRecord Word64
1 (Word8 -> ByteString -> ByteString
BS.cons Word8
0 ((QueryFlags -> ByteString) -> [QueryFlags] -> ByteString
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(QueryFlags Word64
w) ->
                                       Word64 -> ByteString
BOLT1.encode_bigsize Word64
w) [QueryFlags]
fs))]
  t <- merge [1] flags (qsci_tlvs m)
  pure (BOLT1.un_chain_hash (qsci_chain_hash m) <> ids <> t)

-- | Decode a t'QueryShortChannelIds' payload.
--
--   Fails on an unknown encoding type (including the deprecated zlib
--   encoding), on @encoded_short_ids@ that isn't a whole number of short
--   channel ids, and on query flags that don't number one per short
--   channel id.
--
--   >>> let zlib = BS.replicate 32 0 <> "\NUL\STX\SOHx"
--   >>> decode_query_short_channel_ids zlib
--   Left (DecodeUnknownEncoding 1)
decode_query_short_channel_ids
  :: BS.ByteString -> Either DecodeError QueryShortChannelIds
decode_query_short_channel_ids :: ByteString -> Either DecodeError QueryShortChannelIds
decode_query_short_channel_ids ByteString
b0 = do
  (ch, b1)  <- ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash ByteString
b0
  (ids, b2) <- u16_prefixed b1
  scids     <- short_ids ids
  s         <- tlvs [1] b2
  flags     <- traverse (query_flags_value (length scids))
                 (BOLT1.lookup_tlv 1 s)
  pure QueryShortChannelIds
    { qsci_chain_hash        = ch
    , qsci_short_channel_ids = scids
    , qsci_query_flags       = flags
    , qsci_tlvs              = BOLT1.filter_tlv_stream (/= 1) s
    }

query_flags_value :: Int -> BS.ByteString -> Either DecodeError [QueryFlags]
query_flags_value :: Int -> ByteString -> Either DecodeError [QueryFlags]
query_flags_value Int
n ByteString
v = case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
v of
  Maybe (Word8, ByteString)
Nothing -> DecodeError -> Either DecodeError [QueryFlags]
forall a b. a -> Either a b
Left (Word64 -> DecodeError
DecodeInvalidTlvValue Word64
1)
  Just (Word8
0, ByteString
r) -> do
    fs <- ByteString -> Either DecodeError [Word64]
bigsizes ByteString
r
    if length fs /= n
      then Left DecodeCountMismatch
      else Right (map QueryFlags fs)
  Just (Word8
e, ByteString
_) -> DecodeError -> Either DecodeError [QueryFlags]
forall a b. a -> Either a b
Left (Word8 -> DecodeError
DecodeUnknownEncoding Word8
e)
  where
    bigsizes :: ByteString -> Either DecodeError [Word64]
bigsizes !ByteString
r
      | ByteString -> Bool
BS.null ByteString
r = [Word64] -> Either DecodeError [Word64]
forall a b. b -> Either a b
Right []
      | Bool
otherwise = case ByteString -> Maybe (Word64, ByteString)
BOLT1.decode_bigsize ByteString
r of
          Maybe (Word64, ByteString)
Nothing      -> DecodeError -> Either DecodeError [Word64]
forall a b. a -> Either a b
Left (Word64 -> DecodeError
DecodeInvalidTlvValue Word64
1)
          Just (Word64
w, ByteString
r1) -> (Word64
w Word64 -> [Word64] -> [Word64]
forall a. a -> [a] -> [a]
:) ([Word64] -> [Word64])
-> Either DecodeError [Word64] -> Either DecodeError [Word64]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either DecodeError [Word64]
bigsizes ByteString
r1

-- reply_short_channel_ids_end ------------------------------------------------

-- | Encode a t'ReplyShortChannelIdsEnd' payload.
encode_reply_short_channel_ids_end
  :: ReplyShortChannelIdsEnd -> BS.ByteString
encode_reply_short_channel_ids_end :: ReplyShortChannelIdsEnd -> ByteString
encode_reply_short_channel_ids_end ReplyShortChannelIdsEnd
m = [ByteString] -> ByteString
forall a. Monoid a => [a] -> a
mconcat
  [ ChainHash -> ByteString
BOLT1.un_chain_hash (ReplyShortChannelIdsEnd -> ChainHash
rsce_chain_hash ReplyShortChannelIdsEnd
m)
  , Bool -> ByteString
encode_bool (ReplyShortChannelIdsEnd -> Bool
rsce_full_information ReplyShortChannelIdsEnd
m)
  , TlvStream -> ByteString
BOLT1.encode_tlv_stream (ReplyShortChannelIdsEnd -> TlvStream
rsce_tlvs ReplyShortChannelIdsEnd
m)
  ]

-- | Decode a t'ReplyShortChannelIdsEnd' payload.
--
--   >>> decode_reply_short_channel_ids_end (BS.replicate 32 0 <> "\STX")
--   Left DecodeInvalidBool
decode_reply_short_channel_ids_end
  :: BS.ByteString -> Either DecodeError ReplyShortChannelIdsEnd
decode_reply_short_channel_ids_end :: ByteString -> Either DecodeError ReplyShortChannelIdsEnd
decode_reply_short_channel_ids_end ByteString
b0 = do
  (ch, b1)   <- ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash ByteString
b0
  (full, b2) <- bool b1
  ext        <- extension b2
  pure (ReplyShortChannelIdsEnd ch full ext)

-- query_channel_range --------------------------------------------------------

-- | Encode a t'QueryChannelRange' payload. Fails if 'qcr_tlvs' holds a
--   record of type 1.
encode_query_channel_range
  :: QueryChannelRange -> Either EncodeError BS.ByteString
encode_query_channel_range :: QueryChannelRange -> Either EncodeError ByteString
encode_query_channel_range QueryChannelRange
m = do
  let opt :: [TlvRecord]
opt = case QueryChannelRange -> Maybe QueryOption
qcr_query_option QueryChannelRange
m of
        Maybe QueryOption
Nothing              -> []
        Just (QueryOption Word64
w) -> [Word64 -> ByteString -> TlvRecord
TlvRecord Word64
1 (Word64 -> ByteString
BOLT1.encode_bigsize Word64
w)]
  t <- [Word64]
-> [TlvRecord] -> TlvStream -> Either EncodeError ByteString
merge [Word64
1] [TlvRecord]
opt (QueryChannelRange -> TlvStream
qcr_tlvs QueryChannelRange
m)
  pure $ mconcat
    [ BOLT1.un_chain_hash (qcr_chain_hash m)
    , BOLT1.encode_u32 (qcr_first_blocknum m)
    , BOLT1.encode_u32 (qcr_number_of_blocks m)
    , t
    ]

-- | Decode a t'QueryChannelRange' payload.
decode_query_channel_range
  :: BS.ByteString -> Either DecodeError QueryChannelRange
decode_query_channel_range :: ByteString -> Either DecodeError QueryChannelRange
decode_query_channel_range ByteString
b0 = do
  (ch, b1)    <- ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash ByteString
b0
  (first, b2) <- u32 b1
  (num, b3)   <- u32 b2
  s           <- tlvs [1] b3
  opt         <- traverse option (BOLT1.lookup_tlv 1 s)
  pure QueryChannelRange
    { qcr_chain_hash       = ch
    , qcr_first_blocknum   = first
    , qcr_number_of_blocks = num
    , qcr_query_option     = opt
    , qcr_tlvs             = BOLT1.filter_tlv_stream (/= 1) s
    }
  where
    option :: ByteString -> Either DecodeError QueryOption
option ByteString
v = case ByteString -> Maybe (Word64, ByteString)
BOLT1.decode_bigsize ByteString
v of
      Just (Word64
w, ByteString
r) | ByteString -> Bool
BS.null ByteString
r -> QueryOption -> Either DecodeError QueryOption
forall a b. b -> Either a b
Right (Word64 -> QueryOption
QueryOption Word64
w)
      Maybe (Word64, ByteString)
_ -> DecodeError -> Either DecodeError QueryOption
forall a b. a -> Either a b
Left (Word64 -> DecodeError
DecodeInvalidTlvValue Word64
1)

-- reply_channel_range --------------------------------------------------------

-- | Encode a t'ReplyChannelRange' payload. Fails if the short channel ids
--   exceed the u16 length limit (8191 of them), if the timestamps or
--   checksums don't number one per short channel id, or if 'rcr_tlvs'
--   holds a record of type 1 or 3.
encode_reply_channel_range
  :: ReplyChannelRange -> Either EncodeError BS.ByteString
encode_reply_channel_range :: ReplyChannelRange -> Either EncodeError ByteString
encode_reply_channel_range ReplyChannelRange
m = do
  let scids :: [ShortChannelId]
scids = ReplyChannelRange -> [ShortChannelId]
rcr_short_channel_ids ReplyChannelRange
m
      n :: Int
n = [ShortChannelId] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ShortChannelId]
scids
      count :: t a -> Either EncodeError ()
count t a
xs
        | t a -> Int
forall a. t a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length t a
xs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
n = EncodeError -> Either EncodeError ()
forall a b. a -> Either a b
Left EncodeError
EncodeCountMismatch
        | Bool
otherwise      = () -> Either EncodeError ()
forall a b. b -> Either a b
Right ()
  ids <- ByteString -> Either EncodeError ByteString
prefixed ([ShortChannelId] -> ByteString
encode_short_ids [ShortChannelId]
scids)
  ts <- case rcr_timestamps m of
    Maybe [ChannelUpdateTimestamps]
Nothing -> [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    Just [ChannelUpdateTimestamps]
xs -> do
      [ChannelUpdateTimestamps] -> Either EncodeError ()
forall {t :: * -> *} {a}.
Foldable t =>
t a -> Either EncodeError ()
count [ChannelUpdateTimestamps]
xs
      [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Word64 -> ByteString -> TlvRecord
TlvRecord Word64
1 (Word8 -> ByteString -> ByteString
BS.cons Word8
0 ((ChannelUpdateTimestamps -> ByteString)
-> [ChannelUpdateTimestamps] -> ByteString
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap
        (\(ChannelUpdateTimestamps Word32
a Word32
b) -> Word32 -> Word32 -> ByteString
pair Word32
a Word32
b) [ChannelUpdateTimestamps]
xs))]
  cs <- case rcr_checksums m of
    Maybe [ChannelUpdateChecksums]
Nothing -> [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    Just [ChannelUpdateChecksums]
xs -> do
      [ChannelUpdateChecksums] -> Either EncodeError ()
forall {t :: * -> *} {a}.
Foldable t =>
t a -> Either EncodeError ()
count [ChannelUpdateChecksums]
xs
      [TlvRecord] -> Either EncodeError [TlvRecord]
forall a. a -> Either EncodeError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Word64 -> ByteString -> TlvRecord
TlvRecord Word64
3 ((ChannelUpdateChecksums -> ByteString)
-> [ChannelUpdateChecksums] -> ByteString
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap
        (\(ChannelUpdateChecksums Word32
a Word32
b) -> Word32 -> Word32 -> ByteString
pair Word32
a Word32
b) [ChannelUpdateChecksums]
xs)]
  t <- merge [1, 3] (ts <> cs) (rcr_tlvs m)
  pure $ mconcat
    [ BOLT1.un_chain_hash (rcr_chain_hash m)
    , BOLT1.encode_u32 (rcr_first_blocknum m)
    , BOLT1.encode_u32 (rcr_number_of_blocks m)
    , encode_bool (rcr_sync_complete m)
    , ids
    , t
    ]
  where
    pair :: Word32 -> Word32 -> ByteString
pair Word32
a Word32
b = Word32 -> ByteString
BOLT1.encode_u32 Word32
a ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word32 -> ByteString
BOLT1.encode_u32 Word32
b

-- | Decode a t'ReplyChannelRange' payload.
--
--   Fails on an unknown encoding type (including the deprecated zlib
--   encoding), on @encoded_short_ids@ that isn't a whole number of short
--   channel ids, and on timestamps or checksums that don't number one
--   per short channel id.
decode_reply_channel_range
  :: BS.ByteString -> Either DecodeError ReplyChannelRange
decode_reply_channel_range :: ByteString -> Either DecodeError ReplyChannelRange
decode_reply_channel_range ByteString
b0 = do
  (ch, b1)    <- ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash ByteString
b0
  (first, b2) <- u32 b1
  (num, b3)   <- u32 b2
  (sync, b4)  <- bool b3
  (ids, b5)   <- u16_prefixed b4
  scids       <- short_ids ids
  s           <- tlvs [1, 3] b5
  let n = [ShortChannelId] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ShortChannelId]
scids
  ts <- traverse (timestamps n) (BOLT1.lookup_tlv 1 s)
  cs <- traverse (pairs 3 ChannelUpdateChecksums n) (BOLT1.lookup_tlv 3 s)
  pure ReplyChannelRange
    { rcr_chain_hash        = ch
    , rcr_first_blocknum    = first
    , rcr_number_of_blocks  = num
    , rcr_sync_complete     = sync
    , rcr_short_channel_ids = scids
    , rcr_timestamps        = ts
    , rcr_checksums         = cs
    , rcr_tlvs              =
        BOLT1.filter_tlv_stream (\Word64
t -> Word64
t Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word64
1 Bool -> Bool -> Bool
&& Word64
t Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word64
3) s
    }
  where
    timestamps :: Int -> ByteString -> Either DecodeError [ChannelUpdateTimestamps]
timestamps Int
n ByteString
v = case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
v of
      Maybe (Word8, ByteString)
Nothing     -> DecodeError -> Either DecodeError [ChannelUpdateTimestamps]
forall a b. a -> Either a b
Left (Word64 -> DecodeError
DecodeInvalidTlvValue Word64
1)
      Just (Word8
0, ByteString
r) -> Word64
-> (Word32 -> Word32 -> ChannelUpdateTimestamps)
-> Int
-> ByteString
-> Either DecodeError [ChannelUpdateTimestamps]
forall a.
Word64
-> (Word32 -> Word32 -> a)
-> Int
-> ByteString
-> Either DecodeError [a]
pairs Word64
1 Word32 -> Word32 -> ChannelUpdateTimestamps
ChannelUpdateTimestamps Int
n ByteString
r
      Just (Word8
e, ByteString
_) -> DecodeError -> Either DecodeError [ChannelUpdateTimestamps]
forall a b. a -> Either a b
Left (Word8 -> DecodeError
DecodeUnknownEncoding Word8
e)

-- decode an array of u32 pairs holding n elements
pairs
  :: Word64 -> (Word32 -> Word32 -> a) -> Int -> BS.ByteString
  -> Either DecodeError [a]
pairs :: forall a.
Word64
-> (Word32 -> Word32 -> a)
-> Int
-> ByteString
-> Either DecodeError [a]
pairs Word64
t Word32 -> Word32 -> a
mk Int
n ByteString
r
  | ByteString -> Int
BS.length ByteString
r Int -> Int -> Int
forall a. Integral a => a -> a -> a
`rem` Int
8 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0  = DecodeError -> Either DecodeError [a]
forall a b. a -> Either a b
Left (Word64 -> DecodeError
DecodeInvalidTlvValue Word64
t)
  | ByteString -> Int
BS.length ByteString
r Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` Int
8 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
n = DecodeError -> Either DecodeError [a]
forall a b. a -> Either a b
Left DecodeError
DecodeCountMismatch
  | Bool
otherwise                 = [a] -> Either DecodeError [a]
forall a b. b -> Either a b
Right (ByteString -> [a]
go ByteString
r)
  where
    go :: ByteString -> [a]
go !ByteString
bs = case ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32 ByteString
bs of
      Maybe (Word32, ByteString)
Nothing -> []
      Just (Word32
a, ByteString
r1) -> case ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32 ByteString
r1 of
        Maybe (Word32, ByteString)
Nothing      -> []
        Just (Word32
b, ByteString
r2) -> Word32 -> Word32 -> a
mk Word32
a Word32
b a -> [a] -> [a]
forall a. a -> [a] -> [a]
: ByteString -> [a]
go ByteString
r2

-- gossip_timestamp_filter ----------------------------------------------------

-- | Encode a t'GossipTimestampFilter' payload.
encode_gossip_timestamp_filter :: GossipTimestampFilter -> BS.ByteString
encode_gossip_timestamp_filter :: GossipTimestampFilter -> ByteString
encode_gossip_timestamp_filter GossipTimestampFilter
m = [ByteString] -> ByteString
forall a. Monoid a => [a] -> a
mconcat
  [ ChainHash -> ByteString
BOLT1.un_chain_hash (GossipTimestampFilter -> ChainHash
gtf_chain_hash GossipTimestampFilter
m)
  , Word32 -> ByteString
BOLT1.encode_u32 (GossipTimestampFilter -> Word32
gtf_first_timestamp GossipTimestampFilter
m)
  , Word32 -> ByteString
BOLT1.encode_u32 (GossipTimestampFilter -> Word32
gtf_timestamp_range GossipTimestampFilter
m)
  , TlvStream -> ByteString
BOLT1.encode_tlv_stream (GossipTimestampFilter -> TlvStream
gtf_tlvs GossipTimestampFilter
m)
  ]

-- | Decode a t'GossipTimestampFilter' payload.
decode_gossip_timestamp_filter
  :: BS.ByteString -> Either DecodeError GossipTimestampFilter
decode_gossip_timestamp_filter :: ByteString -> Either DecodeError GossipTimestampFilter
decode_gossip_timestamp_filter ByteString
b0 = do
  (ch, b1)    <- ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash ByteString
b0
  (first, b2) <- u32 b1
  (range, b3) <- u32 b2
  ext         <- extension b3
  pure (GossipTimestampFilter ch first range ext)

-- encoded short channel ids --------------------------------------------------

-- encoding type 0 (uncompressed), the only one allowed
encode_short_ids :: [ShortChannelId] -> BS.ByteString
encode_short_ids :: [ShortChannelId] -> ByteString
encode_short_ids = Word8 -> ByteString -> ByteString
BS.cons Word8
0 (ByteString -> ByteString)
-> ([ShortChannelId] -> ByteString)
-> [ShortChannelId]
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ShortChannelId -> ByteString) -> [ShortChannelId] -> ByteString
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap ShortChannelId -> ByteString
BOLT1.encode_short_channel_id

short_ids :: BS.ByteString -> Either DecodeError [ShortChannelId]
short_ids :: ByteString -> Either DecodeError [ShortChannelId]
short_ids ByteString
bs = case ByteString -> Maybe (Word8, ByteString)
BS.uncons ByteString
bs of
  Maybe (Word8, ByteString)
Nothing -> DecodeError -> Either DecodeError [ShortChannelId]
forall a b. a -> Either a b
Left DecodeError
DecodeInvalidShortChannelIds
  Just (Word8
0, ByteString
r)
    | ByteString -> Int
BS.length ByteString
r Int -> Int -> Int
forall a. Integral a => a -> a -> a
`rem` Int
8 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 -> [ShortChannelId] -> Either DecodeError [ShortChannelId]
forall a b. b -> Either a b
Right (ByteString -> [ShortChannelId]
go ByteString
r)
    | Bool
otherwise                -> DecodeError -> Either DecodeError [ShortChannelId]
forall a b. a -> Either a b
Left DecodeError
DecodeInvalidShortChannelIds
  Just (Word8
e, ByteString
_) -> DecodeError -> Either DecodeError [ShortChannelId]
forall a b. a -> Either a b
Left (Word8 -> DecodeError
DecodeUnknownEncoding Word8
e)
  where
    go :: ByteString -> [ShortChannelId]
go !ByteString
r = case ByteString -> Maybe (ShortChannelId, ByteString)
BOLT1.decode_short_channel_id ByteString
r of
      Maybe (ShortChannelId, ByteString)
Nothing      -> []
      Just (ShortChannelId
s, ByteString
r1) -> ShortChannelId
s ShortChannelId -> [ShortChannelId] -> [ShortChannelId]
forall a. a -> [a] -> [a]
: ByteString -> [ShortChannelId]
go ByteString
r1

-- helpers --------------------------------------------------------------------

need :: Maybe a -> Either DecodeError a
need :: forall a. Maybe a -> Either DecodeError a
need = Either DecodeError a
-> (a -> Either DecodeError a) -> Maybe a -> Either DecodeError a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (DecodeError -> Either DecodeError a
forall a b. a -> Either a b
Left DecodeError
DecodeInsufficientBytes) a -> Either DecodeError a
forall a b. b -> Either a b
Right
{-# INLINE need #-}

u8 :: BS.ByteString -> Either DecodeError (Word8, BS.ByteString)
u8 :: ByteString -> Either DecodeError (Word8, ByteString)
u8 = Maybe (Word8, ByteString) -> Either DecodeError (Word8, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (Word8, ByteString)
 -> Either DecodeError (Word8, ByteString))
-> (ByteString -> Maybe (Word8, ByteString))
-> ByteString
-> Either DecodeError (Word8, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (Word8, ByteString)
BS.uncons
{-# INLINE u8 #-}

u16 :: BS.ByteString -> Either DecodeError (Word16, BS.ByteString)
u16 :: ByteString -> Either DecodeError (Word16, ByteString)
u16 = Maybe (Word16, ByteString)
-> Either DecodeError (Word16, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (Word16, ByteString)
 -> Either DecodeError (Word16, ByteString))
-> (ByteString -> Maybe (Word16, ByteString))
-> ByteString
-> Either DecodeError (Word16, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (Word16, ByteString)
BOLT1.decode_u16
{-# INLINE u16 #-}

u32 :: BS.ByteString -> Either DecodeError (Word32, BS.ByteString)
u32 :: ByteString -> Either DecodeError (Word32, ByteString)
u32 = Maybe (Word32, ByteString)
-> Either DecodeError (Word32, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (Word32, ByteString)
 -> Either DecodeError (Word32, ByteString))
-> (ByteString -> Maybe (Word32, ByteString))
-> ByteString
-> Either DecodeError (Word32, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (Word32, ByteString)
BOLT1.decode_u32
{-# INLINE u32 #-}

bytes
  :: Int -> BS.ByteString
  -> Either DecodeError (BS.ByteString, BS.ByteString)
bytes :: Int -> ByteString -> Either DecodeError (ByteString, ByteString)
bytes Int
n ByteString
bs
  | ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
n = DecodeError -> Either DecodeError (ByteString, ByteString)
forall a b. a -> Either a b
Left DecodeError
DecodeInsufficientBytes
  | Bool
otherwise        = (ByteString, ByteString)
-> Either DecodeError (ByteString, ByteString)
forall a b. b -> Either a b
Right (Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
n ByteString
bs)
{-# INLINE bytes #-}

u16_prefixed
  :: BS.ByteString -> Either DecodeError (BS.ByteString, BS.ByteString)
u16_prefixed :: ByteString -> Either DecodeError (ByteString, ByteString)
u16_prefixed = Maybe (ByteString, ByteString)
-> Either DecodeError (ByteString, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (ByteString, ByteString)
 -> Either DecodeError (ByteString, ByteString))
-> (ByteString -> Maybe (ByteString, ByteString))
-> ByteString
-> Either DecodeError (ByteString, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (ByteString, ByteString)
BOLT1.decode_u16_prefixed
{-# INLINE u16_prefixed #-}

bool :: BS.ByteString -> Either DecodeError (Bool, BS.ByteString)
bool :: ByteString -> Either DecodeError (Bool, ByteString)
bool ByteString
bs = do
  (b, r) <- ByteString -> Either DecodeError (Word8, ByteString)
u8 ByteString
bs
  case b of
    Word8
0 -> (Bool, ByteString) -> Either DecodeError (Bool, ByteString)
forall a b. b -> Either a b
Right (Bool
False, ByteString
r)
    Word8
1 -> (Bool, ByteString) -> Either DecodeError (Bool, ByteString)
forall a b. b -> Either a b
Right (Bool
True, ByteString
r)
    Word8
_ -> DecodeError -> Either DecodeError (Bool, ByteString)
forall a b. a -> Either a b
Left DecodeError
DecodeInvalidBool

signature :: BS.ByteString -> Either DecodeError (Signature, BS.ByteString)
signature :: ByteString -> Either DecodeError (Signature, ByteString)
signature = Maybe (Signature, ByteString)
-> Either DecodeError (Signature, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (Signature, ByteString)
 -> Either DecodeError (Signature, ByteString))
-> (ByteString -> Maybe (Signature, ByteString))
-> ByteString
-> Either DecodeError (Signature, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (Signature, ByteString)
BOLT1.decode_signature
{-# INLINE signature #-}

chain_hash :: BS.ByteString -> Either DecodeError (ChainHash, BS.ByteString)
chain_hash :: ByteString -> Either DecodeError (ChainHash, ByteString)
chain_hash = Maybe (ChainHash, ByteString)
-> Either DecodeError (ChainHash, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (ChainHash, ByteString)
 -> Either DecodeError (ChainHash, ByteString))
-> (ByteString -> Maybe (ChainHash, ByteString))
-> ByteString
-> Either DecodeError (ChainHash, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (ChainHash, ByteString)
BOLT1.decode_chain_hash
{-# INLINE chain_hash #-}

short_channel_id
  :: BS.ByteString -> Either DecodeError (ShortChannelId, BS.ByteString)
short_channel_id :: ByteString -> Either DecodeError (ShortChannelId, ByteString)
short_channel_id = Maybe (ShortChannelId, ByteString)
-> Either DecodeError (ShortChannelId, ByteString)
forall a. Maybe a -> Either DecodeError a
need (Maybe (ShortChannelId, ByteString)
 -> Either DecodeError (ShortChannelId, ByteString))
-> (ByteString -> Maybe (ShortChannelId, ByteString))
-> ByteString
-> Either DecodeError (ShortChannelId, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Maybe (ShortChannelId, ByteString)
BOLT1.decode_short_channel_id
{-# INLINE short_channel_id #-}

point :: BS.ByteString -> Either DecodeError (Point, BS.ByteString)
point :: ByteString -> Either DecodeError (Point, ByteString)
point ByteString
bs = do
  (b, r) <- Int -> ByteString -> Either DecodeError (ByteString, ByteString)
bytes Int
33 ByteString
bs
  case BOLT1.point b of
    Maybe Point
Nothing -> DecodeError -> Either DecodeError (Point, ByteString)
forall a b. a -> Either a b
Left DecodeError
DecodeInvalidPoint
    Just Point
p  -> (Point, ByteString) -> Either DecodeError (Point, ByteString)
forall a b. b -> Either a b
Right (Point
p, ByteString
r)

milli_satoshi
  :: BS.ByteString -> Either DecodeError (MilliSatoshi, BS.ByteString)
milli_satoshi :: ByteString -> Either DecodeError (MilliSatoshi, ByteString)
milli_satoshi ByteString
bs = do
  (w, r) <- Maybe (Word64, ByteString)
-> Either DecodeError (Word64, ByteString)
forall a. Maybe a -> Either DecodeError a
need (ByteString -> Maybe (Word64, ByteString)
BOLT1.decode_u64 ByteString
bs)
  case BOLT1.milli_satoshi w of
    Maybe MilliSatoshi
Nothing -> DecodeError -> Either DecodeError (MilliSatoshi, ByteString)
forall a b. a -> Either a b
Left DecodeError
DecodeInvalidAmount
    Just MilliSatoshi
a  -> (MilliSatoshi, ByteString)
-> Either DecodeError (MilliSatoshi, ByteString)
forall a b. b -> Either a b
Right (MilliSatoshi
a, ByteString
r)

-- a TLV stream with the given known types
tlvs :: [Word64] -> BS.ByteString -> Either DecodeError TlvStream
tlvs :: [Word64] -> ByteString -> Either DecodeError TlvStream
tlvs [Word64]
known ByteString
bs = (TlvError -> Either DecodeError TlvStream)
-> (TlvStream -> Either DecodeError TlvStream)
-> Either TlvError TlvStream
-> Either DecodeError TlvStream
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (DecodeError -> Either DecodeError TlvStream
forall a b. a -> Either a b
Left (DecodeError -> Either DecodeError TlvStream)
-> (TlvError -> DecodeError)
-> TlvError
-> Either DecodeError TlvStream
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TlvError -> DecodeError
DecodeTlvError) TlvStream -> Either DecodeError TlvStream
forall a b. b -> Either a b
Right
  ((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) ByteString
bs)

-- an extension stream, in which no types are known
extension :: BS.ByteString -> Either DecodeError TlvStream
extension :: ByteString -> Either DecodeError TlvStream
extension = [Word64] -> ByteString -> Either DecodeError TlvStream
tlvs []
{-# INLINE extension #-}

prefixed :: BS.ByteString -> Either EncodeError BS.ByteString
prefixed :: ByteString -> Either EncodeError ByteString
prefixed ByteString
bs =
  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
EncodeLengthOverflow) ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (ByteString -> Maybe ByteString
BOLT1.encode_u16_prefixed ByteString
bs)
{-# INLINE prefixed #-}

encode_bool :: Bool -> BS.ByteString
encode_bool :: Bool -> ByteString
encode_bool Bool
b = Word8 -> ByteString
BS.singleton (if Bool
b then Word8
1 else Word8
0)
{-# INLINE encode_bool #-}

-- encode typed records together with the extra records of a @_tlvs@
-- field, which mustn't use any of the message's known types
merge
  :: [Word64] -> [TlvRecord] -> TlvStream -> Either EncodeError BS.ByteString
merge :: [Word64]
-> [TlvRecord] -> TlvStream -> Either EncodeError ByteString
merge [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
tlv_type) [TlvRecord]
rs = EncodeError -> Either EncodeError ByteString
forall a b. a -> Either a b
Left EncodeError
EncodeInvalidTlvs
  | Bool
otherwise =
      Either EncodeError ByteString
-> (TlvStream -> Either EncodeError ByteString)
-> Maybe TlvStream
-> 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
EncodeInvalidTlvs) (ByteString -> Either EncodeError ByteString
forall a b. b -> Either a b
Right (ByteString -> Either EncodeError ByteString)
-> (TlvStream -> ByteString)
-> TlvStream
-> Either EncodeError ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TlvStream -> ByteString
BOLT1.encode_tlv_stream)
      ([TlvRecord] -> Maybe TlvStream
BOLT1.tlv_stream ([TlvRecord]
typed [TlvRecord] -> [TlvRecord] -> [TlvRecord]
forall a. Semigroup a => a -> a -> a
<> [TlvRecord]
rs))
  where
    rs :: [TlvRecord]
rs = TlvStream -> [TlvRecord]
BOLT1.un_tlv_stream TlvStream
extra