bolt2

Lightning peer protocol, per BOLT #2 (docs.ppad.tech/bolt2).
git clone git://git.ppad.tech/bolt2.git
Log | Files | Refs | README | LICENSE

Codec.hs (50118B)


      1 {-# OPTIONS_HADDOCK hide #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 {-# LANGUAGE DeriveGeneric #-}
      4 
      5 -- |
      6 -- Module: Lightning.Protocol.BOLT2.Codec
      7 -- Copyright: (c) 2025 Jared Tobin
      8 -- License: MIT
      9 -- Maintainer: Jared Tobin <jared@ppad.tech>
     10 --
     11 -- Encoding and decoding of BOLT #2 messages.
     12 
     13 module Lightning.Protocol.BOLT2.Codec (
     14     EncodeError(..)
     15   , DecodeError(..)
     16 
     17   , encode_message
     18   , decode_message
     19 
     20   , encode_open_channel
     21   , decode_open_channel
     22   , encode_accept_channel
     23   , decode_accept_channel
     24   , encode_funding_created
     25   , decode_funding_created
     26   , encode_funding_signed
     27   , decode_funding_signed
     28   , encode_channel_ready
     29   , decode_channel_ready
     30 
     31   , encode_open_channel2
     32   , decode_open_channel2
     33   , encode_accept_channel2
     34   , decode_accept_channel2
     35   , encode_tx_add_input
     36   , decode_tx_add_input
     37   , encode_tx_add_output
     38   , decode_tx_add_output
     39   , encode_tx_remove_input
     40   , decode_tx_remove_input
     41   , encode_tx_remove_output
     42   , decode_tx_remove_output
     43   , encode_tx_complete
     44   , decode_tx_complete
     45   , encode_tx_signatures
     46   , decode_tx_signatures
     47   , encode_tx_init_rbf
     48   , decode_tx_init_rbf
     49   , encode_tx_ack_rbf
     50   , decode_tx_ack_rbf
     51   , encode_tx_abort
     52   , decode_tx_abort
     53 
     54   , encode_stfu
     55   , decode_stfu
     56 
     57   , encode_shutdown
     58   , decode_shutdown
     59   , encode_closing_complete
     60   , decode_closing_complete
     61   , encode_closing_sig
     62   , decode_closing_sig
     63   , encode_closing_signed
     64   , decode_closing_signed
     65 
     66   , encode_update_add_htlc
     67   , decode_update_add_htlc
     68   , encode_update_fulfill_htlc
     69   , decode_update_fulfill_htlc
     70   , encode_update_fail_htlc
     71   , decode_update_fail_htlc
     72   , encode_update_fail_malformed_htlc
     73   , decode_update_fail_malformed_htlc
     74   , encode_commitment_signed
     75   , decode_commitment_signed
     76   , encode_revoke_and_ack
     77   , decode_revoke_and_ack
     78   , encode_update_fee
     79   , decode_update_fee
     80 
     81   , encode_channel_reestablish
     82   , decode_channel_reestablish
     83   ) where
     84 
     85 import Bitcoin.Prim.Tx (TxId, mk_txid, un_txid)
     86 import Control.DeepSeq (NFData)
     87 import qualified Data.ByteString as BS
     88 import qualified Data.ByteString.Unsafe as BU
     89 import Data.Int (Int64)
     90 import Data.Word (Word8, Word16, Word32, Word64)
     91 import GHC.Generics (Generic)
     92 import qualified Lightning.Protocol.BOLT1 as BOLT1
     93 import Lightning.Protocol.BOLT1
     94   ( ChannelId, Signature, Point, TlvRecord(..), TlvStream, TlvError )
     95 import qualified Lightning.Protocol.BOLT9 as BOLT9
     96 import Lightning.Protocol.BOLT2.Messages
     97 import Lightning.Protocol.BOLT2.Types
     98 
     99 -- errors ---------------------------------------------------------------------
    100 
    101 -- | Why a message failed to encode.
    102 data EncodeError
    103   = EncodeLengthOverflow
    104     -- ^ a length-prefixed field or a counted list exceeds 65535
    105   | EncodeInvalidTlvs
    106     -- ^ a @_tlvs@ field contains a record of a type the message knows
    107   | EncodeMessageTooLarge
    108     -- ^ the message (type and payload) exceeds 65535 bytes
    109   deriving (Eq, Show, Generic)
    110 
    111 instance NFData EncodeError
    112 
    113 -- | Why a message failed to decode.
    114 data DecodeError
    115   = DecodeInsufficientBytes
    116     -- ^ the input ended before a field did
    117   | DecodeInvalidPoint
    118     -- ^ a point lacks a compressed-encoding prefix
    119   | DecodeInvalidAmount
    120     -- ^ an amount exceeds 21 million BTC
    121   | DecodeInvalidInitiator
    122     -- ^ the @initiator@ byte of @stfu@ is neither 0 nor 1
    123   | DecodeTlvError !TlvError
    124     -- ^ the message's TLV stream is malformed, or has an unknown even
    125     --   type
    126   | DecodeInvalidTlvValue !Word64
    127     -- ^ a known TLV record (of the given type) has a malformed value
    128   | DecodeUnknownEvenType !Word16
    129     -- ^ a message type that BOLT #2 doesn't define (even)
    130   | DecodeUnknownOddType !Word16
    131     -- ^ a message type that BOLT #2 doesn't define (odd)
    132   deriving (Eq, Show, Generic)
    133 
    134 instance NFData DecodeError
    135 
    136 -- parsing --------------------------------------------------------------------
    137 
    138 newtype Parser a = Parser
    139   { run_parser :: BS.ByteString -> Either DecodeError (a, BS.ByteString) }
    140 
    141 instance Functor Parser where
    142   fmap f (Parser p) = Parser $ \bs -> case p bs of
    143     Left e        -> Left e
    144     Right (a, r)  -> Right (f a, r)
    145   {-# INLINE fmap #-}
    146 
    147 instance Applicative Parser where
    148   pure a = Parser $ \bs -> Right (a, bs)
    149   {-# INLINE pure #-}
    150   Parser pf <*> Parser pa = Parser $ \bs -> case pf bs of
    151     Left e       -> Left e
    152     Right (f, r) -> case pa r of
    153       Left e        -> Left e
    154       Right (a, r') -> Right (f a, r')
    155   {-# INLINE (<*>) #-}
    156 
    157 instance Monad Parser where
    158   Parser p >>= k = Parser $ \bs -> case p bs of
    159     Left e       -> Left e
    160     Right (a, r) -> run_parser (k a) r
    161   {-# INLINE (>>=) #-}
    162 
    163 -- run a parser whose last step consumes the remaining input
    164 parse :: Parser a -> BS.ByteString -> Either DecodeError a
    165 parse p bs = fmap fst (run_parser p bs)
    166 {-# INLINE parse #-}
    167 
    168 failure :: DecodeError -> Parser a
    169 failure e = Parser $ \_ -> Left e
    170 {-# INLINE failure #-}
    171 
    172 -- lift a bolt1 field decoder, whose only failure is truncation
    173 field :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> Parser a
    174 field f = Parser $ \bs -> case f bs of
    175   Nothing -> Left DecodeInsufficientBytes
    176   Just r  -> Right r
    177 {-# INLINE field #-}
    178 
    179 bytes :: Int -> Parser BS.ByteString
    180 bytes n = Parser $ \bs ->
    181   if BS.length bs < n
    182     then Left DecodeInsufficientBytes
    183     else Right (BU.unsafeTake n bs, BU.unsafeDrop n bs)
    184 {-# INLINE bytes #-}
    185 
    186 -- a fixed-size field whose constructor checks only the length
    187 sized :: Int -> (BS.ByteString -> Maybe a) -> Parser a
    188 sized n f = do
    189   b <- bytes n
    190   maybe (failure DecodeInsufficientBytes) pure (f b)
    191 {-# INLINE sized #-}
    192 
    193 u8 :: Parser Word8
    194 u8 = Parser $ \bs -> case BS.uncons bs of
    195   Nothing -> Left DecodeInsufficientBytes
    196   Just r  -> Right r
    197 {-# INLINE u8 #-}
    198 
    199 u16 :: Parser Word16
    200 u16 = field BOLT1.decode_u16
    201 {-# INLINE u16 #-}
    202 
    203 u32 :: Parser Word32
    204 u32 = field BOLT1.decode_u32
    205 {-# INLINE u32 #-}
    206 
    207 u64 :: Parser Word64
    208 u64 = field BOLT1.decode_u64
    209 {-# INLINE u64 #-}
    210 
    211 chain_hash :: Parser BOLT1.ChainHash
    212 chain_hash = field BOLT1.decode_chain_hash
    213 {-# INLINE chain_hash #-}
    214 
    215 channel_id :: Parser ChannelId
    216 channel_id = field BOLT1.decode_channel_id
    217 {-# INLINE channel_id #-}
    218 
    219 signature :: Parser Signature
    220 signature = field BOLT1.decode_signature
    221 {-# INLINE signature #-}
    222 
    223 payment_hash :: Parser BOLT1.PaymentHash
    224 payment_hash = field BOLT1.decode_payment_hash
    225 {-# INLINE payment_hash #-}
    226 
    227 payment_preimage :: Parser BOLT1.PaymentPreimage
    228 payment_preimage = field BOLT1.decode_payment_preimage
    229 {-# INLINE payment_preimage #-}
    230 
    231 per_commitment_secret :: Parser BOLT1.PerCommitmentSecret
    232 per_commitment_secret = field BOLT1.decode_per_commitment_secret
    233 {-# INLINE per_commitment_secret #-}
    234 
    235 point :: Parser Point
    236 point = do
    237   b <- bytes 33
    238   maybe (failure DecodeInvalidPoint) pure (BOLT1.point b)
    239 {-# INLINE point #-}
    240 
    241 satoshi :: Parser BOLT1.Satoshi
    242 satoshi = do
    243   w <- u64
    244   maybe (failure DecodeInvalidAmount) pure (BOLT1.satoshi w)
    245 {-# INLINE satoshi #-}
    246 
    247 milli_satoshi :: Parser BOLT1.MilliSatoshi
    248 milli_satoshi = do
    249   w <- u64
    250   maybe (failure DecodeInvalidAmount) pure (BOLT1.milli_satoshi w)
    251 {-# INLINE milli_satoshi #-}
    252 
    253 txid :: Parser TxId
    254 txid = sized 32 mk_txid
    255 {-# INLINE txid #-}
    256 
    257 htlc_id :: Parser HtlcId
    258 htlc_id = fmap HtlcId u64
    259 {-# INLINE htlc_id #-}
    260 
    261 serial_id :: Parser SerialId
    262 serial_id = fmap SerialId u64
    263 {-# INLINE serial_id #-}
    264 
    265 prefixed :: Parser BS.ByteString
    266 prefixed = field BOLT1.decode_u16_prefixed
    267 {-# INLINE prefixed #-}
    268 
    269 script :: Parser ScriptPubKey
    270 script = do
    271   b <- prefixed
    272   maybe (failure DecodeInsufficientBytes) pure (script_pubkey b)
    273 {-# INLINE script #-}
    274 
    275 -- n items, each parsed by p
    276 count :: Int -> Parser a -> Parser [a]
    277 count n0 p = go n0 []
    278   where
    279     go !n !acc
    280       | n <= 0    = pure (reverse acc)
    281       | otherwise = p >>= \a -> go (n - 1) (a : acc)
    282 {-# INLINE count #-}
    283 
    284 -- the TLV stream occupying the rest of the payload, given the message's
    285 -- known types
    286 tlvs :: [Word64] -> Parser TlvStream
    287 tlvs known = Parser $ \bs ->
    288   case BOLT1.decode_tlv_stream (`elem` known) bs of
    289     Left e  -> Left (DecodeTlvError e)
    290     Right s -> Right (s, BS.empty)
    291 {-# INLINE tlvs #-}
    292 
    293 -- the unknown records of a stream
    294 unknown :: [Word64] -> TlvStream -> TlvStream
    295 unknown known = BOLT1.filter_tlv_stream (`notElem` known)
    296 {-# INLINE unknown #-}
    297 
    298 -- the typed value of a known record, if present
    299 record :: Word64 -> (BS.ByteString -> Maybe a) -> TlvStream -> Parser (Maybe a)
    300 record t f s = case BOLT1.lookup_tlv t s of
    301   Nothing -> pure Nothing
    302   Just v  -> maybe (failure (DecodeInvalidTlvValue t)) (pure . Just) (f v)
    303 {-# INLINE record #-}
    304 
    305 -- whether a known record with an empty value is present
    306 flag :: Word64 -> TlvStream -> Parser Bool
    307 flag t s = fmap (maybe False (const True)) (record t empty_value s)
    308   where
    309     empty_value v
    310       | BS.null v = Just ()
    311       | otherwise = Nothing
    312 {-# INLINE flag #-}
    313 
    314 -- TLV values -----------------------------------------------------------------
    315 
    316 -- run a field decoder over a whole TLV value
    317 whole :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString
    318       -> Maybe a
    319 whole f v = case f v of
    320   Just (a, r) | BS.null r -> Just a
    321   _ -> Nothing
    322 {-# INLINE whole #-}
    323 
    324 tlv_point :: BS.ByteString -> Maybe Point
    325 tlv_point v
    326   | BS.length v == 33 = BOLT1.point v
    327   | otherwise         = Nothing
    328 
    329 tlv_s64 :: BS.ByteString -> Maybe Int64
    330 tlv_s64 = whole BOLT1.decode_s64
    331 
    332 tlv_fee_range :: BS.ByteString -> Maybe FeeRange
    333 tlv_fee_range v = do
    334   (lo, r0) <- BOLT1.decode_satoshi v
    335   hi <- whole BOLT1.decode_satoshi r0
    336   pure (FeeRange lo hi)
    337 
    338 tlv_next_funding :: BS.ByteString -> Maybe NextFunding
    339 tlv_next_funding v
    340   | BS.length v == 33 = do
    341       t <- mk_txid (BU.unsafeTake 32 v)
    342       pure (NextFunding t (BU.unsafeIndex v 32))
    343   | otherwise = Nothing
    344 
    345 -- encoding -------------------------------------------------------------------
    346 
    347 u16_prefixed :: BS.ByteString -> Either EncodeError BS.ByteString
    348 u16_prefixed bs = maybe (Left EncodeLengthOverflow) Right
    349   (BOLT1.encode_u16_prefixed bs)
    350 {-# INLINE u16_prefixed #-}
    351 
    352 -- scripts are bounded, so their prefix can't overflow
    353 script_bytes :: ScriptPubKey -> BS.ByteString
    354 script_bytes s =
    355   let !b = un_script_pubkey s
    356   in  BOLT1.encode_u16 (fromIntegral (BS.length b)) <> b
    357 {-# INLINE script_bytes #-}
    358 
    359 count_prefix :: [a] -> Either EncodeError BS.ByteString
    360 count_prefix xs
    361   | n > 65535 = Left EncodeLengthOverflow
    362   | otherwise = Right (BOLT1.encode_u16 (fromIntegral n))
    363   where
    364     !n = length xs
    365 {-# INLINE count_prefix #-}
    366 
    367 txid_bytes :: TxId -> BS.ByteString
    368 txid_bytes = un_txid
    369 {-# INLINE txid_bytes #-}
    370 
    371 word8 :: Word8 -> BS.ByteString
    372 word8 = BS.singleton
    373 {-# INLINE word8 #-}
    374 
    375 -- encode a message's TLV stream: its typed records plus the unknown
    376 -- ones, which mustn't use a known type
    377 encode_tlvs
    378   :: [Word64] -> [TlvRecord] -> TlvStream -> Either EncodeError BS.ByteString
    379 encode_tlvs known recs extra
    380   | any ((`elem` known) . tlv_type) others = Left EncodeInvalidTlvs
    381   | otherwise = case BOLT1.tlv_stream (recs <> others) of
    382       Nothing -> Left EncodeInvalidTlvs
    383       Just s  -> Right (BOLT1.encode_tlv_stream s)
    384   where
    385     others = BOLT1.un_tlv_stream extra
    386 {-# INLINE encode_tlvs #-}
    387 
    388 opt :: Word64 -> (a -> BS.ByteString) -> Maybe a -> [TlvRecord]
    389 opt t f = maybe [] (\a -> [TlvRecord t (f a)])
    390 {-# INLINE opt #-}
    391 
    392 opt_flag :: Word64 -> Bool -> [TlvRecord]
    393 opt_flag t b = if b then [TlvRecord t BS.empty] else []
    394 {-# INLINE opt_flag #-}
    395 
    396 fee_range_bytes :: FeeRange -> BS.ByteString
    397 fee_range_bytes (FeeRange lo hi) =
    398   BOLT1.encode_satoshi lo <> BOLT1.encode_satoshi hi
    399 
    400 next_funding_bytes :: NextFunding -> BS.ByteString
    401 next_funding_bytes (NextFunding t f) = txid_bytes t <> word8 f
    402 
    403 -- messages -------------------------------------------------------------------
    404 
    405 -- | Encode a BOLT #2 message, including its type. Fails if a field
    406 --   can't be encoded or the result exceeds 65535 bytes.
    407 --
    408 --   >>> let stfu = Stfu cid True BOLT1.empty_tlv_stream
    409 --   >>> fmap BS.length (encode_message (MsgStfu stfu))
    410 --   Right 35
    411 encode_message :: Message -> Either EncodeError BS.ByteString
    412 encode_message m = do
    413   payload <- case m of
    414     MsgOpenChannel a             -> encode_open_channel a
    415     MsgAcceptChannel a           -> encode_accept_channel a
    416     MsgFundingCreated a          -> Right (encode_funding_created a)
    417     MsgFundingSigned a           -> Right (encode_funding_signed a)
    418     MsgChannelReady a            -> encode_channel_ready a
    419     MsgOpenChannel2 a            -> encode_open_channel2 a
    420     MsgAcceptChannel2 a          -> encode_accept_channel2 a
    421     MsgTxAddInput a              -> encode_tx_add_input a
    422     MsgTxAddOutput a             -> Right (encode_tx_add_output a)
    423     MsgTxRemoveInput a           -> Right (encode_tx_remove_input a)
    424     MsgTxRemoveOutput a          -> Right (encode_tx_remove_output a)
    425     MsgTxComplete a              -> Right (encode_tx_complete a)
    426     MsgTxSignatures a            -> encode_tx_signatures a
    427     MsgTxInitRbf a               -> encode_tx_init_rbf a
    428     MsgTxAckRbf a                -> encode_tx_ack_rbf a
    429     MsgTxAbort a                 -> encode_tx_abort a
    430     MsgStfu a                    -> Right (encode_stfu a)
    431     MsgShutdown a                -> Right (encode_shutdown a)
    432     MsgClosingComplete a         -> encode_closing_complete a
    433     MsgClosingSig a              -> encode_closing_sig a
    434     MsgClosingSigned a           -> encode_closing_signed a
    435     MsgUpdateAddHtlc a           -> encode_update_add_htlc a
    436     MsgUpdateFulfillHtlc a       -> encode_update_fulfill_htlc a
    437     MsgUpdateFailHtlc a          -> encode_update_fail_htlc a
    438     MsgUpdateFailMalformedHtlc a ->
    439       Right (encode_update_fail_malformed_htlc a)
    440     MsgCommitmentSigned a        -> encode_commitment_signed a
    441     MsgRevokeAndAck a            -> Right (encode_revoke_and_ack a)
    442     MsgUpdateFee a               -> Right (encode_update_fee a)
    443     MsgChannelReestablish a      -> encode_channel_reestablish a
    444   case BOLT1.encode_envelope (message_type m) payload of
    445     Left _  -> Left EncodeMessageTooLarge
    446     Right w -> Right w
    447 
    448 -- | Decode a BOLT #2 message, including its type.
    449 --
    450 --   A type that BOLT #2 doesn't define (including the splicing
    451 --   messages, which this library doesn't implement) yields
    452 --   'DecodeUnknownEvenType' or 'DecodeUnknownOddType'.
    453 --
    454 --   >>> let wire = "\x00\x02" <> BS.replicate 32 0xab <> "\x01"
    455 --   >>> fmap message_type (decode_message wire)
    456 --   Right 2
    457 --   >>> decode_message "\x00\x50"
    458 --   Left (DecodeUnknownEvenType 80)
    459 decode_message :: BS.ByteString -> Either DecodeError Message
    460 decode_message bs = do
    461   (t, payload) <- case BOLT1.decode_envelope bs of
    462     Left _  -> Left DecodeInsufficientBytes
    463     Right r -> Right r
    464   case t of
    465     32  -> MsgOpenChannel <$> decode_open_channel payload
    466     33  -> MsgAcceptChannel <$> decode_accept_channel payload
    467     34  -> MsgFundingCreated <$> decode_funding_created payload
    468     35  -> MsgFundingSigned <$> decode_funding_signed payload
    469     36  -> MsgChannelReady <$> decode_channel_ready payload
    470     64  -> MsgOpenChannel2 <$> decode_open_channel2 payload
    471     65  -> MsgAcceptChannel2 <$> decode_accept_channel2 payload
    472     66  -> MsgTxAddInput <$> decode_tx_add_input payload
    473     67  -> MsgTxAddOutput <$> decode_tx_add_output payload
    474     68  -> MsgTxRemoveInput <$> decode_tx_remove_input payload
    475     69  -> MsgTxRemoveOutput <$> decode_tx_remove_output payload
    476     70  -> MsgTxComplete <$> decode_tx_complete payload
    477     71  -> MsgTxSignatures <$> decode_tx_signatures payload
    478     72  -> MsgTxInitRbf <$> decode_tx_init_rbf payload
    479     73  -> MsgTxAckRbf <$> decode_tx_ack_rbf payload
    480     74  -> MsgTxAbort <$> decode_tx_abort payload
    481     2   -> MsgStfu <$> decode_stfu payload
    482     38  -> MsgShutdown <$> decode_shutdown payload
    483     40  -> MsgClosingComplete <$> decode_closing_complete payload
    484     41  -> MsgClosingSig <$> decode_closing_sig payload
    485     39  -> MsgClosingSigned <$> decode_closing_signed payload
    486     128 -> MsgUpdateAddHtlc <$> decode_update_add_htlc payload
    487     130 -> MsgUpdateFulfillHtlc <$> decode_update_fulfill_htlc payload
    488     131 -> MsgUpdateFailHtlc <$> decode_update_fail_htlc payload
    489     135 -> MsgUpdateFailMalformedHtlc <$>
    490              decode_update_fail_malformed_htlc payload
    491     132 -> MsgCommitmentSigned <$> decode_commitment_signed payload
    492     133 -> MsgRevokeAndAck <$> decode_revoke_and_ack payload
    493     134 -> MsgUpdateFee <$> decode_update_fee payload
    494     136 -> MsgChannelReestablish <$> decode_channel_reestablish payload
    495     _ | even t    -> Left (DecodeUnknownEvenType t)
    496       | otherwise -> Left (DecodeUnknownOddType t)
    497 
    498 -- open_channel ---------------------------------------------------------------
    499 
    500 open_channel_known :: [Word64]
    501 open_channel_known = [0, 1]
    502 
    503 -- | Encode an t'OpenChannel' payload.
    504 encode_open_channel :: OpenChannel -> Either EncodeError BS.ByteString
    505 encode_open_channel m = do
    506   ts <- encode_tlvs open_channel_known
    507     (  opt 0 un_script_pubkey (open_channel_upfront_shutdown_script m)
    508     <> opt 1 BOLT9.render (open_channel_channel_type m) )
    509     (open_channel_tlvs m)
    510   pure $ mconcat [
    511       BOLT1.un_chain_hash (open_channel_chain_hash m)
    512     , BOLT1.un_channel_id (open_channel_temporary_channel_id m)
    513     , BOLT1.encode_satoshi (open_channel_funding_satoshis m)
    514     , BOLT1.encode_milli_satoshi (open_channel_push_msat m)
    515     , BOLT1.encode_satoshi (open_channel_dust_limit_satoshis m)
    516     , BOLT1.encode_u64 (open_channel_max_htlc_value_in_flight_msat m)
    517     , BOLT1.encode_satoshi (open_channel_channel_reserve_satoshis m)
    518     , BOLT1.encode_milli_satoshi (open_channel_htlc_minimum_msat m)
    519     , BOLT1.encode_u32 (open_channel_feerate_per_kw m)
    520     , BOLT1.encode_u16 (open_channel_to_self_delay m)
    521     , BOLT1.encode_u16 (open_channel_max_accepted_htlcs m)
    522     , BOLT1.un_point (open_channel_funding_pubkey m)
    523     , BOLT1.un_point (open_channel_revocation_basepoint m)
    524     , BOLT1.un_point (open_channel_payment_basepoint m)
    525     , BOLT1.un_point (open_channel_delayed_payment_basepoint m)
    526     , BOLT1.un_point (open_channel_htlc_basepoint m)
    527     , BOLT1.un_point (open_channel_first_per_commitment_point m)
    528     , word8 (open_channel_channel_flags m)
    529     , ts
    530     ]
    531 
    532 -- | Decode an t'OpenChannel' payload.
    533 decode_open_channel :: BS.ByteString -> Either DecodeError OpenChannel
    534 decode_open_channel = parse $ do
    535   ch    <- chain_hash
    536   tcid  <- channel_id
    537   fund  <- satoshi
    538   push  <- milli_satoshi
    539   dust  <- satoshi
    540   maxv  <- u64
    541   res   <- satoshi
    542   hmin  <- milli_satoshi
    543   fee   <- u32
    544   delay <- u16
    545   maxa  <- u16
    546   fpk   <- point
    547   rev   <- point
    548   pay   <- point
    549   del   <- point
    550   htlc  <- point
    551   pcp   <- point
    552   flags <- u8
    553   s     <- tlvs open_channel_known
    554   shut  <- record 0 script_pubkey s
    555   ctype <- record 1 (Just . BOLT9.parse) s
    556   pure OpenChannel {
    557       open_channel_chain_hash                    = ch
    558     , open_channel_temporary_channel_id          = tcid
    559     , open_channel_funding_satoshis              = fund
    560     , open_channel_push_msat                     = push
    561     , open_channel_dust_limit_satoshis           = dust
    562     , open_channel_max_htlc_value_in_flight_msat = maxv
    563     , open_channel_channel_reserve_satoshis      = res
    564     , open_channel_htlc_minimum_msat             = hmin
    565     , open_channel_feerate_per_kw                = fee
    566     , open_channel_to_self_delay                 = delay
    567     , open_channel_max_accepted_htlcs            = maxa
    568     , open_channel_funding_pubkey                = fpk
    569     , open_channel_revocation_basepoint          = rev
    570     , open_channel_payment_basepoint             = pay
    571     , open_channel_delayed_payment_basepoint     = del
    572     , open_channel_htlc_basepoint                = htlc
    573     , open_channel_first_per_commitment_point    = pcp
    574     , open_channel_channel_flags                 = flags
    575     , open_channel_upfront_shutdown_script       = shut
    576     , open_channel_channel_type                  = ctype
    577     , open_channel_tlvs                          = unknown open_channel_known s
    578     }
    579 
    580 -- accept_channel -------------------------------------------------------------
    581 
    582 accept_channel_known :: [Word64]
    583 accept_channel_known = [0, 1]
    584 
    585 -- | Encode an t'AcceptChannel' payload.
    586 encode_accept_channel :: AcceptChannel -> Either EncodeError BS.ByteString
    587 encode_accept_channel m = do
    588   ts <- encode_tlvs accept_channel_known
    589     (  opt 0 un_script_pubkey (accept_channel_upfront_shutdown_script m)
    590     <> opt 1 BOLT9.render (accept_channel_channel_type m) )
    591     (accept_channel_tlvs m)
    592   pure $ mconcat [
    593       BOLT1.un_channel_id (accept_channel_temporary_channel_id m)
    594     , BOLT1.encode_satoshi (accept_channel_dust_limit_satoshis m)
    595     , BOLT1.encode_u64 (accept_channel_max_htlc_value_in_flight_msat m)
    596     , BOLT1.encode_satoshi (accept_channel_channel_reserve_satoshis m)
    597     , BOLT1.encode_milli_satoshi (accept_channel_htlc_minimum_msat m)
    598     , BOLT1.encode_u32 (accept_channel_minimum_depth m)
    599     , BOLT1.encode_u16 (accept_channel_to_self_delay m)
    600     , BOLT1.encode_u16 (accept_channel_max_accepted_htlcs m)
    601     , BOLT1.un_point (accept_channel_funding_pubkey m)
    602     , BOLT1.un_point (accept_channel_revocation_basepoint m)
    603     , BOLT1.un_point (accept_channel_payment_basepoint m)
    604     , BOLT1.un_point (accept_channel_delayed_payment_basepoint m)
    605     , BOLT1.un_point (accept_channel_htlc_basepoint m)
    606     , BOLT1.un_point (accept_channel_first_per_commitment_point m)
    607     , ts
    608     ]
    609 
    610 -- | Decode an t'AcceptChannel' payload.
    611 decode_accept_channel :: BS.ByteString -> Either DecodeError AcceptChannel
    612 decode_accept_channel = parse $ do
    613   tcid  <- channel_id
    614   dust  <- satoshi
    615   maxv  <- u64
    616   res   <- satoshi
    617   hmin  <- milli_satoshi
    618   depth <- u32
    619   delay <- u16
    620   maxa  <- u16
    621   fpk   <- point
    622   rev   <- point
    623   pay   <- point
    624   del   <- point
    625   htlc  <- point
    626   pcp   <- point
    627   s     <- tlvs accept_channel_known
    628   shut  <- record 0 script_pubkey s
    629   ctype <- record 1 (Just . BOLT9.parse) s
    630   pure AcceptChannel {
    631       accept_channel_temporary_channel_id          = tcid
    632     , accept_channel_dust_limit_satoshis           = dust
    633     , accept_channel_max_htlc_value_in_flight_msat = maxv
    634     , accept_channel_channel_reserve_satoshis      = res
    635     , accept_channel_htlc_minimum_msat             = hmin
    636     , accept_channel_minimum_depth                 = depth
    637     , accept_channel_to_self_delay                 = delay
    638     , accept_channel_max_accepted_htlcs            = maxa
    639     , accept_channel_funding_pubkey                = fpk
    640     , accept_channel_revocation_basepoint          = rev
    641     , accept_channel_payment_basepoint             = pay
    642     , accept_channel_delayed_payment_basepoint     = del
    643     , accept_channel_htlc_basepoint                = htlc
    644     , accept_channel_first_per_commitment_point    = pcp
    645     , accept_channel_upfront_shutdown_script       = shut
    646     , accept_channel_channel_type                  = ctype
    647     , accept_channel_tlvs = unknown accept_channel_known s
    648     }
    649 
    650 -- funding_created, funding_signed --------------------------------------------
    651 
    652 -- | Encode a t'FundingCreated' payload.
    653 encode_funding_created :: FundingCreated -> BS.ByteString
    654 encode_funding_created m = mconcat [
    655     BOLT1.un_channel_id (funding_created_temporary_channel_id m)
    656   , txid_bytes (funding_created_funding_txid m)
    657   , BOLT1.encode_u16 (funding_created_funding_output_index m)
    658   , BOLT1.un_signature (funding_created_signature m)
    659   , BOLT1.encode_tlv_stream (funding_created_tlvs m)
    660   ]
    661 
    662 -- | Decode a t'FundingCreated' payload.
    663 decode_funding_created :: BS.ByteString -> Either DecodeError FundingCreated
    664 decode_funding_created = parse $
    665   FundingCreated <$> channel_id <*> txid <*> u16 <*> signature <*> tlvs []
    666 
    667 -- | Encode a t'FundingSigned' payload.
    668 encode_funding_signed :: FundingSigned -> BS.ByteString
    669 encode_funding_signed m = mconcat [
    670     BOLT1.un_channel_id (funding_signed_channel_id m)
    671   , BOLT1.un_signature (funding_signed_signature m)
    672   , BOLT1.encode_tlv_stream (funding_signed_tlvs m)
    673   ]
    674 
    675 -- | Decode a t'FundingSigned' payload.
    676 decode_funding_signed :: BS.ByteString -> Either DecodeError FundingSigned
    677 decode_funding_signed = parse $
    678   FundingSigned <$> channel_id <*> signature <*> tlvs []
    679 
    680 -- channel_ready --------------------------------------------------------------
    681 
    682 channel_ready_known :: [Word64]
    683 channel_ready_known = [1]
    684 
    685 -- | Encode a t'ChannelReady' payload.
    686 encode_channel_ready :: ChannelReady -> Either EncodeError BS.ByteString
    687 encode_channel_ready m = do
    688   ts <- encode_tlvs channel_ready_known
    689     (opt 1 BOLT1.encode_short_channel_id (channel_ready_alias m))
    690     (channel_ready_tlvs m)
    691   pure $ mconcat [
    692       BOLT1.un_channel_id (channel_ready_channel_id m)
    693     , BOLT1.un_point (channel_ready_second_per_commitment_point m)
    694     , ts
    695     ]
    696 
    697 -- | Decode a t'ChannelReady' payload.
    698 decode_channel_ready :: BS.ByteString -> Either DecodeError ChannelReady
    699 decode_channel_ready = parse $ do
    700   cid   <- channel_id
    701   pcp   <- point
    702   s     <- tlvs channel_ready_known
    703   alias <- record 1 (whole BOLT1.decode_short_channel_id) s
    704   pure (ChannelReady cid pcp alias (unknown channel_ready_known s))
    705 
    706 -- open_channel2 --------------------------------------------------------------
    707 
    708 opening_known :: [Word64]
    709 opening_known = [0, 1, 2]
    710 
    711 -- | Encode an t'OpenChannel2' payload.
    712 encode_open_channel2 :: OpenChannel2 -> Either EncodeError BS.ByteString
    713 encode_open_channel2 m = do
    714   ts <- encode_tlvs opening_known
    715     (  opt 0 un_script_pubkey (open_channel2_upfront_shutdown_script m)
    716     <> opt 1 BOLT9.render (open_channel2_channel_type m)
    717     <> opt_flag 2 (open_channel2_require_confirmed_inputs m) )
    718     (open_channel2_tlvs m)
    719   pure $ mconcat [
    720       BOLT1.un_chain_hash (open_channel2_chain_hash m)
    721     , BOLT1.un_channel_id (open_channel2_temporary_channel_id m)
    722     , BOLT1.encode_u32 (open_channel2_funding_feerate_perkw m)
    723     , BOLT1.encode_u32 (open_channel2_commitment_feerate_perkw m)
    724     , BOLT1.encode_satoshi (open_channel2_funding_satoshis m)
    725     , BOLT1.encode_satoshi (open_channel2_dust_limit_satoshis m)
    726     , BOLT1.encode_u64 (open_channel2_max_htlc_value_in_flight_msat m)
    727     , BOLT1.encode_milli_satoshi (open_channel2_htlc_minimum_msat m)
    728     , BOLT1.encode_u16 (open_channel2_to_self_delay m)
    729     , BOLT1.encode_u16 (open_channel2_max_accepted_htlcs m)
    730     , BOLT1.encode_u32 (open_channel2_locktime m)
    731     , BOLT1.un_point (open_channel2_funding_pubkey m)
    732     , BOLT1.un_point (open_channel2_revocation_basepoint m)
    733     , BOLT1.un_point (open_channel2_payment_basepoint m)
    734     , BOLT1.un_point (open_channel2_delayed_payment_basepoint m)
    735     , BOLT1.un_point (open_channel2_htlc_basepoint m)
    736     , BOLT1.un_point (open_channel2_first_per_commitment_point m)
    737     , BOLT1.un_point (open_channel2_second_per_commitment_point m)
    738     , word8 (open_channel2_channel_flags m)
    739     , ts
    740     ]
    741 
    742 -- | Decode an t'OpenChannel2' payload.
    743 decode_open_channel2 :: BS.ByteString -> Either DecodeError OpenChannel2
    744 decode_open_channel2 = parse $ do
    745   ch    <- chain_hash
    746   tcid  <- channel_id
    747   ffee  <- u32
    748   cfee  <- u32
    749   fund  <- satoshi
    750   dust  <- satoshi
    751   maxv  <- u64
    752   hmin  <- milli_satoshi
    753   delay <- u16
    754   maxa  <- u16
    755   lock  <- u32
    756   fpk   <- point
    757   rev   <- point
    758   pay   <- point
    759   del   <- point
    760   htlc  <- point
    761   pcp1  <- point
    762   pcp2  <- point
    763   flags <- u8
    764   s     <- tlvs opening_known
    765   shut  <- record 0 script_pubkey s
    766   ctype <- record 1 (Just . BOLT9.parse) s
    767   conf  <- flag 2 s
    768   pure OpenChannel2 {
    769       open_channel2_chain_hash                    = ch
    770     , open_channel2_temporary_channel_id          = tcid
    771     , open_channel2_funding_feerate_perkw         = ffee
    772     , open_channel2_commitment_feerate_perkw      = cfee
    773     , open_channel2_funding_satoshis              = fund
    774     , open_channel2_dust_limit_satoshis           = dust
    775     , open_channel2_max_htlc_value_in_flight_msat = maxv
    776     , open_channel2_htlc_minimum_msat             = hmin
    777     , open_channel2_to_self_delay                 = delay
    778     , open_channel2_max_accepted_htlcs            = maxa
    779     , open_channel2_locktime                      = lock
    780     , open_channel2_funding_pubkey                = fpk
    781     , open_channel2_revocation_basepoint          = rev
    782     , open_channel2_payment_basepoint             = pay
    783     , open_channel2_delayed_payment_basepoint     = del
    784     , open_channel2_htlc_basepoint                = htlc
    785     , open_channel2_first_per_commitment_point    = pcp1
    786     , open_channel2_second_per_commitment_point   = pcp2
    787     , open_channel2_channel_flags                 = flags
    788     , open_channel2_upfront_shutdown_script       = shut
    789     , open_channel2_channel_type                  = ctype
    790     , open_channel2_require_confirmed_inputs      = conf
    791     , open_channel2_tlvs                          = unknown opening_known s
    792     }
    793 
    794 -- accept_channel2 ------------------------------------------------------------
    795 
    796 -- | Encode an t'AcceptChannel2' payload.
    797 encode_accept_channel2 :: AcceptChannel2 -> Either EncodeError BS.ByteString
    798 encode_accept_channel2 m = do
    799   ts <- encode_tlvs opening_known
    800     (  opt 0 un_script_pubkey (accept_channel2_upfront_shutdown_script m)
    801     <> opt 1 BOLT9.render (accept_channel2_channel_type m)
    802     <> opt_flag 2 (accept_channel2_require_confirmed_inputs m) )
    803     (accept_channel2_tlvs m)
    804   pure $ mconcat [
    805       BOLT1.un_channel_id (accept_channel2_temporary_channel_id m)
    806     , BOLT1.encode_satoshi (accept_channel2_funding_satoshis m)
    807     , BOLT1.encode_satoshi (accept_channel2_dust_limit_satoshis m)
    808     , BOLT1.encode_u64 (accept_channel2_max_htlc_value_in_flight_msat m)
    809     , BOLT1.encode_milli_satoshi (accept_channel2_htlc_minimum_msat m)
    810     , BOLT1.encode_u32 (accept_channel2_minimum_depth m)
    811     , BOLT1.encode_u16 (accept_channel2_to_self_delay m)
    812     , BOLT1.encode_u16 (accept_channel2_max_accepted_htlcs m)
    813     , BOLT1.un_point (accept_channel2_funding_pubkey m)
    814     , BOLT1.un_point (accept_channel2_revocation_basepoint m)
    815     , BOLT1.un_point (accept_channel2_payment_basepoint m)
    816     , BOLT1.un_point (accept_channel2_delayed_payment_basepoint m)
    817     , BOLT1.un_point (accept_channel2_htlc_basepoint m)
    818     , BOLT1.un_point (accept_channel2_first_per_commitment_point m)
    819     , BOLT1.un_point (accept_channel2_second_per_commitment_point m)
    820     , ts
    821     ]
    822 
    823 -- | Decode an t'AcceptChannel2' payload.
    824 decode_accept_channel2 :: BS.ByteString -> Either DecodeError AcceptChannel2
    825 decode_accept_channel2 = parse $ do
    826   tcid  <- channel_id
    827   fund  <- satoshi
    828   dust  <- satoshi
    829   maxv  <- u64
    830   hmin  <- milli_satoshi
    831   depth <- u32
    832   delay <- u16
    833   maxa  <- u16
    834   fpk   <- point
    835   rev   <- point
    836   pay   <- point
    837   del   <- point
    838   htlc  <- point
    839   pcp1  <- point
    840   pcp2  <- point
    841   s     <- tlvs opening_known
    842   shut  <- record 0 script_pubkey s
    843   ctype <- record 1 (Just . BOLT9.parse) s
    844   conf  <- flag 2 s
    845   pure AcceptChannel2 {
    846       accept_channel2_temporary_channel_id          = tcid
    847     , accept_channel2_funding_satoshis              = fund
    848     , accept_channel2_dust_limit_satoshis           = dust
    849     , accept_channel2_max_htlc_value_in_flight_msat = maxv
    850     , accept_channel2_htlc_minimum_msat             = hmin
    851     , accept_channel2_minimum_depth                 = depth
    852     , accept_channel2_to_self_delay                 = delay
    853     , accept_channel2_max_accepted_htlcs            = maxa
    854     , accept_channel2_funding_pubkey                = fpk
    855     , accept_channel2_revocation_basepoint          = rev
    856     , accept_channel2_payment_basepoint             = pay
    857     , accept_channel2_delayed_payment_basepoint     = del
    858     , accept_channel2_htlc_basepoint                = htlc
    859     , accept_channel2_first_per_commitment_point    = pcp1
    860     , accept_channel2_second_per_commitment_point   = pcp2
    861     , accept_channel2_upfront_shutdown_script       = shut
    862     , accept_channel2_channel_type                  = ctype
    863     , accept_channel2_require_confirmed_inputs      = conf
    864     , accept_channel2_tlvs = unknown opening_known s
    865     }
    866 
    867 -- interactive transaction construction ---------------------------------------
    868 
    869 -- | Encode a t'TxAddInput' payload. Fails if @prevtx@ exceeds 65535
    870 --   bytes.
    871 encode_tx_add_input :: TxAddInput -> Either EncodeError BS.ByteString
    872 encode_tx_add_input m = do
    873   prev <- u16_prefixed (tx_add_input_prevtx m)
    874   let SerialId sid = tx_add_input_serial_id m
    875   pure $ mconcat [
    876       BOLT1.un_channel_id (tx_add_input_channel_id m)
    877     , BOLT1.encode_u64 sid
    878     , prev
    879     , BOLT1.encode_u32 (tx_add_input_prevtx_vout m)
    880     , BOLT1.encode_u32 (tx_add_input_sequence m)
    881     , BOLT1.encode_tlv_stream (tx_add_input_tlvs m)
    882     ]
    883 
    884 -- | Decode a t'TxAddInput' payload.
    885 decode_tx_add_input :: BS.ByteString -> Either DecodeError TxAddInput
    886 decode_tx_add_input = parse $
    887   TxAddInput <$> channel_id <*> serial_id <*> prefixed <*> u32 <*> u32
    888              <*> tlvs []
    889 
    890 -- | Encode a t'TxAddOutput' payload.
    891 encode_tx_add_output :: TxAddOutput -> BS.ByteString
    892 encode_tx_add_output m =
    893   let SerialId sid = tx_add_output_serial_id m
    894   in  mconcat [
    895           BOLT1.un_channel_id (tx_add_output_channel_id m)
    896         , BOLT1.encode_u64 sid
    897         , BOLT1.encode_satoshi (tx_add_output_sats m)
    898         , script_bytes (tx_add_output_script m)
    899         , BOLT1.encode_tlv_stream (tx_add_output_tlvs m)
    900         ]
    901 
    902 -- | Decode a t'TxAddOutput' payload.
    903 decode_tx_add_output :: BS.ByteString -> Either DecodeError TxAddOutput
    904 decode_tx_add_output = parse $
    905   TxAddOutput <$> channel_id <*> serial_id <*> satoshi <*> script
    906               <*> tlvs []
    907 
    908 -- | Encode a t'TxRemoveInput' payload.
    909 encode_tx_remove_input :: TxRemoveInput -> BS.ByteString
    910 encode_tx_remove_input (TxRemoveInput cid (SerialId sid) ts) = mconcat [
    911     BOLT1.un_channel_id cid
    912   , BOLT1.encode_u64 sid
    913   , BOLT1.encode_tlv_stream ts
    914   ]
    915 
    916 -- | Decode a t'TxRemoveInput' payload.
    917 decode_tx_remove_input :: BS.ByteString -> Either DecodeError TxRemoveInput
    918 decode_tx_remove_input = parse $
    919   TxRemoveInput <$> channel_id <*> serial_id <*> tlvs []
    920 
    921 -- | Encode a t'TxRemoveOutput' payload.
    922 encode_tx_remove_output :: TxRemoveOutput -> BS.ByteString
    923 encode_tx_remove_output (TxRemoveOutput cid (SerialId sid) ts) = mconcat [
    924     BOLT1.un_channel_id cid
    925   , BOLT1.encode_u64 sid
    926   , BOLT1.encode_tlv_stream ts
    927   ]
    928 
    929 -- | Decode a t'TxRemoveOutput' payload.
    930 decode_tx_remove_output
    931   :: BS.ByteString -> Either DecodeError TxRemoveOutput
    932 decode_tx_remove_output = parse $
    933   TxRemoveOutput <$> channel_id <*> serial_id <*> tlvs []
    934 
    935 -- | Encode a t'TxComplete' payload.
    936 encode_tx_complete :: TxComplete -> BS.ByteString
    937 encode_tx_complete (TxComplete cid ts) =
    938   BOLT1.un_channel_id cid <> BOLT1.encode_tlv_stream ts
    939 
    940 -- | Decode a t'TxComplete' payload.
    941 decode_tx_complete :: BS.ByteString -> Either DecodeError TxComplete
    942 decode_tx_complete = parse $ TxComplete <$> channel_id <*> tlvs []
    943 
    944 -- | Encode a t'TxSignatures' payload. Fails if there are more than 65535
    945 --   witnesses.
    946 encode_tx_signatures :: TxSignatures -> Either EncodeError BS.ByteString
    947 encode_tx_signatures m = do
    948   let ws = tx_signatures_witnesses m
    949   n <- count_prefix ws
    950   pure $ mconcat [
    951       BOLT1.un_channel_id (tx_signatures_channel_id m)
    952     , txid_bytes (tx_signatures_txid m)
    953     , n
    954     , mconcat [ BOLT1.encode_u16 (fromIntegral (BS.length w)) <> w
    955               | w <- map un_witness ws ]
    956     , BOLT1.encode_tlv_stream (tx_signatures_tlvs m)
    957     ]
    958 
    959 -- | Decode a t'TxSignatures' payload.
    960 decode_tx_signatures :: BS.ByteString -> Either DecodeError TxSignatures
    961 decode_tx_signatures = parse $ do
    962   cid <- channel_id
    963   t   <- txid
    964   n   <- u16
    965   ws  <- count (fromIntegral n) wit
    966   TxSignatures cid t ws <$> tlvs []
    967   where
    968     wit = do
    969       b <- prefixed
    970       maybe (failure DecodeInsufficientBytes) pure (witness b)
    971 
    972 rbf_known :: [Word64]
    973 rbf_known = [0, 2]
    974 
    975 -- | Encode a t'TxInitRbf' payload.
    976 encode_tx_init_rbf :: TxInitRbf -> Either EncodeError BS.ByteString
    977 encode_tx_init_rbf m = do
    978   ts <- encode_tlvs rbf_known
    979     (  opt 0 BOLT1.encode_s64 (tx_init_rbf_funding_output_contribution m)
    980     <> opt_flag 2 (tx_init_rbf_require_confirmed_inputs m) )
    981     (tx_init_rbf_tlvs m)
    982   pure $ mconcat [
    983       BOLT1.un_channel_id (tx_init_rbf_channel_id m)
    984     , BOLT1.encode_u32 (tx_init_rbf_locktime m)
    985     , BOLT1.encode_u32 (tx_init_rbf_feerate m)
    986     , ts
    987     ]
    988 
    989 -- | Decode a t'TxInitRbf' payload.
    990 decode_tx_init_rbf :: BS.ByteString -> Either DecodeError TxInitRbf
    991 decode_tx_init_rbf = parse $ do
    992   cid  <- channel_id
    993   lock <- u32
    994   fee  <- u32
    995   s    <- tlvs rbf_known
    996   contrib <- record 0 tlv_s64 s
    997   conf <- flag 2 s
    998   pure (TxInitRbf cid lock fee contrib conf (unknown rbf_known s))
    999 
   1000 -- | Encode a t'TxAckRbf' payload.
   1001 encode_tx_ack_rbf :: TxAckRbf -> Either EncodeError BS.ByteString
   1002 encode_tx_ack_rbf m = do
   1003   ts <- encode_tlvs rbf_known
   1004     (  opt 0 BOLT1.encode_s64 (tx_ack_rbf_funding_output_contribution m)
   1005     <> opt_flag 2 (tx_ack_rbf_require_confirmed_inputs m) )
   1006     (tx_ack_rbf_tlvs m)
   1007   pure (BOLT1.un_channel_id (tx_ack_rbf_channel_id m) <> ts)
   1008 
   1009 -- | Decode a t'TxAckRbf' payload.
   1010 decode_tx_ack_rbf :: BS.ByteString -> Either DecodeError TxAckRbf
   1011 decode_tx_ack_rbf = parse $ do
   1012   cid  <- channel_id
   1013   s    <- tlvs rbf_known
   1014   contrib <- record 0 tlv_s64 s
   1015   conf <- flag 2 s
   1016   pure (TxAckRbf cid contrib conf (unknown rbf_known s))
   1017 
   1018 -- | Encode a t'TxAbort' payload. Fails if @data@ exceeds 65535 bytes.
   1019 encode_tx_abort :: TxAbort -> Either EncodeError BS.ByteString
   1020 encode_tx_abort (TxAbort cid dat ts) = do
   1021   dat' <- u16_prefixed dat
   1022   pure (BOLT1.un_channel_id cid <> dat' <> BOLT1.encode_tlv_stream ts)
   1023 
   1024 -- | Decode a t'TxAbort' payload.
   1025 decode_tx_abort :: BS.ByteString -> Either DecodeError TxAbort
   1026 decode_tx_abort = parse $ TxAbort <$> channel_id <*> prefixed <*> tlvs []
   1027 
   1028 -- stfu -----------------------------------------------------------------------
   1029 
   1030 -- | Encode a t'Stfu' payload.
   1031 encode_stfu :: Stfu -> BS.ByteString
   1032 encode_stfu (Stfu cid ini ts) = mconcat [
   1033     BOLT1.un_channel_id cid
   1034   , word8 (if ini then 1 else 0)
   1035   , BOLT1.encode_tlv_stream ts
   1036   ]
   1037 
   1038 -- | Decode a t'Stfu' payload. The @initiator@ byte must be 0 or 1.
   1039 decode_stfu :: BS.ByteString -> Either DecodeError Stfu
   1040 decode_stfu = parse $ do
   1041   cid <- channel_id
   1042   b   <- u8
   1043   ini <- case b of
   1044     0 -> pure False
   1045     1 -> pure True
   1046     _ -> failure DecodeInvalidInitiator
   1047   Stfu cid ini <$> tlvs []
   1048 
   1049 -- shutdown -------------------------------------------------------------------
   1050 
   1051 -- | Encode a t'Shutdown' payload.
   1052 encode_shutdown :: Shutdown -> BS.ByteString
   1053 encode_shutdown (Shutdown cid spk ts) = mconcat [
   1054     BOLT1.un_channel_id cid
   1055   , script_bytes spk
   1056   , BOLT1.encode_tlv_stream ts
   1057   ]
   1058 
   1059 -- | Decode a t'Shutdown' payload.
   1060 decode_shutdown :: BS.ByteString -> Either DecodeError Shutdown
   1061 decode_shutdown = parse $ Shutdown <$> channel_id <*> script <*> tlvs []
   1062 
   1063 -- closing_complete, closing_sig ----------------------------------------------
   1064 
   1065 closing_known :: [Word64]
   1066 closing_known = [1, 2, 3]
   1067 
   1068 closing_records
   1069   :: Maybe Signature -> Maybe Signature -> Maybe Signature -> [TlvRecord]
   1070 closing_records a b c =
   1071      opt 1 BOLT1.un_signature a
   1072   <> opt 2 BOLT1.un_signature b
   1073   <> opt 3 BOLT1.un_signature c
   1074 
   1075 -- | Encode a t'ClosingComplete' payload.
   1076 encode_closing_complete :: ClosingComplete -> Either EncodeError BS.ByteString
   1077 encode_closing_complete m = do
   1078   ts <- encode_tlvs closing_known
   1079     (closing_records
   1080       (closing_complete_closer_output_only m)
   1081       (closing_complete_closee_output_only m)
   1082       (closing_complete_closer_and_closee_outputs m))
   1083     (closing_complete_tlvs m)
   1084   pure $ mconcat [
   1085       BOLT1.un_channel_id (closing_complete_channel_id m)
   1086     , script_bytes (closing_complete_closer_scriptpubkey m)
   1087     , script_bytes (closing_complete_closee_scriptpubkey m)
   1088     , BOLT1.encode_satoshi (closing_complete_fee_satoshis m)
   1089     , BOLT1.encode_u32 (closing_complete_locktime m)
   1090     , ts
   1091     ]
   1092 
   1093 -- | Decode a t'ClosingComplete' payload.
   1094 decode_closing_complete
   1095   :: BS.ByteString -> Either DecodeError ClosingComplete
   1096 decode_closing_complete = parse $ do
   1097   cid    <- channel_id
   1098   closer <- script
   1099   closee <- script
   1100   fee    <- satoshi
   1101   lock   <- u32
   1102   s      <- tlvs closing_known
   1103   a      <- record 1 BOLT1.signature s
   1104   b      <- record 2 BOLT1.signature s
   1105   c      <- record 3 BOLT1.signature s
   1106   pure (ClosingComplete cid closer closee fee lock a b c
   1107           (unknown closing_known s))
   1108 
   1109 -- | Encode a t'ClosingSig' payload.
   1110 encode_closing_sig :: ClosingSig -> Either EncodeError BS.ByteString
   1111 encode_closing_sig m = do
   1112   ts <- encode_tlvs closing_known
   1113     (closing_records
   1114       (closing_sig_closer_output_only m)
   1115       (closing_sig_closee_output_only m)
   1116       (closing_sig_closer_and_closee_outputs m))
   1117     (closing_sig_tlvs m)
   1118   pure $ mconcat [
   1119       BOLT1.un_channel_id (closing_sig_channel_id m)
   1120     , script_bytes (closing_sig_closer_scriptpubkey m)
   1121     , script_bytes (closing_sig_closee_scriptpubkey m)
   1122     , BOLT1.encode_satoshi (closing_sig_fee_satoshis m)
   1123     , BOLT1.encode_u32 (closing_sig_locktime m)
   1124     , ts
   1125     ]
   1126 
   1127 -- | Decode a t'ClosingSig' payload.
   1128 decode_closing_sig :: BS.ByteString -> Either DecodeError ClosingSig
   1129 decode_closing_sig = parse $ do
   1130   cid    <- channel_id
   1131   closer <- script
   1132   closee <- script
   1133   fee    <- satoshi
   1134   lock   <- u32
   1135   s      <- tlvs closing_known
   1136   a      <- record 1 BOLT1.signature s
   1137   b      <- record 2 BOLT1.signature s
   1138   c      <- record 3 BOLT1.signature s
   1139   pure (ClosingSig cid closer closee fee lock a b c
   1140           (unknown closing_known s))
   1141 
   1142 -- closing_signed -------------------------------------------------------------
   1143 
   1144 closing_signed_known :: [Word64]
   1145 closing_signed_known = [1]
   1146 
   1147 -- | Encode a t'ClosingSigned' payload.
   1148 encode_closing_signed :: ClosingSigned -> Either EncodeError BS.ByteString
   1149 encode_closing_signed m = do
   1150   ts <- encode_tlvs closing_signed_known
   1151     (opt 1 fee_range_bytes (closing_signed_fee_range m))
   1152     (closing_signed_tlvs m)
   1153   pure $ mconcat [
   1154       BOLT1.un_channel_id (closing_signed_channel_id m)
   1155     , BOLT1.encode_satoshi (closing_signed_fee_satoshis m)
   1156     , BOLT1.un_signature (closing_signed_signature m)
   1157     , ts
   1158     ]
   1159 
   1160 -- | Decode a t'ClosingSigned' payload.
   1161 decode_closing_signed :: BS.ByteString -> Either DecodeError ClosingSigned
   1162 decode_closing_signed = parse $ do
   1163   cid   <- channel_id
   1164   fee   <- satoshi
   1165   sig   <- signature
   1166   s     <- tlvs closing_signed_known
   1167   range <- record 1 tlv_fee_range s
   1168   pure (ClosingSigned cid fee sig range (unknown closing_signed_known s))
   1169 
   1170 -- update_add_htlc ------------------------------------------------------------
   1171 
   1172 update_add_htlc_known :: [Word64]
   1173 update_add_htlc_known = [0]
   1174 
   1175 -- | Encode an t'UpdateAddHtlc' payload.
   1176 encode_update_add_htlc :: UpdateAddHtlc -> Either EncodeError BS.ByteString
   1177 encode_update_add_htlc m = do
   1178   ts <- encode_tlvs update_add_htlc_known
   1179     (opt 0 BOLT1.un_point (update_add_htlc_path_key m))
   1180     (update_add_htlc_tlvs m)
   1181   let HtlcId hid = update_add_htlc_id m
   1182   pure $ mconcat [
   1183       BOLT1.un_channel_id (update_add_htlc_channel_id m)
   1184     , BOLT1.encode_u64 hid
   1185     , BOLT1.encode_milli_satoshi (update_add_htlc_amount_msat m)
   1186     , BOLT1.un_payment_hash (update_add_htlc_payment_hash m)
   1187     , BOLT1.encode_u32 (update_add_htlc_cltv_expiry m)
   1188     , un_onion_routing_packet (update_add_htlc_onion_routing_packet m)
   1189     , ts
   1190     ]
   1191 
   1192 -- | Decode an t'UpdateAddHtlc' payload.
   1193 decode_update_add_htlc :: BS.ByteString -> Either DecodeError UpdateAddHtlc
   1194 decode_update_add_htlc = parse $ do
   1195   cid   <- channel_id
   1196   hid   <- htlc_id
   1197   amt   <- milli_satoshi
   1198   ph    <- payment_hash
   1199   cltv  <- u32
   1200   onion <- sized 1366 onion_routing_packet
   1201   s     <- tlvs update_add_htlc_known
   1202   pk    <- record 0 tlv_point s
   1203   pure (UpdateAddHtlc cid hid amt ph cltv onion pk
   1204           (unknown update_add_htlc_known s))
   1205 
   1206 -- update_fulfill_htlc --------------------------------------------------------
   1207 
   1208 update_fulfill_htlc_known :: [Word64]
   1209 update_fulfill_htlc_known = [1, 3]
   1210 
   1211 -- | Encode an t'UpdateFulfillHtlc' payload.
   1212 encode_update_fulfill_htlc
   1213   :: UpdateFulfillHtlc -> Either EncodeError BS.ByteString
   1214 encode_update_fulfill_htlc m = do
   1215   ts <- encode_tlvs update_fulfill_htlc_known
   1216     (  opt 1 un_attribution_data (update_fulfill_htlc_attribution_data m)
   1217     <> opt 3 id (update_fulfill_htlc_fulfillment_payload m) )
   1218     (update_fulfill_htlc_tlvs m)
   1219   let HtlcId hid = update_fulfill_htlc_id m
   1220   pure $ mconcat [
   1221       BOLT1.un_channel_id (update_fulfill_htlc_channel_id m)
   1222     , BOLT1.encode_u64 hid
   1223     , BOLT1.un_payment_preimage (update_fulfill_htlc_payment_preimage m)
   1224     , ts
   1225     ]
   1226 
   1227 -- | Decode an t'UpdateFulfillHtlc' payload.
   1228 decode_update_fulfill_htlc
   1229   :: BS.ByteString -> Either DecodeError UpdateFulfillHtlc
   1230 decode_update_fulfill_htlc = parse $ do
   1231   cid <- channel_id
   1232   hid <- htlc_id
   1233   pre <- payment_preimage
   1234   s   <- tlvs update_fulfill_htlc_known
   1235   att <- record 1 attribution_data s
   1236   pay <- record 3 Just s
   1237   pure (UpdateFulfillHtlc cid hid pre att pay
   1238           (unknown update_fulfill_htlc_known s))
   1239 
   1240 -- update_fail_htlc -----------------------------------------------------------
   1241 
   1242 update_fail_htlc_known :: [Word64]
   1243 update_fail_htlc_known = [1]
   1244 
   1245 -- | Encode an t'UpdateFailHtlc' payload. Fails if @reason@ exceeds 65535
   1246 --   bytes.
   1247 encode_update_fail_htlc :: UpdateFailHtlc -> Either EncodeError BS.ByteString
   1248 encode_update_fail_htlc m = do
   1249   reason <- u16_prefixed (update_fail_htlc_reason m)
   1250   ts <- encode_tlvs update_fail_htlc_known
   1251     (opt 1 un_attribution_data (update_fail_htlc_attribution_data m))
   1252     (update_fail_htlc_tlvs m)
   1253   let HtlcId hid = update_fail_htlc_id m
   1254   pure $ mconcat [
   1255       BOLT1.un_channel_id (update_fail_htlc_channel_id m)
   1256     , BOLT1.encode_u64 hid
   1257     , reason
   1258     , ts
   1259     ]
   1260 
   1261 -- | Decode an t'UpdateFailHtlc' payload.
   1262 decode_update_fail_htlc :: BS.ByteString -> Either DecodeError UpdateFailHtlc
   1263 decode_update_fail_htlc = parse $ do
   1264   cid    <- channel_id
   1265   hid    <- htlc_id
   1266   reason <- prefixed
   1267   s      <- tlvs update_fail_htlc_known
   1268   att    <- record 1 attribution_data s
   1269   pure (UpdateFailHtlc cid hid reason att (unknown update_fail_htlc_known s))
   1270 
   1271 -- update_fail_malformed_htlc -------------------------------------------------
   1272 
   1273 -- | Encode an t'UpdateFailMalformedHtlc' payload.
   1274 encode_update_fail_malformed_htlc :: UpdateFailMalformedHtlc -> BS.ByteString
   1275 encode_update_fail_malformed_htlc
   1276   (UpdateFailMalformedHtlc cid (HtlcId hid) oh code ts) = mconcat [
   1277       BOLT1.un_channel_id cid
   1278     , BOLT1.encode_u64 hid
   1279     , un_onion_hash oh
   1280     , BOLT1.encode_u16 code
   1281     , BOLT1.encode_tlv_stream ts
   1282     ]
   1283 
   1284 -- | Decode an t'UpdateFailMalformedHtlc' payload.
   1285 decode_update_fail_malformed_htlc
   1286   :: BS.ByteString -> Either DecodeError UpdateFailMalformedHtlc
   1287 decode_update_fail_malformed_htlc = parse $
   1288   UpdateFailMalformedHtlc <$> channel_id <*> htlc_id <*> sized 32 onion_hash
   1289                           <*> u16 <*> tlvs []
   1290 
   1291 -- commitment_signed ----------------------------------------------------------
   1292 
   1293 commitment_signed_known :: [Word64]
   1294 commitment_signed_known = [1]
   1295 
   1296 -- | Encode a t'CommitmentSigned' payload. Fails if there are more than
   1297 --   65535 HTLC signatures.
   1298 encode_commitment_signed
   1299   :: CommitmentSigned -> Either EncodeError BS.ByteString
   1300 encode_commitment_signed m = do
   1301   let sigs = commitment_signed_htlc_signatures m
   1302   n  <- count_prefix sigs
   1303   ts <- encode_tlvs commitment_signed_known
   1304     (opt 1 txid_bytes (commitment_signed_funding_txid m))
   1305     (commitment_signed_tlvs m)
   1306   pure $ mconcat [
   1307       BOLT1.un_channel_id (commitment_signed_channel_id m)
   1308     , BOLT1.un_signature (commitment_signed_signature m)
   1309     , n
   1310     , mconcat (map BOLT1.un_signature sigs)
   1311     , ts
   1312     ]
   1313 
   1314 -- | Decode a t'CommitmentSigned' payload.
   1315 decode_commitment_signed
   1316   :: BS.ByteString -> Either DecodeError CommitmentSigned
   1317 decode_commitment_signed = parse $ do
   1318   cid  <- channel_id
   1319   sig  <- signature
   1320   n    <- u16
   1321   sigs <- count (fromIntegral n) signature
   1322   s    <- tlvs commitment_signed_known
   1323   fund <- record 1 mk_txid s
   1324   pure (CommitmentSigned cid sig sigs fund (unknown commitment_signed_known s))
   1325 
   1326 -- revoke_and_ack, update_fee -------------------------------------------------
   1327 
   1328 -- | Encode a t'RevokeAndAck' payload.
   1329 encode_revoke_and_ack :: RevokeAndAck -> BS.ByteString
   1330 encode_revoke_and_ack (RevokeAndAck cid sec pcp ts) = mconcat [
   1331     BOLT1.un_channel_id cid
   1332   , BOLT1.un_per_commitment_secret sec
   1333   , BOLT1.un_point pcp
   1334   , BOLT1.encode_tlv_stream ts
   1335   ]
   1336 
   1337 -- | Decode a t'RevokeAndAck' payload.
   1338 decode_revoke_and_ack :: BS.ByteString -> Either DecodeError RevokeAndAck
   1339 decode_revoke_and_ack = parse $
   1340   RevokeAndAck <$> channel_id <*> per_commitment_secret <*> point <*> tlvs []
   1341 
   1342 -- | Encode an t'UpdateFee' payload.
   1343 encode_update_fee :: UpdateFee -> BS.ByteString
   1344 encode_update_fee (UpdateFee cid fee ts) = mconcat [
   1345     BOLT1.un_channel_id cid
   1346   , BOLT1.encode_u32 fee
   1347   , BOLT1.encode_tlv_stream ts
   1348   ]
   1349 
   1350 -- | Decode an t'UpdateFee' payload.
   1351 decode_update_fee :: BS.ByteString -> Either DecodeError UpdateFee
   1352 decode_update_fee = parse $ UpdateFee <$> channel_id <*> u32 <*> tlvs []
   1353 
   1354 -- channel_reestablish --------------------------------------------------------
   1355 
   1356 channel_reestablish_known :: [Word64]
   1357 channel_reestablish_known = [1]
   1358 
   1359 -- | Encode a t'ChannelReestablish' payload.
   1360 encode_channel_reestablish
   1361   :: ChannelReestablish -> Either EncodeError BS.ByteString
   1362 encode_channel_reestablish m = do
   1363   ts <- encode_tlvs channel_reestablish_known
   1364     (opt 1 next_funding_bytes (channel_reestablish_next_funding m))
   1365     (channel_reestablish_tlvs m)
   1366   pure $ mconcat [
   1367       BOLT1.un_channel_id (channel_reestablish_channel_id m)
   1368     , BOLT1.encode_u64 (channel_reestablish_next_commitment_number m)
   1369     , BOLT1.encode_u64 (channel_reestablish_next_revocation_number m)
   1370     , BOLT1.un_per_commitment_secret
   1371         (channel_reestablish_your_last_per_commitment_secret m)
   1372     , BOLT1.un_point (channel_reestablish_my_current_per_commitment_point m)
   1373     , ts
   1374     ]
   1375 
   1376 -- | Decode a t'ChannelReestablish' payload.
   1377 decode_channel_reestablish
   1378   :: BS.ByteString -> Either DecodeError ChannelReestablish
   1379 decode_channel_reestablish = parse $ do
   1380   cid  <- channel_id
   1381   nc   <- u64
   1382   nr   <- u64
   1383   sec  <- per_commitment_secret
   1384   pcp  <- point
   1385   s    <- tlvs channel_reestablish_known
   1386   next <- record 1 tlv_next_funding s
   1387   pure (ChannelReestablish cid nc nr sec pcp next
   1388           (unknown channel_reestablish_known s))