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 (49766B)


      1 {-# OPTIONS_HADDOCK prune #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 {-# LANGUAGE DeriveGeneric #-}
      4 {-# LANGUAGE DerivingStrategies #-}
      5 
      6 -- |
      7 -- Module: Lightning.Protocol.BOLT2.Codec
      8 -- Copyright: (c) 2025 Jared Tobin
      9 -- License: MIT
     10 -- Maintainer: Jared Tobin <jared@ppad.tech>
     11 --
     12 -- Encode/decode functions for BOLT #2 messages.
     13 
     14 module Lightning.Protocol.BOLT2.Codec (
     15   -- * Error types
     16     EncodeError(..)
     17   , DecodeError(..)
     18 
     19   -- * Channel establishment v1
     20   , encodeOpenChannel
     21   , decodeOpenChannel
     22   , encodeAcceptChannel
     23   , decodeAcceptChannel
     24   , encodeFundingCreated
     25   , decodeFundingCreated
     26   , encodeFundingSigned
     27   , decodeFundingSigned
     28   , encodeChannelReady
     29   , decodeChannelReady
     30 
     31   -- * Channel establishment v2 (interactive-tx)
     32   , encodeOpenChannel2
     33   , decodeOpenChannel2
     34   , encodeAcceptChannel2
     35   , decodeAcceptChannel2
     36   , encodeTxAddInput
     37   , decodeTxAddInput
     38   , encodeTxAddOutput
     39   , decodeTxAddOutput
     40   , encodeTxRemoveInput
     41   , decodeTxRemoveInput
     42   , encodeTxRemoveOutput
     43   , decodeTxRemoveOutput
     44   , encodeTxComplete
     45   , decodeTxComplete
     46   , encodeTxSignatures
     47   , decodeTxSignatures
     48   , encodeTxInitRbf
     49   , decodeTxInitRbf
     50   , encodeTxAckRbf
     51   , decodeTxAckRbf
     52   , encodeTxAbort
     53   , decodeTxAbort
     54 
     55   -- * Channel close
     56   , encodeStfu
     57   , decodeStfu
     58   , encodeShutdown
     59   , decodeShutdown
     60   , encodeClosingSigned
     61   , decodeClosingSigned
     62   , encodeClosingComplete
     63   , decodeClosingComplete
     64   , encodeClosingSig
     65   , decodeClosingSig
     66 
     67   -- * Normal operation
     68   , encodeUpdateAddHtlc
     69   , decodeUpdateAddHtlc
     70   , encodeUpdateFulfillHtlc
     71   , decodeUpdateFulfillHtlc
     72   , encodeUpdateFailHtlc
     73   , decodeUpdateFailHtlc
     74   , encodeUpdateFailMalformedHtlc
     75   , decodeUpdateFailMalformedHtlc
     76   , encodeCommitmentSigned
     77   , decodeCommitmentSigned
     78   , encodeRevokeAndAck
     79   , decodeRevokeAndAck
     80   , encodeUpdateFee
     81   , decodeUpdateFee
     82 
     83   -- * Channel reestablishment
     84   , encodeChannelReestablish
     85   , decodeChannelReestablish
     86   ) where
     87 
     88 import Control.DeepSeq (NFData)
     89 import Control.Monad (unless)
     90 import qualified Data.ByteString as BS
     91 import Data.Word (Word8, Word16, Word32)
     92 import GHC.Generics (Generic)
     93 import Lightning.Protocol.BOLT1
     94   ( TlvStream
     95   , unsafeTlvStream
     96   , TlvError
     97   , encodeU16
     98   , encodeU32
     99   , encodeU64
    100   , decodeU16
    101   , decodeU32
    102   , decodeU64
    103   , encodeTlvStream
    104   , decodeTlvStreamRaw
    105   )
    106 import Lightning.Protocol.BOLT2.Types
    107 import Lightning.Protocol.BOLT2.Messages
    108 
    109 -- Error types -----------------------------------------------------------------
    110 
    111 -- | Encoding errors.
    112 data EncodeError
    113   = EncodeLengthOverflow  -- ^ Payload exceeds u16 max (65535 bytes)
    114   deriving stock (Eq, Show, Generic)
    115 
    116 instance NFData EncodeError
    117 
    118 -- | Decoding errors.
    119 data DecodeError
    120   = DecodeInsufficientBytes
    121   | DecodeInvalidLength
    122   | DecodeInvalidChannelId
    123   | DecodeInvalidChainHash
    124   | DecodeInvalidSignature
    125   | DecodeInvalidPoint
    126   | DecodeInvalidTxId
    127   | DecodeInvalidPaymentHash
    128   | DecodeInvalidPaymentPreimage
    129   | DecodeInvalidOnionPacket
    130   | DecodeInvalidSecret
    131   | DecodeInvalidInitiator
    132   | DecodeTlvError !TlvError
    133   deriving stock (Eq, Show, Generic)
    134 
    135 instance NFData DecodeError
    136 
    137 -- Helpers ---------------------------------------------------------------------
    138 
    139 -- | Decode a single byte.
    140 decodeU8 :: BS.ByteString -> Maybe (Word8, BS.ByteString)
    141 decodeU8 !bs
    142   | BS.null bs = Nothing
    143   | otherwise  = Just (BS.index bs 0, BS.drop 1 bs)
    144 {-# INLINE decodeU8 #-}
    145 
    146 -- | Decode fixed-size bytes.
    147 decodeBytes :: Int -> BS.ByteString -> Maybe (BS.ByteString, BS.ByteString)
    148 decodeBytes !n !bs
    149   | BS.length bs < n = Nothing
    150   | otherwise        = Just (BS.take n bs, BS.drop n bs)
    151 {-# INLINE decodeBytes #-}
    152 
    153 -- | Decode a ChannelId (32 bytes).
    154 decodeChannelIdBytes
    155   :: BS.ByteString -> Either DecodeError (ChannelId, BS.ByteString)
    156 decodeChannelIdBytes !bs = do
    157   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    158                    (decodeBytes channelIdLen bs)
    159   cid <- maybe (Left DecodeInvalidChannelId) Right (channelId raw)
    160   Right (cid, rest)
    161 {-# INLINE decodeChannelIdBytes #-}
    162 
    163 -- | Decode a ChainHash (32 bytes).
    164 decodeChainHashBytes
    165   :: BS.ByteString -> Either DecodeError (ChainHash, BS.ByteString)
    166 decodeChainHashBytes !bs = do
    167   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    168                    (decodeBytes chainHashLen bs)
    169   ch <- maybe (Left DecodeInvalidChainHash) Right (chainHash raw)
    170   Right (ch, rest)
    171 {-# INLINE decodeChainHashBytes #-}
    172 
    173 -- | Decode a Signature (64 bytes).
    174 decodeSignatureBytes
    175   :: BS.ByteString -> Either DecodeError (Signature, BS.ByteString)
    176 decodeSignatureBytes !bs = do
    177   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    178                    (decodeBytes signatureLen bs)
    179   sig <- maybe (Left DecodeInvalidSignature) Right (signature raw)
    180   Right (sig, rest)
    181 {-# INLINE decodeSignatureBytes #-}
    182 
    183 -- | Decode a Point (33 bytes).
    184 decodePointBytes
    185   :: BS.ByteString -> Either DecodeError (Point, BS.ByteString)
    186 decodePointBytes !bs = do
    187   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    188                    (decodeBytes pointLen bs)
    189   pt <- maybe (Left DecodeInvalidPoint) Right (point raw)
    190   Right (pt, rest)
    191 {-# INLINE decodePointBytes #-}
    192 
    193 -- | Decode a TxId (32 bytes).
    194 decodeTxIdBytes
    195   :: BS.ByteString -> Either DecodeError (TxId, BS.ByteString)
    196 decodeTxIdBytes !bs = do
    197   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    198                    (decodeBytes 32 bs)
    199   tid <- maybe (Left DecodeInvalidTxId) Right (mkTxId raw)
    200   Right (tid, rest)
    201 {-# INLINE decodeTxIdBytes #-}
    202 
    203 -- | Decode a u16 with error handling.
    204 decodeU16E :: BS.ByteString -> Either DecodeError (Word16, BS.ByteString)
    205 decodeU16E !bs = maybe (Left DecodeInsufficientBytes) Right (decodeU16 bs)
    206 {-# INLINE decodeU16E #-}
    207 
    208 -- | Decode a u32 with error handling.
    209 decodeU32E :: BS.ByteString -> Either DecodeError (Word32, BS.ByteString)
    210 decodeU32E !bs = maybe (Left DecodeInsufficientBytes) Right (decodeU32 bs)
    211 {-# INLINE decodeU32E #-}
    212 
    213 -- | Decode a u64 as Satoshi.
    214 decodeSatoshi
    215   :: BS.ByteString -> Either DecodeError (Satoshi, BS.ByteString)
    216 decodeSatoshi !bs = do
    217   (val, rest) <- maybe (Left DecodeInsufficientBytes) Right (decodeU64 bs)
    218   Right (Satoshi val, rest)
    219 {-# INLINE decodeSatoshi #-}
    220 
    221 -- | Decode a u64 as MilliSatoshi.
    222 decodeMilliSatoshi
    223   :: BS.ByteString -> Either DecodeError (MilliSatoshi, BS.ByteString)
    224 decodeMilliSatoshi !bs = do
    225   (val, rest) <- maybe (Left DecodeInsufficientBytes) Right (decodeU64 bs)
    226   Right (MilliSatoshi val, rest)
    227 {-# INLINE decodeMilliSatoshi #-}
    228 
    229 -- | Decode optional TLV stream from remaining bytes.
    230 decodeTlvs :: BS.ByteString -> Either DecodeError TlvStream
    231 decodeTlvs !bs
    232   | BS.null bs = Right (unsafeTlvStream [])
    233   | otherwise  = either (Left . DecodeTlvError) Right (decodeTlvStreamRaw bs)
    234 {-# INLINE decodeTlvs #-}
    235 
    236 -- | Decode a length-prefixed script (u16 length prefix).
    237 decodeScriptPubKey
    238   :: BS.ByteString -> Either DecodeError (ScriptPubKey, BS.ByteString)
    239 decodeScriptPubKey !bs = do
    240   (len, rest1) <- decodeU16E bs
    241   let !scriptLen = fromIntegral len
    242   unless (BS.length rest1 >= scriptLen) $ Left DecodeInsufficientBytes
    243   let !script = BS.take scriptLen rest1
    244       !rest2 = BS.drop scriptLen rest1
    245   Right (scriptPubKey script, rest2)
    246 {-# INLINE decodeScriptPubKey #-}
    247 
    248 -- | Decode a PaymentHash (32 bytes).
    249 decodePaymentHashBytes
    250   :: BS.ByteString -> Either DecodeError (PaymentHash, BS.ByteString)
    251 decodePaymentHashBytes !bs = do
    252   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    253                    (decodeBytes paymentHashLen bs)
    254   ph <- maybe (Left DecodeInvalidPaymentHash) Right (paymentHash raw)
    255   Right (ph, rest)
    256 {-# INLINE decodePaymentHashBytes #-}
    257 
    258 -- | Decode a PaymentPreimage (32 bytes).
    259 decodePaymentPreimageBytes
    260   :: BS.ByteString -> Either DecodeError (PaymentPreimage, BS.ByteString)
    261 decodePaymentPreimageBytes !bs = do
    262   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    263                    (decodeBytes paymentPreimageLen bs)
    264   pp <- maybe (Left DecodeInvalidPaymentPreimage) Right (paymentPreimage raw)
    265   Right (pp, rest)
    266 {-# INLINE decodePaymentPreimageBytes #-}
    267 
    268 -- | Decode an OnionPacket (1366 bytes).
    269 decodeOnionPacketBytes
    270   :: BS.ByteString -> Either DecodeError (OnionPacket, BS.ByteString)
    271 decodeOnionPacketBytes !bs = do
    272   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    273                    (decodeBytes onionPacketLen bs)
    274   op <- maybe (Left DecodeInvalidOnionPacket) Right (onionPacket raw)
    275   Right (op, rest)
    276 {-# INLINE decodeOnionPacketBytes #-}
    277 
    278 -- | Decode a PerCommitmentSecret (32 bytes).
    279 decodePerCommitmentSecretBytes
    280   :: BS.ByteString
    281   -> Either DecodeError (PerCommitmentSecret, BS.ByteString)
    282 decodePerCommitmentSecretBytes !bs = do
    283   (raw, rest) <- maybe (Left DecodeInsufficientBytes) Right
    284                    (decodeBytes perCommitmentSecretLen bs)
    285   sec <- maybe (Left DecodeInvalidSecret) Right
    286            (perCommitmentSecret raw)
    287   Right (sec, rest)
    288 {-# INLINE decodePerCommitmentSecretBytes #-}
    289 
    290 -- | Encode a u16-prefixed byte string with bounds checking.
    291 encodeU16BytesE :: BS.ByteString -> Either EncodeError BS.ByteString
    292 encodeU16BytesE !bs
    293   | BS.length bs > 65535 = Left EncodeLengthOverflow
    294   | otherwise = Right $! encodeU16 (fromIntegral (BS.length bs)) <> bs
    295 {-# INLINE encodeU16BytesE #-}
    296 
    297 -- | Check that a list count fits in u16.
    298 checkListCountU16 :: Int -> Either EncodeError Word16
    299 checkListCountU16 !n
    300   | n > 65535 = Left EncodeLengthOverflow
    301   | otherwise = Right $! fromIntegral n
    302 {-# INLINE checkListCountU16 #-}
    303 
    304 -- | Decode a u16-prefixed byte string.
    305 decodeU16Bytes
    306   :: BS.ByteString -> Either DecodeError (BS.ByteString, BS.ByteString)
    307 decodeU16Bytes !bs = do
    308   (len, rest1) <- decodeU16E bs
    309   let !n = fromIntegral len
    310   unless (BS.length rest1 >= n) $ Left DecodeInsufficientBytes
    311   Right (BS.take n rest1, BS.drop n rest1)
    312 {-# INLINE decodeU16Bytes #-}
    313 
    314 -- | Decode optional trailing TLV stream.
    315 decodeOptionalTlvs
    316   :: BS.ByteString -> Either DecodeError (TlvStream, BS.ByteString)
    317 decodeOptionalTlvs !bs
    318   | BS.null bs = Right (unsafeTlvStream [], BS.empty)
    319   | otherwise  = case decodeTlvStreamRaw bs of
    320       Left e  -> Left (DecodeTlvError e)
    321       Right t -> Right (t, BS.empty)
    322 {-# INLINE decodeOptionalTlvs #-}
    323 
    324 -- Channel establishment v1 ----------------------------------------------------
    325 
    326 -- | Encode an OpenChannel message (type 32).
    327 --
    328 -- Wire format:
    329 -- - chain_hash: 32 bytes
    330 -- - temporary_channel_id: 32 bytes
    331 -- - funding_satoshis: u64
    332 -- - push_msat: u64
    333 -- - dust_limit_satoshis: u64
    334 -- - max_htlc_value_in_flight_msat: u64
    335 -- - channel_reserve_satoshis: u64
    336 -- - htlc_minimum_msat: u64
    337 -- - feerate_per_kw: u32
    338 -- - to_self_delay: u16
    339 -- - max_accepted_htlcs: u16
    340 -- - funding_pubkey: 33 bytes
    341 -- - revocation_basepoint: 33 bytes
    342 -- - payment_basepoint: 33 bytes
    343 -- - delayed_payment_basepoint: 33 bytes
    344 -- - htlc_basepoint: 33 bytes
    345 -- - first_per_commitment_point: 33 bytes
    346 -- - channel_flags: 1 byte
    347 -- - tlvs: TLV stream
    348 encodeOpenChannel :: OpenChannel -> BS.ByteString
    349 encodeOpenChannel !msg = mconcat
    350   [ unChainHash (openChannelChainHash msg)
    351   , unChannelId (openChannelTempChannelId msg)
    352   , encodeU64 (unSatoshi (openChannelFundingSatoshi msg))
    353   , encodeU64 (unMilliSatoshi (openChannelPushMsat msg))
    354   , encodeU64 (unSatoshi (openChannelDustLimitSatoshi msg))
    355   , encodeU64 (unMilliSatoshi (openChannelMaxHtlcValueInFlight msg))
    356   , encodeU64 (unSatoshi (openChannelChannelReserveSat msg))
    357   , encodeU64 (unMilliSatoshi (openChannelHtlcMinimumMsat msg))
    358   , encodeU32 (openChannelFeeratePerKw msg)
    359   , encodeU16 (openChannelToSelfDelay msg)
    360   , encodeU16 (openChannelMaxAcceptedHtlcs msg)
    361   , unPoint (openChannelFundingPubkey msg)
    362   , unPoint (openChannelRevocationBasepoint msg)
    363   , unPoint (openChannelPaymentBasepoint msg)
    364   , unPoint (openChannelDelayedPaymentBase msg)
    365   , unPoint (openChannelHtlcBasepoint msg)
    366   , unPoint (openChannelFirstPerCommitPoint msg)
    367   , BS.singleton (openChannelChannelFlags msg)
    368   , encodeTlvStream (openChannelTlvs msg)
    369   ]
    370 
    371 -- | Decode an OpenChannel message (type 32).
    372 decodeOpenChannel
    373   :: BS.ByteString -> Either DecodeError (OpenChannel, BS.ByteString)
    374 decodeOpenChannel !bs = do
    375   (chainHash', rest1) <- decodeChainHashBytes bs
    376   (tempChanId, rest2) <- decodeChannelIdBytes rest1
    377   (fundingSats, rest3) <- decodeSatoshi rest2
    378   (pushMsat, rest4) <- decodeMilliSatoshi rest3
    379   (dustLimit, rest5) <- decodeSatoshi rest4
    380   (maxHtlcVal, rest6) <- decodeMilliSatoshi rest5
    381   (chanReserve, rest7) <- decodeSatoshi rest6
    382   (htlcMin, rest8) <- decodeMilliSatoshi rest7
    383   (feerate, rest9) <- decodeU32E rest8
    384   (toSelfDelay, rest10) <- decodeU16E rest9
    385   (maxHtlcs, rest11) <- decodeU16E rest10
    386   (fundingPk, rest12) <- decodePointBytes rest11
    387   (revocBase, rest13) <- decodePointBytes rest12
    388   (paymentBase, rest14) <- decodePointBytes rest13
    389   (delayedBase, rest15) <- decodePointBytes rest14
    390   (htlcBase, rest16) <- decodePointBytes rest15
    391   (firstCommit, rest17) <- decodePointBytes rest16
    392   (flags, rest18) <- maybe (Left DecodeInsufficientBytes) Right
    393                        (decodeU8 rest17)
    394   tlvs <- decodeTlvs rest18
    395   let !msg = OpenChannel
    396         { openChannelChainHash            = chainHash'
    397         , openChannelTempChannelId        = tempChanId
    398         , openChannelFundingSatoshi      = fundingSats
    399         , openChannelPushMsat             = pushMsat
    400         , openChannelDustLimitSatoshi    = dustLimit
    401         , openChannelMaxHtlcValueInFlight = maxHtlcVal
    402         , openChannelChannelReserveSat    = chanReserve
    403         , openChannelHtlcMinimumMsat      = htlcMin
    404         , openChannelFeeratePerKw         = feerate
    405         , openChannelToSelfDelay          = toSelfDelay
    406         , openChannelMaxAcceptedHtlcs     = maxHtlcs
    407         , openChannelFundingPubkey        = fundingPk
    408         , openChannelRevocationBasepoint  = revocBase
    409         , openChannelPaymentBasepoint     = paymentBase
    410         , openChannelDelayedPaymentBase   = delayedBase
    411         , openChannelHtlcBasepoint        = htlcBase
    412         , openChannelFirstPerCommitPoint  = firstCommit
    413         , openChannelChannelFlags         = flags
    414         , openChannelTlvs                 = tlvs
    415         }
    416   Right (msg, BS.empty)
    417 
    418 -- | Encode an AcceptChannel message (type 33).
    419 --
    420 -- Wire format:
    421 -- - temporary_channel_id: 32 bytes
    422 -- - dust_limit_satoshis: u64
    423 -- - max_htlc_value_in_flight_msat: u64
    424 -- - channel_reserve_satoshis: u64
    425 -- - htlc_minimum_msat: u64
    426 -- - minimum_depth: u32
    427 -- - to_self_delay: u16
    428 -- - max_accepted_htlcs: u16
    429 -- - funding_pubkey: 33 bytes
    430 -- - revocation_basepoint: 33 bytes
    431 -- - payment_basepoint: 33 bytes
    432 -- - delayed_payment_basepoint: 33 bytes
    433 -- - htlc_basepoint: 33 bytes
    434 -- - first_per_commitment_point: 33 bytes
    435 -- - tlvs: TLV stream
    436 encodeAcceptChannel :: AcceptChannel -> BS.ByteString
    437 encodeAcceptChannel !msg = mconcat
    438   [ unChannelId (acceptChannelTempChannelId msg)
    439   , encodeU64 (unSatoshi (acceptChannelDustLimitSatoshi msg))
    440   , encodeU64 (unMilliSatoshi (acceptChannelMaxHtlcValueInFlight msg))
    441   , encodeU64 (unSatoshi (acceptChannelChannelReserveSat msg))
    442   , encodeU64 (unMilliSatoshi (acceptChannelHtlcMinimumMsat msg))
    443   , encodeU32 (acceptChannelMinimumDepth msg)
    444   , encodeU16 (acceptChannelToSelfDelay msg)
    445   , encodeU16 (acceptChannelMaxAcceptedHtlcs msg)
    446   , unPoint (acceptChannelFundingPubkey msg)
    447   , unPoint (acceptChannelRevocationBasepoint msg)
    448   , unPoint (acceptChannelPaymentBasepoint msg)
    449   , unPoint (acceptChannelDelayedPaymentBase msg)
    450   , unPoint (acceptChannelHtlcBasepoint msg)
    451   , unPoint (acceptChannelFirstPerCommitPoint msg)
    452   , encodeTlvStream (acceptChannelTlvs msg)
    453   ]
    454 
    455 -- | Decode an AcceptChannel message (type 33).
    456 decodeAcceptChannel
    457   :: BS.ByteString -> Either DecodeError (AcceptChannel, BS.ByteString)
    458 decodeAcceptChannel !bs = do
    459   (tempChanId, rest1) <- decodeChannelIdBytes bs
    460   (dustLimit, rest2) <- decodeSatoshi rest1
    461   (maxHtlcVal, rest3) <- decodeMilliSatoshi rest2
    462   (chanReserve, rest4) <- decodeSatoshi rest3
    463   (htlcMin, rest5) <- decodeMilliSatoshi rest4
    464   (minDepth, rest6) <- decodeU32E rest5
    465   (toSelfDelay, rest7) <- decodeU16E rest6
    466   (maxHtlcs, rest8) <- decodeU16E rest7
    467   (fundingPk, rest9) <- decodePointBytes rest8
    468   (revocBase, rest10) <- decodePointBytes rest9
    469   (paymentBase, rest11) <- decodePointBytes rest10
    470   (delayedBase, rest12) <- decodePointBytes rest11
    471   (htlcBase, rest13) <- decodePointBytes rest12
    472   (firstCommit, rest14) <- decodePointBytes rest13
    473   tlvs <- decodeTlvs rest14
    474   let !msg = AcceptChannel
    475         { acceptChannelTempChannelId        = tempChanId
    476         , acceptChannelDustLimitSatoshi    = dustLimit
    477         , acceptChannelMaxHtlcValueInFlight = maxHtlcVal
    478         , acceptChannelChannelReserveSat    = chanReserve
    479         , acceptChannelHtlcMinimumMsat      = htlcMin
    480         , acceptChannelMinimumDepth         = minDepth
    481         , acceptChannelToSelfDelay          = toSelfDelay
    482         , acceptChannelMaxAcceptedHtlcs     = maxHtlcs
    483         , acceptChannelFundingPubkey        = fundingPk
    484         , acceptChannelRevocationBasepoint  = revocBase
    485         , acceptChannelPaymentBasepoint     = paymentBase
    486         , acceptChannelDelayedPaymentBase   = delayedBase
    487         , acceptChannelHtlcBasepoint        = htlcBase
    488         , acceptChannelFirstPerCommitPoint  = firstCommit
    489         , acceptChannelTlvs                 = tlvs
    490         }
    491   Right (msg, BS.empty)
    492 
    493 -- | Encode a FundingCreated message (type 34).
    494 --
    495 -- Wire format:
    496 -- - temporary_channel_id: 32 bytes
    497 -- - funding_txid: 32 bytes
    498 -- - funding_output_index: u16
    499 -- - signature: 64 bytes
    500 encodeFundingCreated :: FundingCreated -> BS.ByteString
    501 encodeFundingCreated !msg = mconcat
    502   [ unChannelId (fundingCreatedTempChannelId msg)
    503   , let (TxId bs) = fundingCreatedFundingTxid msg in bs
    504   , encodeU16 (fundingCreatedFundingOutIdx msg)
    505   , unSignature (fundingCreatedSignature msg)
    506   ]
    507 
    508 -- | Decode a FundingCreated message (type 34).
    509 decodeFundingCreated
    510   :: BS.ByteString -> Either DecodeError (FundingCreated, BS.ByteString)
    511 decodeFundingCreated !bs = do
    512   (tempChanId, rest1) <- decodeChannelIdBytes bs
    513   (fundingTxid, rest2) <- decodeTxIdBytes rest1
    514   (outIdx, rest3) <- decodeU16E rest2
    515   (sig, rest4) <- decodeSignatureBytes rest3
    516   let !msg = FundingCreated
    517         { fundingCreatedTempChannelId = tempChanId
    518         , fundingCreatedFundingTxid   = fundingTxid
    519         , fundingCreatedFundingOutIdx = outIdx
    520         , fundingCreatedSignature     = sig
    521         }
    522   Right (msg, rest4)
    523 
    524 -- | Encode a FundingSigned message (type 35).
    525 --
    526 -- Wire format:
    527 -- - channel_id: 32 bytes
    528 -- - signature: 64 bytes
    529 encodeFundingSigned :: FundingSigned -> BS.ByteString
    530 encodeFundingSigned !msg = mconcat
    531   [ unChannelId (fundingSignedChannelId msg)
    532   , unSignature (fundingSignedSignature msg)
    533   ]
    534 
    535 -- | Decode a FundingSigned message (type 35).
    536 decodeFundingSigned
    537   :: BS.ByteString -> Either DecodeError (FundingSigned, BS.ByteString)
    538 decodeFundingSigned !bs = do
    539   (chanId, rest1) <- decodeChannelIdBytes bs
    540   (sig, rest2) <- decodeSignatureBytes rest1
    541   let !msg = FundingSigned
    542         { fundingSignedChannelId = chanId
    543         , fundingSignedSignature = sig
    544         }
    545   Right (msg, rest2)
    546 
    547 -- | Encode a ChannelReady message (type 36).
    548 --
    549 -- Wire format:
    550 -- - channel_id: 32 bytes
    551 -- - second_per_commitment_point: 33 bytes
    552 -- - tlvs: TLV stream
    553 encodeChannelReady :: ChannelReady -> BS.ByteString
    554 encodeChannelReady !msg = mconcat
    555   [ unChannelId (channelReadyChannelId msg)
    556   , unPoint (channelReadySecondPerCommitPoint msg)
    557   , encodeTlvStream (channelReadyTlvs msg)
    558   ]
    559 
    560 -- | Decode a ChannelReady message (type 36).
    561 decodeChannelReady
    562   :: BS.ByteString -> Either DecodeError (ChannelReady, BS.ByteString)
    563 decodeChannelReady !bs = do
    564   (chanId, rest1) <- decodeChannelIdBytes bs
    565   (secondCommit, rest2) <- decodePointBytes rest1
    566   tlvs <- decodeTlvs rest2
    567   let !msg = ChannelReady
    568         { channelReadyChannelId            = chanId
    569         , channelReadySecondPerCommitPoint = secondCommit
    570         , channelReadyTlvs                 = tlvs
    571         }
    572   Right (msg, BS.empty)
    573 
    574 -- Channel close ---------------------------------------------------------------
    575 
    576 -- | Encode a Stfu message (type 2).
    577 --
    578 -- Wire format:
    579 -- - channel_id: 32 bytes
    580 -- - initiator: 1 byte
    581 encodeStfu :: Stfu -> BS.ByteString
    582 encodeStfu !msg = mconcat
    583   [ unChannelId (stfuChannelId msg)
    584   , BS.singleton $! case stfuInitiator msg of
    585       IsInitiator  -> 1
    586       NotInitiator -> 0
    587   ]
    588 
    589 -- | Decode a Stfu message (type 2).
    590 decodeStfu :: BS.ByteString -> Either DecodeError (Stfu, BS.ByteString)
    591 decodeStfu !bs = do
    592   (chanId, rest1) <- decodeChannelIdBytes bs
    593   (raw, rest2) <- maybe (Left DecodeInsufficientBytes) Right
    594                     (decodeU8 rest1)
    595   ini <- case raw of
    596     1 -> Right IsInitiator
    597     0 -> Right NotInitiator
    598     _ -> Left DecodeInvalidInitiator
    599   let !msg = Stfu
    600         { stfuChannelId = chanId
    601         , stfuInitiator = ini
    602         }
    603   Right (msg, rest2)
    604 
    605 -- | Encode a Shutdown message (type 38).
    606 --
    607 -- Wire format:
    608 -- - channel_id: 32 bytes
    609 -- - len: u16
    610 -- - scriptpubkey: len bytes
    611 encodeShutdown :: Shutdown -> Either EncodeError BS.ByteString
    612 encodeShutdown !msg = do
    613   let !script = unScriptPubKey (shutdownScriptPubkey msg)
    614       !scriptLen = BS.length script
    615   if scriptLen > 65535
    616     then Left EncodeLengthOverflow
    617     else Right $ mconcat
    618            [ unChannelId (shutdownChannelId msg)
    619            , encodeU16 (fromIntegral scriptLen)
    620            , script
    621            ]
    622 
    623 -- | Decode a Shutdown message (type 38).
    624 decodeShutdown
    625   :: BS.ByteString -> Either DecodeError (Shutdown, BS.ByteString)
    626 decodeShutdown !bs = do
    627   (chanId, rest1) <- decodeChannelIdBytes bs
    628   (script, rest2) <- decodeScriptPubKey rest1
    629   let !msg = Shutdown
    630         { shutdownChannelId    = chanId
    631         , shutdownScriptPubkey = script
    632         }
    633   Right (msg, rest2)
    634 
    635 -- | Encode a ClosingSigned message (type 39).
    636 --
    637 -- Wire format:
    638 -- - channel_id: 32 bytes
    639 -- - fee_satoshis: u64
    640 -- - signature: 64 bytes
    641 -- - tlvs: TLV stream
    642 encodeClosingSigned :: ClosingSigned -> BS.ByteString
    643 encodeClosingSigned !msg = mconcat
    644   [ unChannelId (closingSignedChannelId msg)
    645   , encodeU64 (unSatoshi (closingSignedFeeSatoshi msg))
    646   , unSignature (closingSignedSignature msg)
    647   , encodeTlvStream (closingSignedTlvs msg)
    648   ]
    649 
    650 -- | Decode a ClosingSigned message (type 39).
    651 decodeClosingSigned
    652   :: BS.ByteString -> Either DecodeError (ClosingSigned, BS.ByteString)
    653 decodeClosingSigned !bs = do
    654   (chanId, rest1) <- decodeChannelIdBytes bs
    655   (feeSats, rest2) <- decodeSatoshi rest1
    656   (sig, rest3) <- decodeSignatureBytes rest2
    657   tlvs <- decodeTlvs rest3
    658   let !msg = ClosingSigned
    659         { closingSignedChannelId   = chanId
    660         , closingSignedFeeSatoshi = feeSats
    661         , closingSignedSignature   = sig
    662         , closingSignedTlvs        = tlvs
    663         }
    664   Right (msg, BS.empty)
    665 
    666 -- | Encode a ClosingComplete message (type 40).
    667 --
    668 -- Wire format:
    669 -- - channel_id: 32 bytes
    670 -- - len: u16 (closer script length)
    671 -- - closer_script: len bytes
    672 -- - len: u16 (closee script length)
    673 -- - closee_script: len bytes
    674 -- - fee_satoshis: u64
    675 -- - locktime: u32
    676 -- - tlvs: TLV stream
    677 encodeClosingComplete :: ClosingComplete -> Either EncodeError BS.ByteString
    678 encodeClosingComplete !msg = do
    679   let !closerScript = unScriptPubKey (closingCompleteCloserScript msg)
    680       !closeeScript = unScriptPubKey (closingCompleteCloseeScript msg)
    681       !closerLen = BS.length closerScript
    682       !closeeLen = BS.length closeeScript
    683   if closerLen > 65535 || closeeLen > 65535
    684     then Left EncodeLengthOverflow
    685     else Right $ mconcat
    686            [ unChannelId (closingCompleteChannelId msg)
    687            , encodeU16 (fromIntegral closerLen)
    688            , closerScript
    689            , encodeU16 (fromIntegral closeeLen)
    690            , closeeScript
    691            , encodeU64 (unSatoshi (closingCompleteFeeSatoshi msg))
    692            , encodeU32 (closingCompleteLocktime msg)
    693            , encodeTlvStream (closingCompleteTlvs msg)
    694            ]
    695 
    696 -- | Decode a ClosingComplete message (type 40).
    697 decodeClosingComplete
    698   :: BS.ByteString -> Either DecodeError (ClosingComplete, BS.ByteString)
    699 decodeClosingComplete !bs = do
    700   (chanId, rest1) <- decodeChannelIdBytes bs
    701   (closerScript, rest2) <- decodeScriptPubKey rest1
    702   (closeeScript, rest3) <- decodeScriptPubKey rest2
    703   (feeSats, rest4) <- decodeSatoshi rest3
    704   (locktime, rest5) <- decodeU32E rest4
    705   tlvs <- decodeTlvs rest5
    706   let !msg = ClosingComplete
    707         { closingCompleteChannelId    = chanId
    708         , closingCompleteCloserScript = closerScript
    709         , closingCompleteCloseeScript = closeeScript
    710         , closingCompleteFeeSatoshi  = feeSats
    711         , closingCompleteLocktime     = locktime
    712         , closingCompleteTlvs         = tlvs
    713         }
    714   Right (msg, BS.empty)
    715 
    716 -- | Encode a ClosingSig message (type 41).
    717 --
    718 -- Wire format:
    719 -- - channel_id: 32 bytes
    720 -- - len: u16 (closer script length)
    721 -- - closer_script: len bytes
    722 -- - len: u16 (closee script length)
    723 -- - closee_script: len bytes
    724 -- - fee_satoshis: u64
    725 -- - locktime: u32
    726 -- - tlvs: TLV stream
    727 encodeClosingSig :: ClosingSig -> Either EncodeError BS.ByteString
    728 encodeClosingSig !msg = do
    729   let !closerScript = unScriptPubKey (closingSigCloserScript msg)
    730       !closeeScript = unScriptPubKey (closingSigCloseeScript msg)
    731       !closerLen = BS.length closerScript
    732       !closeeLen = BS.length closeeScript
    733   if closerLen > 65535 || closeeLen > 65535
    734     then Left EncodeLengthOverflow
    735     else Right $ mconcat
    736            [ unChannelId (closingSigChannelId msg)
    737            , encodeU16 (fromIntegral closerLen)
    738            , closerScript
    739            , encodeU16 (fromIntegral closeeLen)
    740            , closeeScript
    741            , encodeU64 (unSatoshi (closingSigFeeSatoshi msg))
    742            , encodeU32 (closingSigLocktime msg)
    743            , encodeTlvStream (closingSigTlvs msg)
    744            ]
    745 
    746 -- | Decode a ClosingSig message (type 41).
    747 decodeClosingSig
    748   :: BS.ByteString -> Either DecodeError (ClosingSig, BS.ByteString)
    749 decodeClosingSig !bs = do
    750   (chanId, rest1) <- decodeChannelIdBytes bs
    751   (closerScript, rest2) <- decodeScriptPubKey rest1
    752   (closeeScript, rest3) <- decodeScriptPubKey rest2
    753   (feeSats, rest4) <- decodeSatoshi rest3
    754   (locktime, rest5) <- decodeU32E rest4
    755   tlvs <- decodeTlvs rest5
    756   let !msg = ClosingSig
    757         { closingSigChannelId    = chanId
    758         , closingSigCloserScript = closerScript
    759         , closingSigCloseeScript = closeeScript
    760         , closingSigFeeSatoshi  = feeSats
    761         , closingSigLocktime     = locktime
    762         , closingSigTlvs         = tlvs
    763         }
    764   Right (msg, BS.empty)
    765 
    766 -- Channel establishment v2 (interactive-tx) -----------------------------------
    767 
    768 -- | Encode an OpenChannel2 message (type 64).
    769 encodeOpenChannel2 :: OpenChannel2 -> BS.ByteString
    770 encodeOpenChannel2 !msg = mconcat
    771   [ unChainHash (openChannel2ChainHash msg)
    772   , unChannelId (openChannel2TempChannelId msg)
    773   , encodeU32 (openChannel2FundingFeeratePerkw msg)
    774   , encodeU32 (openChannel2CommitFeeratePerkw msg)
    775   , encodeU64 (unSatoshi (openChannel2FundingSatoshi msg))
    776   , encodeU64 (unSatoshi (openChannel2DustLimitSatoshi msg))
    777   , encodeU64 (unMilliSatoshi (openChannel2MaxHtlcValueInFlight msg))
    778   , encodeU64 (unMilliSatoshi (openChannel2HtlcMinimumMsat msg))
    779   , encodeU16 (openChannel2ToSelfDelay msg)
    780   , encodeU16 (openChannel2MaxAcceptedHtlcs msg)
    781   , encodeU32 (openChannel2Locktime msg)
    782   , unPoint (openChannel2FundingPubkey msg)
    783   , unPoint (openChannel2RevocationBasepoint msg)
    784   , unPoint (openChannel2PaymentBasepoint msg)
    785   , unPoint (openChannel2DelayedPaymentBase msg)
    786   , unPoint (openChannel2HtlcBasepoint msg)
    787   , unPoint (openChannel2FirstPerCommitPoint msg)
    788   , unPoint (openChannel2SecondPerCommitPoint msg)
    789   , BS.singleton (openChannel2ChannelFlags msg)
    790   , encodeTlvStream (openChannel2Tlvs msg)
    791   ]
    792 
    793 -- | Decode an OpenChannel2 message (type 64).
    794 decodeOpenChannel2
    795   :: BS.ByteString -> Either DecodeError (OpenChannel2, BS.ByteString)
    796 decodeOpenChannel2 !bs = do
    797   (ch, rest1) <- decodeChainHashBytes bs
    798   (tempCid, rest2) <- decodeChannelIdBytes rest1
    799   (fundingFeerate, rest3) <- decodeU32E rest2
    800   (commitFeerate, rest4) <- decodeU32E rest3
    801   (fundingSats, rest5) <- decodeSatoshi rest4
    802   (dustLimit, rest6) <- decodeSatoshi rest5
    803   (maxHtlcVal, rest7) <- decodeMilliSatoshi rest6
    804   (htlcMin, rest8) <- decodeMilliSatoshi rest7
    805   (toSelfDelay, rest9) <- decodeU16E rest8
    806   (maxHtlcs, rest10) <- decodeU16E rest9
    807   (locktime, rest11) <- decodeU32E rest10
    808   (fundingPk, rest12) <- decodePointBytes rest11
    809   (revBase, rest13) <- decodePointBytes rest12
    810   (payBase, rest14) <- decodePointBytes rest13
    811   (delayBase, rest15) <- decodePointBytes rest14
    812   (htlcBase, rest16) <- decodePointBytes rest15
    813   (firstPt, rest17) <- decodePointBytes rest16
    814   (secondPt, rest18) <- decodePointBytes rest17
    815   (flags, rest19) <- maybe (Left DecodeInsufficientBytes) Right (decodeU8 rest18)
    816   tlvs <- decodeTlvs rest19
    817   let !msg = OpenChannel2
    818         { openChannel2ChainHash            = ch
    819         , openChannel2TempChannelId        = tempCid
    820         , openChannel2FundingFeeratePerkw  = fundingFeerate
    821         , openChannel2CommitFeeratePerkw   = commitFeerate
    822         , openChannel2FundingSatoshi      = fundingSats
    823         , openChannel2DustLimitSatoshi    = dustLimit
    824         , openChannel2MaxHtlcValueInFlight = maxHtlcVal
    825         , openChannel2HtlcMinimumMsat      = htlcMin
    826         , openChannel2ToSelfDelay          = toSelfDelay
    827         , openChannel2MaxAcceptedHtlcs     = maxHtlcs
    828         , openChannel2Locktime             = locktime
    829         , openChannel2FundingPubkey        = fundingPk
    830         , openChannel2RevocationBasepoint  = revBase
    831         , openChannel2PaymentBasepoint     = payBase
    832         , openChannel2DelayedPaymentBase   = delayBase
    833         , openChannel2HtlcBasepoint        = htlcBase
    834         , openChannel2FirstPerCommitPoint  = firstPt
    835         , openChannel2SecondPerCommitPoint = secondPt
    836         , openChannel2ChannelFlags         = flags
    837         , openChannel2Tlvs                 = tlvs
    838         }
    839   Right (msg, BS.empty)
    840 
    841 -- | Encode an AcceptChannel2 message (type 65).
    842 encodeAcceptChannel2 :: AcceptChannel2 -> BS.ByteString
    843 encodeAcceptChannel2 !msg = mconcat
    844   [ unChannelId (acceptChannel2TempChannelId msg)
    845   , encodeU64 (unSatoshi (acceptChannel2FundingSatoshi msg))
    846   , encodeU64 (unSatoshi (acceptChannel2DustLimitSatoshi msg))
    847   , encodeU64 (unMilliSatoshi (acceptChannel2MaxHtlcValueInFlight msg))
    848   , encodeU64 (unMilliSatoshi (acceptChannel2HtlcMinimumMsat msg))
    849   , encodeU32 (acceptChannel2MinimumDepth msg)
    850   , encodeU16 (acceptChannel2ToSelfDelay msg)
    851   , encodeU16 (acceptChannel2MaxAcceptedHtlcs msg)
    852   , unPoint (acceptChannel2FundingPubkey msg)
    853   , unPoint (acceptChannel2RevocationBasepoint msg)
    854   , unPoint (acceptChannel2PaymentBasepoint msg)
    855   , unPoint (acceptChannel2DelayedPaymentBase msg)
    856   , unPoint (acceptChannel2HtlcBasepoint msg)
    857   , unPoint (acceptChannel2FirstPerCommitPoint msg)
    858   , unPoint (acceptChannel2SecondPerCommitPoint msg)
    859   , encodeTlvStream (acceptChannel2Tlvs msg)
    860   ]
    861 
    862 -- | Decode an AcceptChannel2 message (type 65).
    863 decodeAcceptChannel2
    864   :: BS.ByteString -> Either DecodeError (AcceptChannel2, BS.ByteString)
    865 decodeAcceptChannel2 !bs = do
    866   (tempCid, rest1) <- decodeChannelIdBytes bs
    867   (fundingSats, rest2) <- decodeSatoshi rest1
    868   (dustLimit, rest3) <- decodeSatoshi rest2
    869   (maxHtlcVal, rest4) <- decodeMilliSatoshi rest3
    870   (htlcMin, rest5) <- decodeMilliSatoshi rest4
    871   (minDepth, rest6) <- decodeU32E rest5
    872   (toSelfDelay, rest7) <- decodeU16E rest6
    873   (maxHtlcs, rest8) <- decodeU16E rest7
    874   (fundingPk, rest9) <- decodePointBytes rest8
    875   (revBase, rest10) <- decodePointBytes rest9
    876   (payBase, rest11) <- decodePointBytes rest10
    877   (delayBase, rest12) <- decodePointBytes rest11
    878   (htlcBase, rest13) <- decodePointBytes rest12
    879   (firstPt, rest14) <- decodePointBytes rest13
    880   (secondPt, rest15) <- decodePointBytes rest14
    881   tlvs <- decodeTlvs rest15
    882   let !msg = AcceptChannel2
    883         { acceptChannel2TempChannelId        = tempCid
    884         , acceptChannel2FundingSatoshi      = fundingSats
    885         , acceptChannel2DustLimitSatoshi    = dustLimit
    886         , acceptChannel2MaxHtlcValueInFlight = maxHtlcVal
    887         , acceptChannel2HtlcMinimumMsat      = htlcMin
    888         , acceptChannel2MinimumDepth         = minDepth
    889         , acceptChannel2ToSelfDelay          = toSelfDelay
    890         , acceptChannel2MaxAcceptedHtlcs     = maxHtlcs
    891         , acceptChannel2FundingPubkey        = fundingPk
    892         , acceptChannel2RevocationBasepoint  = revBase
    893         , acceptChannel2PaymentBasepoint     = payBase
    894         , acceptChannel2DelayedPaymentBase   = delayBase
    895         , acceptChannel2HtlcBasepoint        = htlcBase
    896         , acceptChannel2FirstPerCommitPoint  = firstPt
    897         , acceptChannel2SecondPerCommitPoint = secondPt
    898         , acceptChannel2Tlvs                 = tlvs
    899         }
    900   Right (msg, BS.empty)
    901 
    902 -- | Encode a TxAddInput message (type 66).
    903 encodeTxAddInput :: TxAddInput -> Either EncodeError BS.ByteString
    904 encodeTxAddInput !msg = do
    905   prevTxEnc <- encodeU16BytesE (txAddInputPrevTx msg)
    906   Right $! mconcat
    907     [ unChannelId (txAddInputChannelId msg)
    908     , encodeU64 (unSerialId (txAddInputSerialId msg))
    909     , prevTxEnc
    910     , encodeU32 (txAddInputPrevVout msg)
    911     , encodeU32 (txAddInputSequence msg)
    912     ]
    913 
    914 -- | Decode a TxAddInput message (type 66).
    915 decodeTxAddInput
    916   :: BS.ByteString -> Either DecodeError (TxAddInput, BS.ByteString)
    917 decodeTxAddInput !bs = do
    918   (cid, rest1) <- decodeChannelIdBytes bs
    919   (sid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
    920                     (decodeU64 rest1)
    921   (prevTx, rest3) <- decodeU16Bytes rest2
    922   (prevVout, rest4) <- decodeU32E rest3
    923   (seqNum, rest5) <- decodeU32E rest4
    924   let !msg = TxAddInput
    925         { txAddInputChannelId = cid
    926         , txAddInputSerialId  = serialId sid
    927         , txAddInputPrevTx    = prevTx
    928         , txAddInputPrevVout  = prevVout
    929         , txAddInputSequence  = seqNum
    930         }
    931   Right (msg, rest5)
    932 
    933 -- | Encode a TxAddOutput message (type 67).
    934 encodeTxAddOutput :: TxAddOutput -> Either EncodeError BS.ByteString
    935 encodeTxAddOutput !msg = do
    936   scriptEnc <- encodeU16BytesE (unScriptPubKey (txAddOutputScript msg))
    937   Right $! mconcat
    938     [ unChannelId (txAddOutputChannelId msg)
    939     , encodeU64 (unSerialId (txAddOutputSerialId msg))
    940     , encodeU64 (unSatoshi (txAddOutputSats msg))
    941     , scriptEnc
    942     ]
    943 
    944 -- | Decode a TxAddOutput message (type 67).
    945 decodeTxAddOutput
    946   :: BS.ByteString -> Either DecodeError (TxAddOutput, BS.ByteString)
    947 decodeTxAddOutput !bs = do
    948   (cid, rest1) <- decodeChannelIdBytes bs
    949   (sid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
    950                     (decodeU64 rest1)
    951   (sats, rest3) <- decodeSatoshi rest2
    952   (scriptBs, rest4) <- decodeU16Bytes rest3
    953   let !msg = TxAddOutput
    954         { txAddOutputChannelId = cid
    955         , txAddOutputSerialId  = serialId sid
    956         , txAddOutputSats      = sats
    957         , txAddOutputScript    = scriptPubKey scriptBs
    958         }
    959   Right (msg, rest4)
    960 
    961 -- | Encode a TxRemoveInput message (type 68).
    962 encodeTxRemoveInput :: TxRemoveInput -> BS.ByteString
    963 encodeTxRemoveInput !msg = mconcat
    964   [ unChannelId (txRemoveInputChannelId msg)
    965   , encodeU64 (unSerialId (txRemoveInputSerialId msg))
    966   ]
    967 
    968 -- | Decode a TxRemoveInput message (type 68).
    969 decodeTxRemoveInput
    970   :: BS.ByteString -> Either DecodeError (TxRemoveInput, BS.ByteString)
    971 decodeTxRemoveInput !bs = do
    972   (cid, rest1) <- decodeChannelIdBytes bs
    973   (sid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
    974                     (decodeU64 rest1)
    975   let !msg = TxRemoveInput
    976         { txRemoveInputChannelId = cid
    977         , txRemoveInputSerialId  = serialId sid
    978         }
    979   Right (msg, rest2)
    980 
    981 -- | Encode a TxRemoveOutput message (type 69).
    982 encodeTxRemoveOutput :: TxRemoveOutput -> BS.ByteString
    983 encodeTxRemoveOutput !msg = mconcat
    984   [ unChannelId (txRemoveOutputChannelId msg)
    985   , encodeU64 (unSerialId (txRemoveOutputSerialId msg))
    986   ]
    987 
    988 -- | Decode a TxRemoveOutput message (type 69).
    989 decodeTxRemoveOutput
    990   :: BS.ByteString -> Either DecodeError (TxRemoveOutput, BS.ByteString)
    991 decodeTxRemoveOutput !bs = do
    992   (cid, rest1) <- decodeChannelIdBytes bs
    993   (sid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
    994                     (decodeU64 rest1)
    995   let !msg = TxRemoveOutput
    996         { txRemoveOutputChannelId = cid
    997         , txRemoveOutputSerialId  = serialId sid
    998         }
    999   Right (msg, rest2)
   1000 
   1001 -- | Encode a TxComplete message (type 70).
   1002 encodeTxComplete :: TxComplete -> BS.ByteString
   1003 encodeTxComplete !msg = unChannelId (txCompleteChannelId msg)
   1004 
   1005 -- | Decode a TxComplete message (type 70).
   1006 decodeTxComplete
   1007   :: BS.ByteString -> Either DecodeError (TxComplete, BS.ByteString)
   1008 decodeTxComplete !bs = do
   1009   (cid, rest) <- decodeChannelIdBytes bs
   1010   let !msg = TxComplete { txCompleteChannelId = cid }
   1011   Right (msg, rest)
   1012 
   1013 -- | Encode a single witness with bounds checking.
   1014 encodeWitnessE :: Witness -> Either EncodeError BS.ByteString
   1015 encodeWitnessE (Witness !wdata) = encodeU16BytesE wdata
   1016 
   1017 -- | Decode a single witness.
   1018 decodeWitness :: BS.ByteString -> Either DecodeError (Witness, BS.ByteString)
   1019 decodeWitness !bs = do
   1020   (wdata, rest) <- decodeU16Bytes bs
   1021   Right (Witness wdata, rest)
   1022 
   1023 -- | Encode a TxSignatures message (type 71).
   1024 encodeTxSignatures :: TxSignatures -> Either EncodeError BS.ByteString
   1025 encodeTxSignatures !msg = do
   1026   let !witnesses = txSignaturesWitnesses msg
   1027   numWit <- checkListCountU16 (length witnesses)
   1028   encodedWits <- traverse encodeWitnessE witnesses
   1029   Right $! mconcat $
   1030     [ unChannelId (txSignaturesChannelId msg)
   1031     , let (TxId bs) = txSignaturesTxid msg in bs
   1032     , encodeU16 numWit
   1033     ] ++ encodedWits
   1034 
   1035 -- | Decode a TxSignatures message (type 71).
   1036 decodeTxSignatures
   1037   :: BS.ByteString -> Either DecodeError (TxSignatures, BS.ByteString)
   1038 decodeTxSignatures !bs = do
   1039   (cid, rest1) <- decodeChannelIdBytes bs
   1040   (tid, rest2) <- decodeTxIdBytes rest1
   1041   (numWit, rest3) <- decodeU16E rest2
   1042   (witnesses, rest4) <- decodeWitnesses (fromIntegral numWit) rest3
   1043   let !msg = TxSignatures
   1044         { txSignaturesChannelId = cid
   1045         , txSignaturesTxid      = tid
   1046         , txSignaturesWitnesses = witnesses
   1047         }
   1048   Right (msg, rest4)
   1049   where
   1050     decodeWitnesses :: Int -> BS.ByteString
   1051                     -> Either DecodeError ([Witness], BS.ByteString)
   1052     decodeWitnesses 0 !rest = Right ([], rest)
   1053     decodeWitnesses !n !rest = do
   1054       (w, rest') <- decodeWitness rest
   1055       (ws, rest'') <- decodeWitnesses (n - 1) rest'
   1056       Right (w : ws, rest'')
   1057 
   1058 -- | Encode a TxInitRbf message (type 72).
   1059 encodeTxInitRbf :: TxInitRbf -> BS.ByteString
   1060 encodeTxInitRbf !msg = mconcat
   1061   [ unChannelId (txInitRbfChannelId msg)
   1062   , encodeU32 (txInitRbfLocktime msg)
   1063   , encodeU32 (txInitRbfFeerate msg)
   1064   , encodeTlvStream (txInitRbfTlvs msg)
   1065   ]
   1066 
   1067 -- | Decode a TxInitRbf message (type 72).
   1068 decodeTxInitRbf
   1069   :: BS.ByteString -> Either DecodeError (TxInitRbf, BS.ByteString)
   1070 decodeTxInitRbf !bs = do
   1071   (cid, rest1) <- decodeChannelIdBytes bs
   1072   (locktime, rest2) <- decodeU32E rest1
   1073   (feerate, rest3) <- decodeU32E rest2
   1074   tlvs <- decodeTlvs rest3
   1075   let !msg = TxInitRbf
   1076         { txInitRbfChannelId = cid
   1077         , txInitRbfLocktime  = locktime
   1078         , txInitRbfFeerate   = feerate
   1079         , txInitRbfTlvs      = tlvs
   1080         }
   1081   Right (msg, BS.empty)
   1082 
   1083 -- | Encode a TxAckRbf message (type 73).
   1084 encodeTxAckRbf :: TxAckRbf -> BS.ByteString
   1085 encodeTxAckRbf !msg = mconcat
   1086   [ unChannelId (txAckRbfChannelId msg)
   1087   , encodeTlvStream (txAckRbfTlvs msg)
   1088   ]
   1089 
   1090 -- | Decode a TxAckRbf message (type 73).
   1091 decodeTxAckRbf
   1092   :: BS.ByteString -> Either DecodeError (TxAckRbf, BS.ByteString)
   1093 decodeTxAckRbf !bs = do
   1094   (cid, rest1) <- decodeChannelIdBytes bs
   1095   tlvs <- decodeTlvs rest1
   1096   let !msg = TxAckRbf
   1097         { txAckRbfChannelId = cid
   1098         , txAckRbfTlvs      = tlvs
   1099         }
   1100   Right (msg, BS.empty)
   1101 
   1102 -- | Encode a TxAbort message (type 74).
   1103 encodeTxAbort :: TxAbort -> Either EncodeError BS.ByteString
   1104 encodeTxAbort !msg = do
   1105   dataEnc <- encodeU16BytesE (txAbortData msg)
   1106   Right $! mconcat
   1107     [ unChannelId (txAbortChannelId msg)
   1108     , dataEnc
   1109     ]
   1110 
   1111 -- | Decode a TxAbort message (type 74).
   1112 decodeTxAbort
   1113   :: BS.ByteString -> Either DecodeError (TxAbort, BS.ByteString)
   1114 decodeTxAbort !bs = do
   1115   (cid, rest1) <- decodeChannelIdBytes bs
   1116   (dat, rest2) <- decodeU16Bytes rest1
   1117   let !msg = TxAbort
   1118         { txAbortChannelId = cid
   1119         , txAbortData      = dat
   1120         }
   1121   Right (msg, rest2)
   1122 
   1123 -- Normal operation ------------------------------------------------------------
   1124 
   1125 -- | Encode an UpdateAddHtlc message (type 128).
   1126 encodeUpdateAddHtlc :: UpdateAddHtlc -> BS.ByteString
   1127 encodeUpdateAddHtlc !m = mconcat
   1128   [ unChannelId (updateAddHtlcChannelId m)
   1129   , encodeU64 (unHtlcId (updateAddHtlcId m))
   1130   , encodeU64 (unMilliSatoshi (updateAddHtlcAmountMsat m))
   1131   , unPaymentHash (updateAddHtlcPaymentHash m)
   1132   , encodeU32 (updateAddHtlcCltvExpiry m)
   1133   , unOnionPacket (updateAddHtlcOnionPacket m)
   1134   , encodeTlvStream (updateAddHtlcTlvs m)
   1135   ]
   1136 {-# INLINABLE encodeUpdateAddHtlc #-}
   1137 
   1138 -- | Decode an UpdateAddHtlc message (type 128).
   1139 decodeUpdateAddHtlc
   1140   :: BS.ByteString -> Either DecodeError (UpdateAddHtlc, BS.ByteString)
   1141 decodeUpdateAddHtlc !bs = do
   1142   (cid, rest1) <- decodeChannelIdBytes bs
   1143   (hid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
   1144                     (decodeU64 rest1)
   1145   (amtMsat, rest3) <- maybe (Left DecodeInsufficientBytes) Right
   1146                         (decodeU64 rest2)
   1147   (pHash, rest4) <- decodePaymentHashBytes rest3
   1148   (cltvExp, rest5) <- decodeU32E rest4
   1149   (onion, rest6) <- decodeOnionPacketBytes rest5
   1150   (tlvs, rest7) <- decodeOptionalTlvs rest6
   1151   let !msg = UpdateAddHtlc
   1152         { updateAddHtlcChannelId   = cid
   1153         , updateAddHtlcId          = htlcId hid
   1154         , updateAddHtlcAmountMsat  = MilliSatoshi amtMsat
   1155         , updateAddHtlcPaymentHash = pHash
   1156         , updateAddHtlcCltvExpiry  = cltvExp
   1157         , updateAddHtlcOnionPacket = onion
   1158         , updateAddHtlcTlvs        = tlvs
   1159         }
   1160   Right (msg, rest7)
   1161 {-# INLINABLE decodeUpdateAddHtlc #-}
   1162 
   1163 -- | Encode an UpdateFulfillHtlc message (type 130).
   1164 encodeUpdateFulfillHtlc :: UpdateFulfillHtlc -> BS.ByteString
   1165 encodeUpdateFulfillHtlc !m = mconcat
   1166   [ unChannelId (updateFulfillHtlcChannelId m)
   1167   , encodeU64 (unHtlcId (updateFulfillHtlcId m))
   1168   , unPaymentPreimage (updateFulfillHtlcPaymentPreimage m)
   1169   , encodeTlvStream (updateFulfillHtlcTlvs m)
   1170   ]
   1171 
   1172 -- | Decode an UpdateFulfillHtlc message (type 130).
   1173 decodeUpdateFulfillHtlc
   1174   :: BS.ByteString -> Either DecodeError (UpdateFulfillHtlc, BS.ByteString)
   1175 decodeUpdateFulfillHtlc !bs = do
   1176   (cid, rest1) <- decodeChannelIdBytes bs
   1177   (hid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
   1178                     (decodeU64 rest1)
   1179   (preimage, rest3) <- decodePaymentPreimageBytes rest2
   1180   (tlvs, rest4) <- decodeOptionalTlvs rest3
   1181   let !msg = UpdateFulfillHtlc
   1182         { updateFulfillHtlcChannelId       = cid
   1183         , updateFulfillHtlcId              = htlcId hid
   1184         , updateFulfillHtlcPaymentPreimage = preimage
   1185         , updateFulfillHtlcTlvs            = tlvs
   1186         }
   1187   Right (msg, rest4)
   1188 
   1189 -- | Encode an UpdateFailHtlc message (type 131).
   1190 encodeUpdateFailHtlc :: UpdateFailHtlc -> Either EncodeError BS.ByteString
   1191 encodeUpdateFailHtlc !m = do
   1192   reasonEnc <- encodeU16BytesE (updateFailHtlcReason m)
   1193   Right $! mconcat
   1194     [ unChannelId (updateFailHtlcChannelId m)
   1195     , encodeU64 (unHtlcId (updateFailHtlcId m))
   1196     , reasonEnc
   1197     , encodeTlvStream (updateFailHtlcTlvs m)
   1198     ]
   1199 
   1200 -- | Decode an UpdateFailHtlc message (type 131).
   1201 decodeUpdateFailHtlc
   1202   :: BS.ByteString -> Either DecodeError (UpdateFailHtlc, BS.ByteString)
   1203 decodeUpdateFailHtlc !bs = do
   1204   (cid, rest1) <- decodeChannelIdBytes bs
   1205   (hid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
   1206                     (decodeU64 rest1)
   1207   (reason, rest3) <- decodeU16Bytes rest2
   1208   (tlvs, rest4) <- decodeOptionalTlvs rest3
   1209   let !msg = UpdateFailHtlc
   1210         { updateFailHtlcChannelId = cid
   1211         , updateFailHtlcId        = htlcId hid
   1212         , updateFailHtlcReason    = reason
   1213         , updateFailHtlcTlvs      = tlvs
   1214         }
   1215   Right (msg, rest4)
   1216 
   1217 -- | Encode an UpdateFailMalformedHtlc message (type 135).
   1218 encodeUpdateFailMalformedHtlc :: UpdateFailMalformedHtlc -> BS.ByteString
   1219 encodeUpdateFailMalformedHtlc !m = mconcat
   1220   [ unChannelId (updateFailMalformedHtlcChannelId m)
   1221   , encodeU64 (unHtlcId (updateFailMalformedHtlcId m))
   1222   , unPaymentHash (updateFailMalformedHtlcSha256Onion m)
   1223   , encodeU16 (updateFailMalformedHtlcFailureCode m)
   1224   ]
   1225 
   1226 -- | Decode an UpdateFailMalformedHtlc message (type 135).
   1227 decodeUpdateFailMalformedHtlc
   1228   :: BS.ByteString -> Either DecodeError (UpdateFailMalformedHtlc, BS.ByteString)
   1229 decodeUpdateFailMalformedHtlc !bs = do
   1230   (cid, rest1) <- decodeChannelIdBytes bs
   1231   (hid, rest2) <- maybe (Left DecodeInsufficientBytes) Right
   1232                     (decodeU64 rest1)
   1233   (sha256Onion, rest3) <- decodePaymentHashBytes rest2
   1234   (failCode, rest4) <- decodeU16E rest3
   1235   let !msg = UpdateFailMalformedHtlc
   1236         { updateFailMalformedHtlcChannelId   = cid
   1237         , updateFailMalformedHtlcId          = htlcId hid
   1238         , updateFailMalformedHtlcSha256Onion = sha256Onion
   1239         , updateFailMalformedHtlcFailureCode = failCode
   1240         }
   1241   Right (msg, rest4)
   1242 
   1243 -- | Encode a CommitmentSigned message (type 132).
   1244 encodeCommitmentSigned :: CommitmentSigned -> Either EncodeError BS.ByteString
   1245 encodeCommitmentSigned !m = do
   1246   let !sigs = commitmentSignedHtlcSignatures m
   1247   numHtlcs <- checkListCountU16 (length sigs)
   1248   Right $! mconcat $
   1249     [ unChannelId (commitmentSignedChannelId m)
   1250     , unSignature (commitmentSignedSignature m)
   1251     , encodeU16 numHtlcs
   1252     ] ++ map unSignature sigs
   1253 {-# INLINABLE encodeCommitmentSigned #-}
   1254 
   1255 -- | Decode a CommitmentSigned message (type 132).
   1256 decodeCommitmentSigned
   1257   :: BS.ByteString -> Either DecodeError (CommitmentSigned, BS.ByteString)
   1258 decodeCommitmentSigned !bs = do
   1259   (cid, rest1) <- decodeChannelIdBytes bs
   1260   (sig, rest2) <- decodeSignatureBytes rest1
   1261   (numHtlcs, rest3) <- decodeU16E rest2
   1262   (htlcSigs, rest4) <- decodeSignatures (fromIntegral numHtlcs) rest3
   1263   let !msg = CommitmentSigned
   1264         { commitmentSignedChannelId      = cid
   1265         , commitmentSignedSignature      = sig
   1266         , commitmentSignedHtlcSignatures = htlcSigs
   1267         }
   1268   Right (msg, rest4)
   1269   where
   1270     decodeSignatures :: Int -> BS.ByteString
   1271                      -> Either DecodeError ([Signature], BS.ByteString)
   1272     decodeSignatures !n !input = go n input []
   1273       where
   1274         go :: Int -> BS.ByteString -> [Signature]
   1275            -> Either DecodeError ([Signature], BS.ByteString)
   1276         go 0 !remaining !acc = Right (reverse acc, remaining)
   1277         go !count !remaining !acc = do
   1278           (s, rest) <- decodeSignatureBytes remaining
   1279           go (count - 1) rest (s : acc)
   1280 {-# INLINABLE decodeCommitmentSigned #-}
   1281 
   1282 -- | Encode a RevokeAndAck message (type 133).
   1283 encodeRevokeAndAck :: RevokeAndAck -> BS.ByteString
   1284 encodeRevokeAndAck !m = mconcat
   1285   [ unChannelId (revokeAndAckChannelId m)
   1286   , unPerCommitmentSecret (revokeAndAckPerCommitmentSecret m)
   1287   , unPoint (revokeAndAckNextPerCommitPoint m)
   1288   ]
   1289 
   1290 -- | Decode a RevokeAndAck message (type 133).
   1291 decodeRevokeAndAck
   1292   :: BS.ByteString -> Either DecodeError (RevokeAndAck, BS.ByteString)
   1293 decodeRevokeAndAck !bs = do
   1294   (cid, rest1) <- decodeChannelIdBytes bs
   1295   (sec, rest2) <- decodePerCommitmentSecretBytes rest1
   1296   (nextPoint, rest3) <- decodePointBytes rest2
   1297   let !msg = RevokeAndAck
   1298         { revokeAndAckChannelId           = cid
   1299         , revokeAndAckPerCommitmentSecret = sec
   1300         , revokeAndAckNextPerCommitPoint  = nextPoint
   1301         }
   1302   Right (msg, rest3)
   1303 
   1304 -- | Encode an UpdateFee message (type 134).
   1305 encodeUpdateFee :: UpdateFee -> BS.ByteString
   1306 encodeUpdateFee !m = mconcat
   1307   [ unChannelId (updateFeeChannelId m)
   1308   , encodeU32 (updateFeeFeeratePerKw m)
   1309   ]
   1310 
   1311 -- | Decode an UpdateFee message (type 134).
   1312 decodeUpdateFee
   1313   :: BS.ByteString -> Either DecodeError (UpdateFee, BS.ByteString)
   1314 decodeUpdateFee !bs = do
   1315   (cid, rest1) <- decodeChannelIdBytes bs
   1316   (feerate, rest2) <- decodeU32E rest1
   1317   let !msg = UpdateFee
   1318         { updateFeeChannelId    = cid
   1319         , updateFeeFeeratePerKw = feerate
   1320         }
   1321   Right (msg, rest2)
   1322 
   1323 -- Channel reestablishment -----------------------------------------------------
   1324 
   1325 -- | Encode a ChannelReestablish message (type 136).
   1326 encodeChannelReestablish :: ChannelReestablish -> BS.ByteString
   1327 encodeChannelReestablish !m = mconcat
   1328   [ unChannelId (channelReestablishChannelId m)
   1329   , encodeU64 (channelReestablishNextCommitNum m)
   1330   , encodeU64 (channelReestablishNextRevocationNum m)
   1331   , unPerCommitmentSecret (channelReestablishYourLastCommitSecret m)
   1332   , unPoint (channelReestablishMyCurrentCommitPoint m)
   1333   , encodeTlvStream (channelReestablishTlvs m)
   1334   ]
   1335 
   1336 -- | Decode a ChannelReestablish message (type 136).
   1337 decodeChannelReestablish
   1338   :: BS.ByteString -> Either DecodeError (ChannelReestablish, BS.ByteString)
   1339 decodeChannelReestablish !bs = do
   1340   (cid, rest1) <- decodeChannelIdBytes bs
   1341   (nextCommit, rest2) <- maybe (Left DecodeInsufficientBytes) Right
   1342                            (decodeU64 rest1)
   1343   (nextRevoke, rest3) <- maybe (Left DecodeInsufficientBytes) Right
   1344                            (decodeU64 rest2)
   1345   (sec, rest4) <- decodePerCommitmentSecretBytes rest3
   1346   (myPoint, rest5) <- decodePointBytes rest4
   1347   (tlvs, rest6) <- decodeOptionalTlvs rest5
   1348   let !msg = ChannelReestablish
   1349         { channelReestablishChannelId            = cid
   1350         , channelReestablishNextCommitNum        = nextCommit
   1351         , channelReestablishNextRevocationNum    = nextRevoke
   1352         , channelReestablishYourLastCommitSecret = sec
   1353         , channelReestablishMyCurrentCommitPoint = myPoint
   1354         , channelReestablishTlvs                 = tlvs
   1355         }
   1356   Right (msg, rest6)