Support paying blinded paths.
[rust-lightning] / lightning / src / ln / msgs.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Wire messages, traits representing wire message handlers, and a few error types live here.
11 //!
12 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
13 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
14 //! server entirely) which handles only channel-related messages you may wish to implement
15 //! [`ChannelMessageHandler`] yourself and use it to re-serialize messages and pass them across
16 //! daemons/servers.
17 //!
18 //! Note that if you go with such an architecture (instead of passing raw socket events to a
19 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
20 //! source `node_id` of the message, however this does allow you to significantly reduce bandwidth
21 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
22 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
23 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
24 //! raw socket events into your non-internet-facing system and then send routing events back to
25 //! track the network on the less-secure system.
26
27 use bitcoin::blockdata::constants::ChainHash;
28 use bitcoin::secp256k1::PublicKey;
29 use bitcoin::secp256k1::ecdsa::Signature;
30 use bitcoin::{secp256k1, Witness};
31 use bitcoin::blockdata::script::Script;
32 use bitcoin::hash_types::{Txid, BlockHash};
33
34 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
35 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
36 use crate::ln::onion_utils;
37 use crate::onion_message;
38
39 use crate::prelude::*;
40 use core::convert::TryFrom;
41 use core::fmt;
42 use core::fmt::Debug;
43 use core::str::FromStr;
44 use crate::io::{self, Read};
45 use crate::io_extras::read_to_end;
46
47 use crate::events::{MessageSendEventsProvider, OnionMessageProvider};
48 use crate::util::logger;
49 use crate::util::ser::{LengthReadable, Readable, ReadableArgs, Writeable, Writer, WithoutLength, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, TransactionU16LenLimited, BigSize};
50 use crate::util::base32;
51
52 use crate::routing::gossip::{NodeAlias, NodeId};
53
54 /// 21 million * 10^8 * 1000
55 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
56
57 #[cfg(taproot)]
58 /// A partial signature that also contains the Musig2 nonce its signer used
59 #[derive(Clone, Debug, PartialEq, Eq)]
60 pub struct PartialSignatureWithNonce(pub musig2::types::PartialSignature, pub musig2::types::PublicNonce);
61
62 /// An error in decoding a message or struct.
63 #[derive(Clone, Debug, PartialEq, Eq)]
64 pub enum DecodeError {
65         /// A version byte specified something we don't know how to handle.
66         ///
67         /// Includes unknown realm byte in an onion hop data packet.
68         UnknownVersion,
69         /// Unknown feature mandating we fail to parse message (e.g., TLV with an even, unknown type)
70         UnknownRequiredFeature,
71         /// Value was invalid.
72         ///
73         /// For example, a byte which was supposed to be a bool was something other than a 0
74         /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was
75         /// syntactically incorrect, etc.
76         InvalidValue,
77         /// The buffer to be read was too short.
78         ShortRead,
79         /// A length descriptor in the packet didn't describe the later data correctly.
80         BadLengthDescriptor,
81         /// Error from [`std::io`].
82         Io(io::ErrorKind),
83         /// The message included zlib-compressed values, which we don't support.
84         UnsupportedCompression,
85 }
86
87 /// An [`init`] message to be sent to or received from a peer.
88 ///
89 /// [`init`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-init-message
90 #[derive(Clone, Debug, PartialEq, Eq)]
91 pub struct Init {
92         /// The relevant features which the sender supports.
93         pub features: InitFeatures,
94         /// Indicates chains the sender is interested in.
95         ///
96         /// If there are no common chains, the connection will be closed.
97         pub networks: Option<Vec<ChainHash>>,
98         /// The receipient's network address.
99         ///
100         /// This adds the option to report a remote IP address back to a connecting peer using the init
101         /// message. A node can decide to use that information to discover a potential update to its
102         /// public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing
103         /// the new address.
104         pub remote_network_address: Option<SocketAddress>,
105 }
106
107 /// An [`error`] message to be sent to or received from a peer.
108 ///
109 /// [`error`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages
110 #[derive(Clone, Debug, PartialEq, Eq)]
111 pub struct ErrorMessage {
112         /// The channel ID involved in the error.
113         ///
114         /// All-0s indicates a general error unrelated to a specific channel, after which all channels
115         /// with the sending peer should be closed.
116         pub channel_id: ChannelId,
117         /// A possibly human-readable error description.
118         ///
119         /// The string should be sanitized before it is used (e.g., emitted to logs or printed to
120         /// `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in
121         /// the terminal emulator or the logging subsystem.
122         pub data: String,
123 }
124
125 /// A [`warning`] message to be sent to or received from a peer.
126 ///
127 /// [`warning`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages
128 #[derive(Clone, Debug, PartialEq, Eq)]
129 pub struct WarningMessage {
130         /// The channel ID involved in the warning.
131         ///
132         /// All-0s indicates a warning unrelated to a specific channel.
133         pub channel_id: ChannelId,
134         /// A possibly human-readable warning description.
135         ///
136         /// The string should be sanitized before it is used (e.g. emitted to logs or printed to
137         /// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in
138         /// the terminal emulator or the logging subsystem.
139         pub data: String,
140 }
141
142 /// A [`ping`] message to be sent to or received from a peer.
143 ///
144 /// [`ping`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages
145 #[derive(Clone, Debug, PartialEq, Eq)]
146 pub struct Ping {
147         /// The desired response length.
148         pub ponglen: u16,
149         /// The ping packet size.
150         ///
151         /// This field is not sent on the wire. byteslen zeros are sent.
152         pub byteslen: u16,
153 }
154
155 /// A [`pong`] message to be sent to or received from a peer.
156 ///
157 /// [`pong`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages
158 #[derive(Clone, Debug, PartialEq, Eq)]
159 pub struct Pong {
160         /// The pong packet size.
161         ///
162         /// This field is not sent on the wire. byteslen zeros are sent.
163         pub byteslen: u16,
164 }
165
166 /// An [`open_channel`] message to be sent to or received from a peer.
167 ///
168 /// Used in V1 channel establishment
169 ///
170 /// [`open_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message
171 #[derive(Clone, Debug, PartialEq, Eq)]
172 pub struct OpenChannel {
173         /// The genesis hash of the blockchain where the channel is to be opened
174         pub chain_hash: BlockHash,
175         /// A temporary channel ID, until the funding outpoint is announced
176         pub temporary_channel_id: ChannelId,
177         /// The channel value
178         pub funding_satoshis: u64,
179         /// The amount to push to the counterparty as part of the open, in milli-satoshi
180         pub push_msat: u64,
181         /// The threshold below which outputs on transactions broadcast by sender will be omitted
182         pub dust_limit_satoshis: u64,
183         /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
184         pub max_htlc_value_in_flight_msat: u64,
185         /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
186         pub channel_reserve_satoshis: u64,
187         /// The minimum HTLC size incoming to sender, in milli-satoshi
188         pub htlc_minimum_msat: u64,
189         /// The feerate per 1000-weight of sender generated transactions, until updated by
190         /// [`UpdateFee`]
191         pub feerate_per_kw: u32,
192         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if
193         /// they broadcast a commitment transaction
194         pub to_self_delay: u16,
195         /// The maximum number of inbound HTLCs towards sender
196         pub max_accepted_htlcs: u16,
197         /// The sender's key controlling the funding transaction
198         pub funding_pubkey: PublicKey,
199         /// Used to derive a revocation key for transactions broadcast by counterparty
200         pub revocation_basepoint: PublicKey,
201         /// A payment key to sender for transactions broadcast by counterparty
202         pub payment_point: PublicKey,
203         /// Used to derive a payment key to sender for transactions broadcast by sender
204         pub delayed_payment_basepoint: PublicKey,
205         /// Used to derive an HTLC payment key to sender
206         pub htlc_basepoint: PublicKey,
207         /// The first to-be-broadcast-by-sender transaction's per commitment point
208         pub first_per_commitment_point: PublicKey,
209         /// The channel flags to be used
210         pub channel_flags: u8,
211         /// A request to pre-set the to-sender output's `scriptPubkey` for when we collaboratively close
212         pub shutdown_scriptpubkey: Option<Script>,
213         /// The channel type that this channel will represent
214         ///
215         /// If this is `None`, we derive the channel type from the intersection of our
216         /// feature bits with our counterparty's feature bits from the [`Init`] message.
217         pub channel_type: Option<ChannelTypeFeatures>,
218 }
219
220 /// An open_channel2 message to be sent by or received from the channel initiator.
221 ///
222 /// Used in V2 channel establishment
223 ///
224 // TODO(dual_funding): Add spec link for `open_channel2`.
225 #[derive(Clone, Debug, PartialEq, Eq)]
226 pub struct OpenChannelV2 {
227         /// The genesis hash of the blockchain where the channel is to be opened
228         pub chain_hash: BlockHash,
229         /// A temporary channel ID derived using a zeroed out value for the channel acceptor's revocation basepoint
230         pub temporary_channel_id: ChannelId,
231         /// The feerate for the funding transaction set by the channel initiator
232         pub funding_feerate_sat_per_1000_weight: u32,
233         /// The feerate for the commitment transaction set by the channel initiator
234         pub commitment_feerate_sat_per_1000_weight: u32,
235         /// Part of the channel value contributed by the channel initiator
236         pub funding_satoshis: u64,
237         /// The threshold below which outputs on transactions broadcast by the channel initiator will be
238         /// omitted
239         pub dust_limit_satoshis: u64,
240         /// The maximum inbound HTLC value in flight towards channel initiator, in milli-satoshi
241         pub max_htlc_value_in_flight_msat: u64,
242         /// The minimum HTLC size incoming to channel initiator, in milli-satoshi
243         pub htlc_minimum_msat: u64,
244         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they
245         /// broadcast a commitment transaction
246         pub to_self_delay: u16,
247         /// The maximum number of inbound HTLCs towards channel initiator
248         pub max_accepted_htlcs: u16,
249         /// The locktime for the funding transaction
250         pub locktime: u32,
251         /// The channel initiator's key controlling the funding transaction
252         pub funding_pubkey: PublicKey,
253         /// Used to derive a revocation key for transactions broadcast by counterparty
254         pub revocation_basepoint: PublicKey,
255         /// A payment key to channel initiator for transactions broadcast by counterparty
256         pub payment_basepoint: PublicKey,
257         /// Used to derive a payment key to channel initiator for transactions broadcast by channel
258         /// initiator
259         pub delayed_payment_basepoint: PublicKey,
260         /// Used to derive an HTLC payment key to channel initiator
261         pub htlc_basepoint: PublicKey,
262         /// The first to-be-broadcast-by-channel-initiator transaction's per commitment point
263         pub first_per_commitment_point: PublicKey,
264         /// The second to-be-broadcast-by-channel-initiator transaction's per commitment point
265         pub second_per_commitment_point: PublicKey,
266         /// Channel flags
267         pub channel_flags: u8,
268         /// Optionally, a request to pre-set the to-channel-initiator output's scriptPubkey for when we
269         /// collaboratively close
270         pub shutdown_scriptpubkey: Option<Script>,
271         /// The channel type that this channel will represent. If none is set, we derive the channel
272         /// type from the intersection of our feature bits with our counterparty's feature bits from
273         /// the Init message.
274         pub channel_type: Option<ChannelTypeFeatures>,
275         /// Optionally, a requirement that only confirmed inputs can be added
276         pub require_confirmed_inputs: Option<()>,
277 }
278
279 /// An [`accept_channel`] message to be sent to or received from a peer.
280 ///
281 /// Used in V1 channel establishment
282 ///
283 /// [`accept_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel-message
284 #[derive(Clone, Debug, PartialEq, Eq)]
285 pub struct AcceptChannel {
286         /// A temporary channel ID, until the funding outpoint is announced
287         pub temporary_channel_id: ChannelId,
288         /// The threshold below which outputs on transactions broadcast by sender will be omitted
289         pub dust_limit_satoshis: u64,
290         /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
291         pub max_htlc_value_in_flight_msat: u64,
292         /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
293         pub channel_reserve_satoshis: u64,
294         /// The minimum HTLC size incoming to sender, in milli-satoshi
295         pub htlc_minimum_msat: u64,
296         /// Minimum depth of the funding transaction before the channel is considered open
297         pub minimum_depth: u32,
298         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
299         pub to_self_delay: u16,
300         /// The maximum number of inbound HTLCs towards sender
301         pub max_accepted_htlcs: u16,
302         /// The sender's key controlling the funding transaction
303         pub funding_pubkey: PublicKey,
304         /// Used to derive a revocation key for transactions broadcast by counterparty
305         pub revocation_basepoint: PublicKey,
306         /// A payment key to sender for transactions broadcast by counterparty
307         pub payment_point: PublicKey,
308         /// Used to derive a payment key to sender for transactions broadcast by sender
309         pub delayed_payment_basepoint: PublicKey,
310         /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
311         pub htlc_basepoint: PublicKey,
312         /// The first to-be-broadcast-by-sender transaction's per commitment point
313         pub first_per_commitment_point: PublicKey,
314         /// A request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
315         pub shutdown_scriptpubkey: Option<Script>,
316         /// The channel type that this channel will represent.
317         ///
318         /// If this is `None`, we derive the channel type from the intersection of
319         /// our feature bits with our counterparty's feature bits from the [`Init`] message.
320         /// This is required to match the equivalent field in [`OpenChannel::channel_type`].
321         pub channel_type: Option<ChannelTypeFeatures>,
322         #[cfg(taproot)]
323         /// Next nonce the channel initiator should use to create a funding output signature against
324         pub next_local_nonce: Option<musig2::types::PublicNonce>,
325 }
326
327 /// An accept_channel2 message to be sent by or received from the channel accepter.
328 ///
329 /// Used in V2 channel establishment
330 ///
331 // TODO(dual_funding): Add spec link for `accept_channel2`.
332 #[derive(Clone, Debug, PartialEq, Eq)]
333 pub struct AcceptChannelV2 {
334         /// The same `temporary_channel_id` received from the initiator's `open_channel2` message.
335         pub temporary_channel_id: ChannelId,
336         /// Part of the channel value contributed by the channel acceptor
337         pub funding_satoshis: u64,
338         /// The threshold below which outputs on transactions broadcast by the channel acceptor will be
339         /// omitted
340         pub dust_limit_satoshis: u64,
341         /// The maximum inbound HTLC value in flight towards channel acceptor, in milli-satoshi
342         pub max_htlc_value_in_flight_msat: u64,
343         /// The minimum HTLC size incoming to channel acceptor, in milli-satoshi
344         pub htlc_minimum_msat: u64,
345         /// Minimum depth of the funding transaction before the channel is considered open
346         pub minimum_depth: u32,
347         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they
348         /// broadcast a commitment transaction
349         pub to_self_delay: u16,
350         /// The maximum number of inbound HTLCs towards channel acceptor
351         pub max_accepted_htlcs: u16,
352         /// The channel acceptor's key controlling the funding transaction
353         pub funding_pubkey: PublicKey,
354         /// Used to derive a revocation key for transactions broadcast by counterparty
355         pub revocation_basepoint: PublicKey,
356         /// A payment key to channel acceptor for transactions broadcast by counterparty
357         pub payment_basepoint: PublicKey,
358         /// Used to derive a payment key to channel acceptor for transactions broadcast by channel
359         /// acceptor
360         pub delayed_payment_basepoint: PublicKey,
361         /// Used to derive an HTLC payment key to channel acceptor for transactions broadcast by counterparty
362         pub htlc_basepoint: PublicKey,
363         /// The first to-be-broadcast-by-channel-acceptor transaction's per commitment point
364         pub first_per_commitment_point: PublicKey,
365         /// The second to-be-broadcast-by-channel-acceptor transaction's per commitment point
366         pub second_per_commitment_point: PublicKey,
367         /// Optionally, a request to pre-set the to-channel-acceptor output's scriptPubkey for when we
368         /// collaboratively close
369         pub shutdown_scriptpubkey: Option<Script>,
370         /// The channel type that this channel will represent. If none is set, we derive the channel
371         /// type from the intersection of our feature bits with our counterparty's feature bits from
372         /// the Init message.
373         ///
374         /// This is required to match the equivalent field in [`OpenChannelV2::channel_type`].
375         pub channel_type: Option<ChannelTypeFeatures>,
376         /// Optionally, a requirement that only confirmed inputs can be added
377         pub require_confirmed_inputs: Option<()>,
378 }
379
380 /// A [`funding_created`] message to be sent to or received from a peer.
381 ///
382 /// Used in V1 channel establishment
383 ///
384 /// [`funding_created`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_created-message
385 #[derive(Clone, Debug, PartialEq, Eq)]
386 pub struct FundingCreated {
387         /// A temporary channel ID, until the funding is established
388         pub temporary_channel_id: ChannelId,
389         /// The funding transaction ID
390         pub funding_txid: Txid,
391         /// The specific output index funding this channel
392         pub funding_output_index: u16,
393         /// The signature of the channel initiator (funder) on the initial commitment transaction
394         pub signature: Signature,
395         #[cfg(taproot)]
396         /// The partial signature of the channel initiator (funder)
397         pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
398         #[cfg(taproot)]
399         /// Next nonce the channel acceptor should use to finalize the funding output signature
400         pub next_local_nonce: Option<musig2::types::PublicNonce>
401 }
402
403 /// A [`funding_signed`] message to be sent to or received from a peer.
404 ///
405 /// Used in V1 channel establishment
406 ///
407 /// [`funding_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_signed-message
408 #[derive(Clone, Debug, PartialEq, Eq)]
409 pub struct FundingSigned {
410         /// The channel ID
411         pub channel_id: ChannelId,
412         /// The signature of the channel acceptor (fundee) on the initial commitment transaction
413         pub signature: Signature,
414         #[cfg(taproot)]
415         /// The partial signature of the channel acceptor (fundee)
416         pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
417 }
418
419 /// A [`channel_ready`] message to be sent to or received from a peer.
420 ///
421 /// [`channel_ready`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message
422 #[derive(Clone, Debug, PartialEq, Eq)]
423 pub struct ChannelReady {
424         /// The channel ID
425         pub channel_id: ChannelId,
426         /// The per-commitment point of the second commitment transaction
427         pub next_per_commitment_point: PublicKey,
428         /// If set, provides a `short_channel_id` alias for this channel.
429         ///
430         /// The sender will accept payments to be forwarded over this SCID and forward them to this
431         /// messages' recipient.
432         pub short_channel_id_alias: Option<u64>,
433 }
434
435 /// A tx_add_input message for adding an input during interactive transaction construction
436 ///
437 // TODO(dual_funding): Add spec link for `tx_add_input`.
438 #[derive(Clone, Debug, PartialEq, Eq)]
439 pub struct TxAddInput {
440         /// The channel ID
441         pub channel_id: ChannelId,
442         /// A randomly chosen unique identifier for this input, which is even for initiators and odd for
443         /// non-initiators.
444         pub serial_id: u64,
445         /// Serialized transaction that contains the output this input spends to verify that it is non
446         /// malleable.
447         pub prevtx: TransactionU16LenLimited,
448         /// The index of the output being spent
449         pub prevtx_out: u32,
450         /// The sequence number of this input
451         pub sequence: u32,
452 }
453
454 /// A tx_add_output message for adding an output during interactive transaction construction.
455 ///
456 // TODO(dual_funding): Add spec link for `tx_add_output`.
457 #[derive(Clone, Debug, PartialEq, Eq)]
458 pub struct TxAddOutput {
459         /// The channel ID
460         pub channel_id: ChannelId,
461         /// A randomly chosen unique identifier for this output, which is even for initiators and odd for
462         /// non-initiators.
463         pub serial_id: u64,
464         /// The satoshi value of the output
465         pub sats: u64,
466         /// The scriptPubKey for the output
467         pub script: Script,
468 }
469
470 /// A tx_remove_input message for removing an input during interactive transaction construction.
471 ///
472 // TODO(dual_funding): Add spec link for `tx_remove_input`.
473 #[derive(Clone, Debug, PartialEq, Eq)]
474 pub struct TxRemoveInput {
475         /// The channel ID
476         pub channel_id: ChannelId,
477         /// The serial ID of the input to be removed
478         pub serial_id: u64,
479 }
480
481 /// A tx_remove_output message for removing an output during interactive transaction construction.
482 ///
483 // TODO(dual_funding): Add spec link for `tx_remove_output`.
484 #[derive(Clone, Debug, PartialEq, Eq)]
485 pub struct TxRemoveOutput {
486         /// The channel ID
487         pub channel_id: ChannelId,
488         /// The serial ID of the output to be removed
489         pub serial_id: u64,
490 }
491
492 /// A tx_complete message signalling the conclusion of a peer's transaction contributions during
493 /// interactive transaction construction.
494 ///
495 // TODO(dual_funding): Add spec link for `tx_complete`.
496 #[derive(Clone, Debug, PartialEq, Eq)]
497 pub struct TxComplete {
498         /// The channel ID
499         pub channel_id: ChannelId,
500 }
501
502 /// A tx_signatures message containing the sender's signatures for a transaction constructed with
503 /// interactive transaction construction.
504 ///
505 // TODO(dual_funding): Add spec link for `tx_signatures`.
506 #[derive(Clone, Debug, PartialEq, Eq)]
507 pub struct TxSignatures {
508         /// The channel ID
509         pub channel_id: ChannelId,
510         /// The TXID
511         pub tx_hash: Txid,
512         /// The list of witnesses
513         pub witnesses: Vec<Witness>,
514 }
515
516 /// A tx_init_rbf message which initiates a replacement of the transaction after it's been
517 /// completed.
518 ///
519 // TODO(dual_funding): Add spec link for `tx_init_rbf`.
520 #[derive(Clone, Debug, PartialEq, Eq)]
521 pub struct TxInitRbf {
522         /// The channel ID
523         pub channel_id: ChannelId,
524         /// The locktime of the transaction
525         pub locktime: u32,
526         /// The feerate of the transaction
527         pub feerate_sat_per_1000_weight: u32,
528         /// The number of satoshis the sender will contribute to or, if negative, remove from
529         /// (e.g. splice-out) the funding output of the transaction
530         pub funding_output_contribution: Option<i64>,
531 }
532
533 /// A tx_ack_rbf message which acknowledges replacement of the transaction after it's been
534 /// completed.
535 ///
536 // TODO(dual_funding): Add spec link for `tx_ack_rbf`.
537 #[derive(Clone, Debug, PartialEq, Eq)]
538 pub struct TxAckRbf {
539         /// The channel ID
540         pub channel_id: ChannelId,
541         /// The number of satoshis the sender will contribute to or, if negative, remove from
542         /// (e.g. splice-out) the funding output of the transaction
543         pub funding_output_contribution: Option<i64>,
544 }
545
546 /// A tx_abort message which signals the cancellation of an in-progress transaction negotiation.
547 ///
548 // TODO(dual_funding): Add spec link for `tx_abort`.
549 #[derive(Clone, Debug, PartialEq, Eq)]
550 pub struct TxAbort {
551         /// The channel ID
552         pub channel_id: ChannelId,
553         /// Message data
554         pub data: Vec<u8>,
555 }
556
557 /// A [`shutdown`] message to be sent to or received from a peer.
558 ///
559 /// [`shutdown`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-initiation-shutdown
560 #[derive(Clone, Debug, PartialEq, Eq)]
561 pub struct Shutdown {
562         /// The channel ID
563         pub channel_id: ChannelId,
564         /// The destination of this peer's funds on closing.
565         ///
566         /// Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR.
567         pub scriptpubkey: Script,
568 }
569
570 /// The minimum and maximum fees which the sender is willing to place on the closing transaction.
571 ///
572 /// This is provided in [`ClosingSigned`] by both sides to indicate the fee range they are willing
573 /// to use.
574 #[derive(Clone, Debug, PartialEq, Eq)]
575 pub struct ClosingSignedFeeRange {
576         /// The minimum absolute fee, in satoshis, which the sender is willing to place on the closing
577         /// transaction.
578         pub min_fee_satoshis: u64,
579         /// The maximum absolute fee, in satoshis, which the sender is willing to place on the closing
580         /// transaction.
581         pub max_fee_satoshis: u64,
582 }
583
584 /// A [`closing_signed`] message to be sent to or received from a peer.
585 ///
586 /// [`closing_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_signed
587 #[derive(Clone, Debug, PartialEq, Eq)]
588 pub struct ClosingSigned {
589         /// The channel ID
590         pub channel_id: ChannelId,
591         /// The proposed total fee for the closing transaction
592         pub fee_satoshis: u64,
593         /// A signature on the closing transaction
594         pub signature: Signature,
595         /// The minimum and maximum fees which the sender is willing to accept, provided only by new
596         /// nodes.
597         pub fee_range: Option<ClosingSignedFeeRange>,
598 }
599
600 /// An [`update_add_htlc`] message to be sent to or received from a peer.
601 ///
602 /// [`update_add_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc
603 #[derive(Clone, Debug, PartialEq, Eq)]
604 pub struct UpdateAddHTLC {
605         /// The channel ID
606         pub channel_id: ChannelId,
607         /// The HTLC ID
608         pub htlc_id: u64,
609         /// The HTLC value in milli-satoshi
610         pub amount_msat: u64,
611         /// The payment hash, the pre-image of which controls HTLC redemption
612         pub payment_hash: PaymentHash,
613         /// The expiry height of the HTLC
614         pub cltv_expiry: u32,
615         /// The extra fee skimmed by the sender of this message. See
616         /// [`ChannelConfig::accept_underpaying_htlcs`].
617         ///
618         /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
619         pub skimmed_fee_msat: Option<u64>,
620         pub(crate) onion_routing_packet: OnionPacket,
621 }
622
623  /// An onion message to be sent to or received from a peer.
624  ///
625  // TODO: update with link to OM when they are merged into the BOLTs
626 #[derive(Clone, Debug, PartialEq, Eq)]
627 pub struct OnionMessage {
628         /// Used in decrypting the onion packet's payload.
629         pub blinding_point: PublicKey,
630         pub(crate) onion_routing_packet: onion_message::Packet,
631 }
632
633 /// An [`update_fulfill_htlc`] message to be sent to or received from a peer.
634 ///
635 /// [`update_fulfill_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc
636 #[derive(Clone, Debug, PartialEq, Eq)]
637 pub struct UpdateFulfillHTLC {
638         /// The channel ID
639         pub channel_id: ChannelId,
640         /// The HTLC ID
641         pub htlc_id: u64,
642         /// The pre-image of the payment hash, allowing HTLC redemption
643         pub payment_preimage: PaymentPreimage,
644 }
645
646 /// An [`update_fail_htlc`] message to be sent to or received from a peer.
647 ///
648 /// [`update_fail_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc
649 #[derive(Clone, Debug, PartialEq, Eq)]
650 pub struct UpdateFailHTLC {
651         /// The channel ID
652         pub channel_id: ChannelId,
653         /// The HTLC ID
654         pub htlc_id: u64,
655         pub(crate) reason: OnionErrorPacket,
656 }
657
658 /// An [`update_fail_malformed_htlc`] message to be sent to or received from a peer.
659 ///
660 /// [`update_fail_malformed_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc
661 #[derive(Clone, Debug, PartialEq, Eq)]
662 pub struct UpdateFailMalformedHTLC {
663         /// The channel ID
664         pub channel_id: ChannelId,
665         /// The HTLC ID
666         pub htlc_id: u64,
667         pub(crate) sha256_of_onion: [u8; 32],
668         /// The failure code
669         pub failure_code: u16,
670 }
671
672 /// A [`commitment_signed`] message to be sent to or received from a peer.
673 ///
674 /// [`commitment_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#committing-updates-so-far-commitment_signed
675 #[derive(Clone, Debug, PartialEq, Eq)]
676 pub struct CommitmentSigned {
677         /// The channel ID
678         pub channel_id: ChannelId,
679         /// A signature on the commitment transaction
680         pub signature: Signature,
681         /// Signatures on the HTLC transactions
682         pub htlc_signatures: Vec<Signature>,
683         #[cfg(taproot)]
684         /// The partial Taproot signature on the commitment transaction
685         pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
686 }
687
688 /// A [`revoke_and_ack`] message to be sent to or received from a peer.
689 ///
690 /// [`revoke_and_ack`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#completing-the-transition-to-the-updated-state-revoke_and_ack
691 #[derive(Clone, Debug, PartialEq, Eq)]
692 pub struct RevokeAndACK {
693         /// The channel ID
694         pub channel_id: ChannelId,
695         /// The secret corresponding to the per-commitment point
696         pub per_commitment_secret: [u8; 32],
697         /// The next sender-broadcast commitment transaction's per-commitment point
698         pub next_per_commitment_point: PublicKey,
699         #[cfg(taproot)]
700         /// Musig nonce the recipient should use in their next commitment signature message
701         pub next_local_nonce: Option<musig2::types::PublicNonce>
702 }
703
704 /// An [`update_fee`] message to be sent to or received from a peer
705 ///
706 /// [`update_fee`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#updating-fees-update_fee
707 #[derive(Clone, Debug, PartialEq, Eq)]
708 pub struct UpdateFee {
709         /// The channel ID
710         pub channel_id: ChannelId,
711         /// Fee rate per 1000-weight of the transaction
712         pub feerate_per_kw: u32,
713 }
714
715 /// A [`channel_reestablish`] message to be sent to or received from a peer.
716 ///
717 /// [`channel_reestablish`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#message-retransmission
718 #[derive(Clone, Debug, PartialEq, Eq)]
719 pub struct ChannelReestablish {
720         /// The channel ID
721         pub channel_id: ChannelId,
722         /// The next commitment number for the sender
723         pub next_local_commitment_number: u64,
724         /// The next commitment number for the recipient
725         pub next_remote_commitment_number: u64,
726         /// Proof that the sender knows the per-commitment secret of a specific commitment transaction
727         /// belonging to the recipient
728         pub your_last_per_commitment_secret: [u8; 32],
729         /// The sender's per-commitment point for their current commitment transaction
730         pub my_current_per_commitment_point: PublicKey,
731         /// The next funding transaction ID
732         pub next_funding_txid: Option<Txid>,
733 }
734
735 /// An [`announcement_signatures`] message to be sent to or received from a peer.
736 ///
737 /// [`announcement_signatures`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message
738 #[derive(Clone, Debug, PartialEq, Eq)]
739 pub struct AnnouncementSignatures {
740         /// The channel ID
741         pub channel_id: ChannelId,
742         /// The short channel ID
743         pub short_channel_id: u64,
744         /// A signature by the node key
745         pub node_signature: Signature,
746         /// A signature by the funding key
747         pub bitcoin_signature: Signature,
748 }
749
750 /// An address which can be used to connect to a remote peer.
751 #[derive(Clone, Debug, PartialEq, Eq)]
752 pub enum SocketAddress {
753         /// An IPv4 address and port on which the peer is listening.
754         TcpIpV4 {
755                 /// The 4-byte IPv4 address
756                 addr: [u8; 4],
757                 /// The port on which the node is listening
758                 port: u16,
759         },
760         /// An IPv6 address and port on which the peer is listening.
761         TcpIpV6 {
762                 /// The 16-byte IPv6 address
763                 addr: [u8; 16],
764                 /// The port on which the node is listening
765                 port: u16,
766         },
767         /// An old-style Tor onion address/port on which the peer is listening.
768         ///
769         /// This field is deprecated and the Tor network generally no longer supports V2 Onion
770         /// addresses. Thus, the details are not parsed here.
771         OnionV2([u8; 12]),
772         /// A new-style Tor onion address/port on which the peer is listening.
773         ///
774         /// To create the human-readable "hostname", concatenate the ED25519 pubkey, checksum, and version,
775         /// wrap as base32 and append ".onion".
776         OnionV3 {
777                 /// The ed25519 long-term public key of the peer
778                 ed25519_pubkey: [u8; 32],
779                 /// The checksum of the pubkey and version, as included in the onion address
780                 checksum: u16,
781                 /// The version byte, as defined by the Tor Onion v3 spec.
782                 version: u8,
783                 /// The port on which the node is listening
784                 port: u16,
785         },
786         /// A hostname/port on which the peer is listening.
787         Hostname {
788                 /// The hostname on which the node is listening.
789                 hostname: Hostname,
790                 /// The port on which the node is listening.
791                 port: u16,
792         },
793 }
794 impl SocketAddress {
795         /// Gets the ID of this address type. Addresses in [`NodeAnnouncement`] messages should be sorted
796         /// by this.
797         pub(crate) fn get_id(&self) -> u8 {
798                 match self {
799                         &SocketAddress::TcpIpV4 {..} => { 1 },
800                         &SocketAddress::TcpIpV6 {..} => { 2 },
801                         &SocketAddress::OnionV2(_) => { 3 },
802                         &SocketAddress::OnionV3 {..} => { 4 },
803                         &SocketAddress::Hostname {..} => { 5 },
804                 }
805         }
806
807         /// Strict byte-length of address descriptor, 1-byte type not recorded
808         fn len(&self) -> u16 {
809                 match self {
810                         &SocketAddress::TcpIpV4 { .. } => { 6 },
811                         &SocketAddress::TcpIpV6 { .. } => { 18 },
812                         &SocketAddress::OnionV2(_) => { 12 },
813                         &SocketAddress::OnionV3 { .. } => { 37 },
814                         // Consists of 1-byte hostname length, hostname bytes, and 2-byte port.
815                         &SocketAddress::Hostname { ref hostname, .. } => { u16::from(hostname.len()) + 3 },
816                 }
817         }
818
819         /// The maximum length of any address descriptor, not including the 1-byte type.
820         /// This maximum length is reached by a hostname address descriptor:
821         /// a hostname with a maximum length of 255, its 1-byte length and a 2-byte port.
822         pub(crate) const MAX_LEN: u16 = 258;
823 }
824
825 impl Writeable for SocketAddress {
826         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
827                 match self {
828                         &SocketAddress::TcpIpV4 { ref addr, ref port } => {
829                                 1u8.write(writer)?;
830                                 addr.write(writer)?;
831                                 port.write(writer)?;
832                         },
833                         &SocketAddress::TcpIpV6 { ref addr, ref port } => {
834                                 2u8.write(writer)?;
835                                 addr.write(writer)?;
836                                 port.write(writer)?;
837                         },
838                         &SocketAddress::OnionV2(bytes) => {
839                                 3u8.write(writer)?;
840                                 bytes.write(writer)?;
841                         },
842                         &SocketAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
843                                 4u8.write(writer)?;
844                                 ed25519_pubkey.write(writer)?;
845                                 checksum.write(writer)?;
846                                 version.write(writer)?;
847                                 port.write(writer)?;
848                         },
849                         &SocketAddress::Hostname { ref hostname, ref port } => {
850                                 5u8.write(writer)?;
851                                 hostname.write(writer)?;
852                                 port.write(writer)?;
853                         },
854                 }
855                 Ok(())
856         }
857 }
858
859 impl Readable for Result<SocketAddress, u8> {
860         fn read<R: Read>(reader: &mut R) -> Result<Result<SocketAddress, u8>, DecodeError> {
861                 let byte = <u8 as Readable>::read(reader)?;
862                 match byte {
863                         1 => {
864                                 Ok(Ok(SocketAddress::TcpIpV4 {
865                                         addr: Readable::read(reader)?,
866                                         port: Readable::read(reader)?,
867                                 }))
868                         },
869                         2 => {
870                                 Ok(Ok(SocketAddress::TcpIpV6 {
871                                         addr: Readable::read(reader)?,
872                                         port: Readable::read(reader)?,
873                                 }))
874                         },
875                         3 => Ok(Ok(SocketAddress::OnionV2(Readable::read(reader)?))),
876                         4 => {
877                                 Ok(Ok(SocketAddress::OnionV3 {
878                                         ed25519_pubkey: Readable::read(reader)?,
879                                         checksum: Readable::read(reader)?,
880                                         version: Readable::read(reader)?,
881                                         port: Readable::read(reader)?,
882                                 }))
883                         },
884                         5 => {
885                                 Ok(Ok(SocketAddress::Hostname {
886                                         hostname: Readable::read(reader)?,
887                                         port: Readable::read(reader)?,
888                                 }))
889                         },
890                         _ => return Ok(Err(byte)),
891                 }
892         }
893 }
894
895 impl Readable for SocketAddress {
896         fn read<R: Read>(reader: &mut R) -> Result<SocketAddress, DecodeError> {
897                 match Readable::read(reader) {
898                         Ok(Ok(res)) => Ok(res),
899                         Ok(Err(_)) => Err(DecodeError::UnknownVersion),
900                         Err(e) => Err(e),
901                 }
902         }
903 }
904
905 /// [`SocketAddress`] error variants
906 #[derive(Debug, Eq, PartialEq, Clone)]
907 pub enum SocketAddressParseError {
908         /// Socket address (IPv4/IPv6) parsing error
909         SocketAddrParse,
910         /// Invalid input format
911         InvalidInput,
912         /// Invalid port
913         InvalidPort,
914         /// Invalid onion v3 address
915         InvalidOnionV3,
916 }
917
918 impl fmt::Display for SocketAddressParseError {
919         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
920                 match self {
921                         SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"),
922                         SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \
923                                 Expected: \"<ipv4>:<port>\", \"[<ipv6>]:<port>\", \"<onion address>.onion:<port>\" or \"<hostname>:<port>\""),
924                         SocketAddressParseError::InvalidPort => write!(f, "Invalid port"),
925                         SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"),
926                 }
927         }
928 }
929
930 #[cfg(feature = "std")]
931 impl From<std::net::SocketAddrV4> for SocketAddress {
932                 fn from(addr: std::net::SocketAddrV4) -> Self {
933                         SocketAddress::TcpIpV4 { addr: addr.ip().octets(), port: addr.port() }
934                 }
935 }
936
937 #[cfg(feature = "std")]
938 impl From<std::net::SocketAddrV6> for SocketAddress {
939                 fn from(addr: std::net::SocketAddrV6) -> Self {
940                         SocketAddress::TcpIpV6 { addr: addr.ip().octets(), port: addr.port() }
941                 }
942 }
943
944 #[cfg(feature = "std")]
945 impl From<std::net::SocketAddr> for SocketAddress {
946                 fn from(addr: std::net::SocketAddr) -> Self {
947                         match addr {
948                                 std::net::SocketAddr::V4(addr) => addr.into(),
949                                 std::net::SocketAddr::V6(addr) => addr.into(),
950                         }
951                 }
952 }
953
954 fn parse_onion_address(host: &str, port: u16) -> Result<SocketAddress, SocketAddressParseError> {
955         if host.ends_with(".onion") {
956                 let domain = &host[..host.len() - ".onion".len()];
957                 if domain.len() != 56 {
958                         return Err(SocketAddressParseError::InvalidOnionV3);
959                 }
960                 let onion =  base32::Alphabet::RFC4648 { padding: false }.decode(&domain).map_err(|_| SocketAddressParseError::InvalidOnionV3)?;
961                 if onion.len() != 35 {
962                         return Err(SocketAddressParseError::InvalidOnionV3);
963                 }
964                 let version = onion[0];
965                 let first_checksum_flag = onion[1];
966                 let second_checksum_flag = onion[2];
967                 let mut ed25519_pubkey = [0; 32];
968                 ed25519_pubkey.copy_from_slice(&onion[3..35]);
969                 let checksum = u16::from_be_bytes([first_checksum_flag, second_checksum_flag]);
970                 return Ok(SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port });
971
972         } else {
973                 return Err(SocketAddressParseError::InvalidInput);
974         }
975 }
976
977 #[cfg(feature = "std")]
978 impl FromStr for SocketAddress {
979         type Err = SocketAddressParseError;
980
981         fn from_str(s: &str) -> Result<Self, Self::Err> {
982                 match std::net::SocketAddr::from_str(s) {
983                         Ok(addr) => Ok(addr.into()),
984                         Err(_) => {
985                                 let trimmed_input = match s.rfind(":") {
986                                         Some(pos) => pos,
987                                         None => return Err(SocketAddressParseError::InvalidInput),
988                                 };
989                                 let host = &s[..trimmed_input];
990                                 let port: u16 = s[trimmed_input + 1..].parse().map_err(|_| SocketAddressParseError::InvalidPort)?;
991                                 if host.ends_with(".onion") {
992                                         return parse_onion_address(host, port);
993                                 };
994                                 if let Ok(hostname) = Hostname::try_from(s[..trimmed_input].to_string()) {
995                                         return Ok(SocketAddress::Hostname { hostname, port });
996                                 };
997                                 return Err(SocketAddressParseError::SocketAddrParse)
998                         },
999                 }
1000         }
1001 }
1002
1003 /// Represents the set of gossip messages that require a signature from a node's identity key.
1004 pub enum UnsignedGossipMessage<'a> {
1005         /// An unsigned channel announcement.
1006         ChannelAnnouncement(&'a UnsignedChannelAnnouncement),
1007         /// An unsigned channel update.
1008         ChannelUpdate(&'a UnsignedChannelUpdate),
1009         /// An unsigned node announcement.
1010         NodeAnnouncement(&'a UnsignedNodeAnnouncement)
1011 }
1012
1013 impl<'a> Writeable for UnsignedGossipMessage<'a> {
1014         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1015                 match self {
1016                         UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer),
1017                         UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer),
1018                         UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer),
1019                 }
1020         }
1021 }
1022
1023 /// The unsigned part of a [`node_announcement`] message.
1024 ///
1025 /// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message
1026 #[derive(Clone, Debug, PartialEq, Eq)]
1027 pub struct UnsignedNodeAnnouncement {
1028         /// The advertised features
1029         pub features: NodeFeatures,
1030         /// A strictly monotonic announcement counter, with gaps allowed
1031         pub timestamp: u32,
1032         /// The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back
1033         /// to this node).
1034         pub node_id: NodeId,
1035         /// An RGB color for UI purposes
1036         pub rgb: [u8; 3],
1037         /// An alias, for UI purposes.
1038         ///
1039         /// This should be sanitized before use. There is no guarantee of uniqueness.
1040         pub alias: NodeAlias,
1041         /// List of addresses on which this node is reachable
1042         pub addresses: Vec<SocketAddress>,
1043         pub(crate) excess_address_data: Vec<u8>,
1044         pub(crate) excess_data: Vec<u8>,
1045 }
1046 #[derive(Clone, Debug, PartialEq, Eq)]
1047 /// A [`node_announcement`] message to be sent to or received from a peer.
1048 ///
1049 /// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message
1050 pub struct NodeAnnouncement {
1051         /// The signature by the node key
1052         pub signature: Signature,
1053         /// The actual content of the announcement
1054         pub contents: UnsignedNodeAnnouncement,
1055 }
1056
1057 /// The unsigned part of a [`channel_announcement`] message.
1058 ///
1059 /// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
1060 #[derive(Clone, Debug, PartialEq, Eq)]
1061 pub struct UnsignedChannelAnnouncement {
1062         /// The advertised channel features
1063         pub features: ChannelFeatures,
1064         /// The genesis hash of the blockchain where the channel is to be opened
1065         pub chain_hash: BlockHash,
1066         /// The short channel ID
1067         pub short_channel_id: u64,
1068         /// One of the two `node_id`s which are endpoints of this channel
1069         pub node_id_1: NodeId,
1070         /// The other of the two `node_id`s which are endpoints of this channel
1071         pub node_id_2: NodeId,
1072         /// The funding key for the first node
1073         pub bitcoin_key_1: NodeId,
1074         /// The funding key for the second node
1075         pub bitcoin_key_2: NodeId,
1076         /// Excess data which was signed as a part of the message which we do not (yet) understand how
1077         /// to decode.
1078         ///
1079         /// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol.
1080         pub excess_data: Vec<u8>,
1081 }
1082 /// A [`channel_announcement`] message to be sent to or received from a peer.
1083 ///
1084 /// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
1085 #[derive(Clone, Debug, PartialEq, Eq)]
1086 pub struct ChannelAnnouncement {
1087         /// Authentication of the announcement by the first public node
1088         pub node_signature_1: Signature,
1089         /// Authentication of the announcement by the second public node
1090         pub node_signature_2: Signature,
1091         /// Proof of funding UTXO ownership by the first public node
1092         pub bitcoin_signature_1: Signature,
1093         /// Proof of funding UTXO ownership by the second public node
1094         pub bitcoin_signature_2: Signature,
1095         /// The actual announcement
1096         pub contents: UnsignedChannelAnnouncement,
1097 }
1098
1099 /// The unsigned part of a [`channel_update`] message.
1100 ///
1101 /// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
1102 #[derive(Clone, Debug, PartialEq, Eq)]
1103 pub struct UnsignedChannelUpdate {
1104         /// The genesis hash of the blockchain where the channel is to be opened
1105         pub chain_hash: BlockHash,
1106         /// The short channel ID
1107         pub short_channel_id: u64,
1108         /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
1109         pub timestamp: u32,
1110         /// Channel flags
1111         pub flags: u8,
1112         /// The number of blocks such that if:
1113         /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta`
1114         /// then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines
1115         /// the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a
1116         /// `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10,
1117         /// then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before
1118         /// forwarding. Note that the HTLC sender is the one who originally sets this value when
1119         /// constructing the route.
1120         pub cltv_expiry_delta: u16,
1121         /// The minimum HTLC size incoming to sender, in milli-satoshi
1122         pub htlc_minimum_msat: u64,
1123         /// The maximum HTLC value incoming to sender, in milli-satoshi.
1124         ///
1125         /// This used to be optional.
1126         pub htlc_maximum_msat: u64,
1127         /// The base HTLC fee charged by sender, in milli-satoshi
1128         pub fee_base_msat: u32,
1129         /// The amount to fee multiplier, in micro-satoshi
1130         pub fee_proportional_millionths: u32,
1131         /// Excess data which was signed as a part of the message which we do not (yet) understand how
1132         /// to decode.
1133         ///
1134         /// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol.
1135         pub excess_data: Vec<u8>,
1136 }
1137 /// A [`channel_update`] message to be sent to or received from a peer.
1138 ///
1139 /// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
1140 #[derive(Clone, Debug, PartialEq, Eq)]
1141 pub struct ChannelUpdate {
1142         /// A signature of the channel update
1143         pub signature: Signature,
1144         /// The actual channel update
1145         pub contents: UnsignedChannelUpdate,
1146 }
1147
1148 /// A [`query_channel_range`] message is used to query a peer for channel
1149 /// UTXOs in a range of blocks. The recipient of a query makes a best
1150 /// effort to reply to the query using one or more [`ReplyChannelRange`]
1151 /// messages.
1152 ///
1153 /// [`query_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages
1154 #[derive(Clone, Debug, PartialEq, Eq)]
1155 pub struct QueryChannelRange {
1156         /// The genesis hash of the blockchain being queried
1157         pub chain_hash: BlockHash,
1158         /// The height of the first block for the channel UTXOs being queried
1159         pub first_blocknum: u32,
1160         /// The number of blocks to include in the query results
1161         pub number_of_blocks: u32,
1162 }
1163
1164 /// A [`reply_channel_range`] message is a reply to a [`QueryChannelRange`]
1165 /// message.
1166 ///
1167 /// Multiple `reply_channel_range` messages can be sent in reply
1168 /// to a single [`QueryChannelRange`] message. The query recipient makes a
1169 /// best effort to respond based on their local network view which may
1170 /// not be a perfect view of the network. The `short_channel_id`s in the
1171 /// reply are encoded. We only support `encoding_type=0` uncompressed
1172 /// serialization and do not support `encoding_type=1` zlib serialization.
1173 ///
1174 /// [`reply_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages
1175 #[derive(Clone, Debug, PartialEq, Eq)]
1176 pub struct ReplyChannelRange {
1177         /// The genesis hash of the blockchain being queried
1178         pub chain_hash: BlockHash,
1179         /// The height of the first block in the range of the reply
1180         pub first_blocknum: u32,
1181         /// The number of blocks included in the range of the reply
1182         pub number_of_blocks: u32,
1183         /// True when this is the final reply for a query
1184         pub sync_complete: bool,
1185         /// The `short_channel_id`s in the channel range
1186         pub short_channel_ids: Vec<u64>,
1187 }
1188
1189 /// A [`query_short_channel_ids`] message is used to query a peer for
1190 /// routing gossip messages related to one or more `short_channel_id`s.
1191 ///
1192 /// The query recipient will reply with the latest, if available,
1193 /// [`ChannelAnnouncement`], [`ChannelUpdate`] and [`NodeAnnouncement`] messages
1194 /// it maintains for the requested `short_channel_id`s followed by a
1195 /// [`ReplyShortChannelIdsEnd`] message. The `short_channel_id`s sent in
1196 /// this query are encoded. We only support `encoding_type=0` uncompressed
1197 /// serialization and do not support `encoding_type=1` zlib serialization.
1198 ///
1199 /// [`query_short_channel_ids`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages
1200 #[derive(Clone, Debug, PartialEq, Eq)]
1201 pub struct QueryShortChannelIds {
1202         /// The genesis hash of the blockchain being queried
1203         pub chain_hash: BlockHash,
1204         /// The short_channel_ids that are being queried
1205         pub short_channel_ids: Vec<u64>,
1206 }
1207
1208 /// A [`reply_short_channel_ids_end`] message is sent as a reply to a
1209 /// message. The query recipient makes a best
1210 /// effort to respond based on their local network view which may not be
1211 /// a perfect view of the network.
1212 ///
1213 /// [`reply_short_channel_ids_end`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages
1214 #[derive(Clone, Debug, PartialEq, Eq)]
1215 pub struct ReplyShortChannelIdsEnd {
1216         /// The genesis hash of the blockchain that was queried
1217         pub chain_hash: BlockHash,
1218         /// Indicates if the query recipient maintains up-to-date channel
1219         /// information for the `chain_hash`
1220         pub full_information: bool,
1221 }
1222
1223 /// A [`gossip_timestamp_filter`] message is used by a node to request
1224 /// gossip relay for messages in the requested time range when the
1225 /// `gossip_queries` feature has been negotiated.
1226 ///
1227 /// [`gossip_timestamp_filter`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-gossip_timestamp_filter-message
1228 #[derive(Clone, Debug, PartialEq, Eq)]
1229 pub struct GossipTimestampFilter {
1230         /// The genesis hash of the blockchain for channel and node information
1231         pub chain_hash: BlockHash,
1232         /// The starting unix timestamp
1233         pub first_timestamp: u32,
1234         /// The range of information in seconds
1235         pub timestamp_range: u32,
1236 }
1237
1238 /// Encoding type for data compression of collections in gossip queries.
1239 ///
1240 /// We do not support `encoding_type=1` zlib serialization [defined in BOLT
1241 /// #7](https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages).
1242 enum EncodingType {
1243         Uncompressed = 0x00,
1244 }
1245
1246 /// Used to put an error message in a [`LightningError`].
1247 #[derive(Clone, Debug, PartialEq)]
1248 pub enum ErrorAction {
1249         /// The peer took some action which made us think they were useless. Disconnect them.
1250         DisconnectPeer {
1251                 /// An error message which we should make an effort to send before we disconnect.
1252                 msg: Option<ErrorMessage>
1253         },
1254         /// The peer did something incorrect. Tell them without closing any channels and disconnect them.
1255         DisconnectPeerWithWarning {
1256                 /// A warning message which we should make an effort to send before we disconnect.
1257                 msg: WarningMessage,
1258         },
1259         /// The peer did something harmless that we weren't able to process, just log and ignore
1260         // New code should *not* use this. New code must use IgnoreAndLog, below!
1261         IgnoreError,
1262         /// The peer did something harmless that we weren't able to meaningfully process.
1263         /// If the error is logged, log it at the given level.
1264         IgnoreAndLog(logger::Level),
1265         /// The peer provided us with a gossip message which we'd already seen. In most cases this
1266         /// should be ignored, but it may result in the message being forwarded if it is a duplicate of
1267         /// our own channel announcements.
1268         IgnoreDuplicateGossip,
1269         /// The peer did something incorrect. Tell them.
1270         SendErrorMessage {
1271                 /// The message to send.
1272                 msg: ErrorMessage,
1273         },
1274         /// The peer did something incorrect. Tell them without closing any channels.
1275         SendWarningMessage {
1276                 /// The message to send.
1277                 msg: WarningMessage,
1278                 /// The peer may have done something harmless that we weren't able to meaningfully process,
1279                 /// though we should still tell them about it.
1280                 /// If this event is logged, log it at the given level.
1281                 log_level: logger::Level,
1282         },
1283 }
1284
1285 /// An Err type for failure to process messages.
1286 #[derive(Clone, Debug)]
1287 pub struct LightningError {
1288         /// A human-readable message describing the error
1289         pub err: String,
1290         /// The action which should be taken against the offending peer.
1291         pub action: ErrorAction,
1292 }
1293
1294 /// Struct used to return values from [`RevokeAndACK`] messages, containing a bunch of commitment
1295 /// transaction updates if they were pending.
1296 #[derive(Clone, Debug, PartialEq, Eq)]
1297 pub struct CommitmentUpdate {
1298         /// `update_add_htlc` messages which should be sent
1299         pub update_add_htlcs: Vec<UpdateAddHTLC>,
1300         /// `update_fulfill_htlc` messages which should be sent
1301         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
1302         /// `update_fail_htlc` messages which should be sent
1303         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
1304         /// `update_fail_malformed_htlc` messages which should be sent
1305         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
1306         /// An `update_fee` message which should be sent
1307         pub update_fee: Option<UpdateFee>,
1308         /// A `commitment_signed` message which should be sent
1309         pub commitment_signed: CommitmentSigned,
1310 }
1311
1312 /// A trait to describe an object which can receive channel messages.
1313 ///
1314 /// Messages MAY be called in parallel when they originate from different `their_node_ids`, however
1315 /// they MUST NOT be called in parallel when the two calls have the same `their_node_id`.
1316 pub trait ChannelMessageHandler : MessageSendEventsProvider {
1317         // Channel init:
1318         /// Handle an incoming `open_channel` message from the given peer.
1319         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel);
1320         /// Handle an incoming `open_channel2` message from the given peer.
1321         fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &OpenChannelV2);
1322         /// Handle an incoming `accept_channel` message from the given peer.
1323         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel);
1324         /// Handle an incoming `accept_channel2` message from the given peer.
1325         fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &AcceptChannelV2);
1326         /// Handle an incoming `funding_created` message from the given peer.
1327         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
1328         /// Handle an incoming `funding_signed` message from the given peer.
1329         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
1330         /// Handle an incoming `channel_ready` message from the given peer.
1331         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &ChannelReady);
1332
1333         // Channel close:
1334         /// Handle an incoming `shutdown` message from the given peer.
1335         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
1336         /// Handle an incoming `closing_signed` message from the given peer.
1337         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
1338
1339         // Interactive channel construction
1340         /// Handle an incoming `tx_add_input message` from the given peer.
1341         fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &TxAddInput);
1342         /// Handle an incoming `tx_add_output` message from the given peer.
1343         fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &TxAddOutput);
1344         /// Handle an incoming `tx_remove_input` message from the given peer.
1345         fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &TxRemoveInput);
1346         /// Handle an incoming `tx_remove_output` message from the given peer.
1347         fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &TxRemoveOutput);
1348         /// Handle an incoming `tx_complete message` from the given peer.
1349         fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &TxComplete);
1350         /// Handle an incoming `tx_signatures` message from the given peer.
1351         fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &TxSignatures);
1352         /// Handle an incoming `tx_init_rbf` message from the given peer.
1353         fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &TxInitRbf);
1354         /// Handle an incoming `tx_ack_rbf` message from the given peer.
1355         fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &TxAckRbf);
1356         /// Handle an incoming `tx_abort message` from the given peer.
1357         fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &TxAbort);
1358
1359         // HTLC handling:
1360         /// Handle an incoming `update_add_htlc` message from the given peer.
1361         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
1362         /// Handle an incoming `update_fulfill_htlc` message from the given peer.
1363         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
1364         /// Handle an incoming `update_fail_htlc` message from the given peer.
1365         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
1366         /// Handle an incoming `update_fail_malformed_htlc` message from the given peer.
1367         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
1368         /// Handle an incoming `commitment_signed` message from the given peer.
1369         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
1370         /// Handle an incoming `revoke_and_ack` message from the given peer.
1371         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
1372
1373         /// Handle an incoming `update_fee` message from the given peer.
1374         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
1375
1376         // Channel-to-announce:
1377         /// Handle an incoming `announcement_signatures` message from the given peer.
1378         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
1379
1380         // Connection loss/reestablish:
1381         /// Indicates a connection to the peer failed/an existing connection was lost.
1382         fn peer_disconnected(&self, their_node_id: &PublicKey);
1383
1384         /// Handle a peer reconnecting, possibly generating `channel_reestablish` message(s).
1385         ///
1386         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
1387         /// with us. Implementors should be somewhat conservative about doing so, however, as other
1388         /// message handlers may still wish to communicate with this peer.
1389         fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init, inbound: bool) -> Result<(), ()>;
1390         /// Handle an incoming `channel_reestablish` message from the given peer.
1391         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
1392
1393         /// Handle an incoming `channel_update` message from the given peer.
1394         fn handle_channel_update(&self, their_node_id: &PublicKey, msg: &ChannelUpdate);
1395
1396         // Error:
1397         /// Handle an incoming `error` message from the given peer.
1398         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
1399
1400         // Handler information:
1401         /// Gets the node feature flags which this handler itself supports. All available handlers are
1402         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
1403         /// which are broadcasted in our [`NodeAnnouncement`] message.
1404         fn provided_node_features(&self) -> NodeFeatures;
1405
1406         /// Gets the init feature flags which should be sent to the given peer. All available handlers
1407         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
1408         /// which are sent in our [`Init`] message.
1409         ///
1410         /// Note that this method is called before [`Self::peer_connected`].
1411         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
1412
1413         /// Gets the genesis hashes for this `ChannelMessageHandler` indicating which chains it supports.
1414         ///
1415         /// If it's `None`, then no particular network chain hash compatibility will be enforced when
1416         /// connecting to peers.
1417         fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>>;
1418 }
1419
1420 /// A trait to describe an object which can receive routing messages.
1421 ///
1422 /// # Implementor DoS Warnings
1423 ///
1424 /// For messages enabled with the `gossip_queries` feature there are potential DoS vectors when
1425 /// handling inbound queries. Implementors using an on-disk network graph should be aware of
1426 /// repeated disk I/O for queries accessing different parts of the network graph.
1427 pub trait RoutingMessageHandler : MessageSendEventsProvider {
1428         /// Handle an incoming `node_announcement` message, returning `true` if it should be forwarded on,
1429         /// `false` or returning an `Err` otherwise.
1430         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
1431         /// Handle a `channel_announcement` message, returning `true` if it should be forwarded on, `false`
1432         /// or returning an `Err` otherwise.
1433         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
1434         /// Handle an incoming `channel_update` message, returning true if it should be forwarded on,
1435         /// `false` or returning an `Err` otherwise.
1436         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
1437         /// Gets channel announcements and updates required to dump our routing table to a remote node,
1438         /// starting at the `short_channel_id` indicated by `starting_point` and including announcements
1439         /// for a single channel.
1440         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
1441         /// Gets a node announcement required to dump our routing table to a remote node, starting at
1442         /// the node *after* the provided pubkey and including up to one announcement immediately
1443         /// higher (as defined by `<PublicKey as Ord>::cmp`) than `starting_point`.
1444         /// If `None` is provided for `starting_point`, we start at the first node.
1445         fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement>;
1446         /// Called when a connection is established with a peer. This can be used to
1447         /// perform routing table synchronization using a strategy defined by the
1448         /// implementor.
1449         ///
1450         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
1451         /// with us. Implementors should be somewhat conservative about doing so, however, as other
1452         /// message handlers may still wish to communicate with this peer.
1453         fn peer_connected(&self, their_node_id: &PublicKey, init: &Init, inbound: bool) -> Result<(), ()>;
1454         /// Handles the reply of a query we initiated to learn about channels
1455         /// for a given range of blocks. We can expect to receive one or more
1456         /// replies to a single query.
1457         fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
1458         /// Handles the reply of a query we initiated asking for routing gossip
1459         /// messages for a list of channels. We should receive this message when
1460         /// a node has completed its best effort to send us the pertaining routing
1461         /// gossip messages.
1462         fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
1463         /// Handles when a peer asks us to send a list of `short_channel_id`s
1464         /// for the requested range of blocks.
1465         fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
1466         /// Handles when a peer asks us to send routing gossip messages for a
1467         /// list of `short_channel_id`s.
1468         fn handle_query_short_channel_ids(&self, their_node_id: &PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
1469
1470         // Handler queueing status:
1471         /// Indicates that there are a large number of [`ChannelAnnouncement`] (or other) messages
1472         /// pending some async action. While there is no guarantee of the rate of future messages, the
1473         /// caller should seek to reduce the rate of new gossip messages handled, especially
1474         /// [`ChannelAnnouncement`]s.
1475         fn processing_queue_high(&self) -> bool;
1476
1477         // Handler information:
1478         /// Gets the node feature flags which this handler itself supports. All available handlers are
1479         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
1480         /// which are broadcasted in our [`NodeAnnouncement`] message.
1481         fn provided_node_features(&self) -> NodeFeatures;
1482         /// Gets the init feature flags which should be sent to the given peer. All available handlers
1483         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
1484         /// which are sent in our [`Init`] message.
1485         ///
1486         /// Note that this method is called before [`Self::peer_connected`].
1487         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
1488 }
1489
1490 /// A trait to describe an object that can receive onion messages.
1491 pub trait OnionMessageHandler : OnionMessageProvider {
1492         /// Handle an incoming `onion_message` message from the given peer.
1493         fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage);
1494         /// Called when a connection is established with a peer. Can be used to track which peers
1495         /// advertise onion message support and are online.
1496         ///
1497         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
1498         /// with us. Implementors should be somewhat conservative about doing so, however, as other
1499         /// message handlers may still wish to communicate with this peer.
1500         fn peer_connected(&self, their_node_id: &PublicKey, init: &Init, inbound: bool) -> Result<(), ()>;
1501         /// Indicates a connection to the peer failed/an existing connection was lost. Allows handlers to
1502         /// drop and refuse to forward onion messages to this peer.
1503         fn peer_disconnected(&self, their_node_id: &PublicKey);
1504
1505         // Handler information:
1506         /// Gets the node feature flags which this handler itself supports. All available handlers are
1507         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
1508         /// which are broadcasted in our [`NodeAnnouncement`] message.
1509         fn provided_node_features(&self) -> NodeFeatures;
1510
1511         /// Gets the init feature flags which should be sent to the given peer. All available handlers
1512         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
1513         /// which are sent in our [`Init`] message.
1514         ///
1515         /// Note that this method is called before [`Self::peer_connected`].
1516         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
1517 }
1518
1519 mod fuzzy_internal_msgs {
1520         use bitcoin::secp256k1::PublicKey;
1521         use crate::prelude::*;
1522         use crate::ln::{PaymentPreimage, PaymentSecret};
1523
1524         // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
1525         // them from untrusted input):
1526         #[derive(Clone)]
1527         pub struct FinalOnionHopData {
1528                 pub payment_secret: PaymentSecret,
1529                 /// The total value, in msat, of the payment as received by the ultimate recipient.
1530                 /// Message serialization may panic if this value is more than 21 million Bitcoin.
1531                 pub total_msat: u64,
1532         }
1533
1534         pub enum InboundOnionPayload {
1535                 Forward {
1536                         short_channel_id: u64,
1537                         /// The value, in msat, of the payment after this hop's fee is deducted.
1538                         amt_to_forward: u64,
1539                         outgoing_cltv_value: u32,
1540                 },
1541                 Receive {
1542                         payment_data: Option<FinalOnionHopData>,
1543                         payment_metadata: Option<Vec<u8>>,
1544                         keysend_preimage: Option<PaymentPreimage>,
1545                         custom_tlvs: Vec<(u64, Vec<u8>)>,
1546                         amt_msat: u64,
1547                         outgoing_cltv_value: u32,
1548                 },
1549         }
1550
1551         pub(crate) enum OutboundOnionPayload {
1552                 Forward {
1553                         short_channel_id: u64,
1554                         /// The value, in msat, of the payment after this hop's fee is deducted.
1555                         amt_to_forward: u64,
1556                         outgoing_cltv_value: u32,
1557                 },
1558                 Receive {
1559                         payment_data: Option<FinalOnionHopData>,
1560                         payment_metadata: Option<Vec<u8>>,
1561                         keysend_preimage: Option<PaymentPreimage>,
1562                         custom_tlvs: Vec<(u64, Vec<u8>)>,
1563                         amt_msat: u64,
1564                         outgoing_cltv_value: u32,
1565                 },
1566                 BlindedForward {
1567                         encrypted_tlvs: Vec<u8>,
1568                         intro_node_blinding_point: Option<PublicKey>,
1569                 },
1570                 BlindedReceive {
1571                         amt_msat: u64,
1572                         total_msat: u64,
1573                         outgoing_cltv_value: u32,
1574                         encrypted_tlvs: Vec<u8>,
1575                         intro_node_blinding_point: Option<PublicKey>, // Set if the introduction node of the blinded path is the final node
1576                 }
1577         }
1578
1579         pub struct DecodedOnionErrorPacket {
1580                 pub(crate) hmac: [u8; 32],
1581                 pub(crate) failuremsg: Vec<u8>,
1582                 pub(crate) pad: Vec<u8>,
1583         }
1584 }
1585 #[cfg(fuzzing)]
1586 pub use self::fuzzy_internal_msgs::*;
1587 #[cfg(not(fuzzing))]
1588 pub(crate) use self::fuzzy_internal_msgs::*;
1589
1590 #[derive(Clone)]
1591 pub(crate) struct OnionPacket {
1592         pub(crate) version: u8,
1593         /// In order to ensure we always return an error on onion decode in compliance with [BOLT
1594         /// #4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md), we have to
1595         /// deserialize `OnionPacket`s contained in [`UpdateAddHTLC`] messages even if the ephemeral
1596         /// public key (here) is bogus, so we hold a [`Result`] instead of a [`PublicKey`] as we'd
1597         /// like.
1598         pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
1599         pub(crate) hop_data: [u8; 20*65],
1600         pub(crate) hmac: [u8; 32],
1601 }
1602
1603 impl onion_utils::Packet for OnionPacket {
1604         type Data = onion_utils::FixedSizeOnionPacket;
1605         fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
1606                 Self {
1607                         version: 0,
1608                         public_key: Ok(pubkey),
1609                         hop_data: hop_data.0,
1610                         hmac,
1611                 }
1612         }
1613 }
1614
1615 impl Eq for OnionPacket { }
1616 impl PartialEq for OnionPacket {
1617         fn eq(&self, other: &OnionPacket) -> bool {
1618                 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
1619                         if i != j { return false; }
1620                 }
1621                 self.version == other.version &&
1622                         self.public_key == other.public_key &&
1623                         self.hmac == other.hmac
1624         }
1625 }
1626
1627 impl fmt::Debug for OnionPacket {
1628         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1629                 f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
1630         }
1631 }
1632
1633 #[derive(Clone, Debug, PartialEq, Eq)]
1634 pub(crate) struct OnionErrorPacket {
1635         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
1636         // (TODO) We limit it in decode to much lower...
1637         pub(crate) data: Vec<u8>,
1638 }
1639
1640 impl fmt::Display for DecodeError {
1641         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1642                 match *self {
1643                         DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
1644                         DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
1645                         DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
1646                         DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
1647                         DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
1648                         DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
1649                         DecodeError::UnsupportedCompression => f.write_str("We don't support receiving messages with zlib-compressed fields"),
1650                 }
1651         }
1652 }
1653
1654 impl From<io::Error> for DecodeError {
1655         fn from(e: io::Error) -> Self {
1656                 if e.kind() == io::ErrorKind::UnexpectedEof {
1657                         DecodeError::ShortRead
1658                 } else {
1659                         DecodeError::Io(e.kind())
1660                 }
1661         }
1662 }
1663
1664 #[cfg(not(taproot))]
1665 impl_writeable_msg!(AcceptChannel, {
1666         temporary_channel_id,
1667         dust_limit_satoshis,
1668         max_htlc_value_in_flight_msat,
1669         channel_reserve_satoshis,
1670         htlc_minimum_msat,
1671         minimum_depth,
1672         to_self_delay,
1673         max_accepted_htlcs,
1674         funding_pubkey,
1675         revocation_basepoint,
1676         payment_point,
1677         delayed_payment_basepoint,
1678         htlc_basepoint,
1679         first_per_commitment_point,
1680 }, {
1681         (0, shutdown_scriptpubkey, (option, encoding: (Script, WithoutLength))), // Don't encode length twice.
1682         (1, channel_type, option),
1683 });
1684
1685 #[cfg(taproot)]
1686 impl_writeable_msg!(AcceptChannel, {
1687         temporary_channel_id,
1688         dust_limit_satoshis,
1689         max_htlc_value_in_flight_msat,
1690         channel_reserve_satoshis,
1691         htlc_minimum_msat,
1692         minimum_depth,
1693         to_self_delay,
1694         max_accepted_htlcs,
1695         funding_pubkey,
1696         revocation_basepoint,
1697         payment_point,
1698         delayed_payment_basepoint,
1699         htlc_basepoint,
1700         first_per_commitment_point,
1701 }, {
1702         (0, shutdown_scriptpubkey, (option, encoding: (Script, WithoutLength))), // Don't encode length twice.
1703         (1, channel_type, option),
1704         (4, next_local_nonce, option),
1705 });
1706
1707 impl_writeable_msg!(AcceptChannelV2, {
1708         temporary_channel_id,
1709         funding_satoshis,
1710         dust_limit_satoshis,
1711         max_htlc_value_in_flight_msat,
1712         htlc_minimum_msat,
1713         minimum_depth,
1714         to_self_delay,
1715         max_accepted_htlcs,
1716         funding_pubkey,
1717         revocation_basepoint,
1718         payment_basepoint,
1719         delayed_payment_basepoint,
1720         htlc_basepoint,
1721         first_per_commitment_point,
1722         second_per_commitment_point,
1723 }, {
1724         (0, shutdown_scriptpubkey, option),
1725         (1, channel_type, option),
1726         (2, require_confirmed_inputs, option),
1727 });
1728
1729 impl_writeable_msg!(TxAddInput, {
1730         channel_id,
1731         serial_id,
1732         prevtx,
1733         prevtx_out,
1734         sequence,
1735 }, {});
1736
1737 impl_writeable_msg!(TxAddOutput, {
1738         channel_id,
1739         serial_id,
1740         sats,
1741         script,
1742 }, {});
1743
1744 impl_writeable_msg!(TxRemoveInput, {
1745         channel_id,
1746         serial_id,
1747 }, {});
1748
1749 impl_writeable_msg!(TxRemoveOutput, {
1750         channel_id,
1751         serial_id,
1752 }, {});
1753
1754 impl_writeable_msg!(TxComplete, {
1755         channel_id,
1756 }, {});
1757
1758 impl_writeable_msg!(TxSignatures, {
1759         channel_id,
1760         tx_hash,
1761         witnesses,
1762 }, {});
1763
1764 impl_writeable_msg!(TxInitRbf, {
1765         channel_id,
1766         locktime,
1767         feerate_sat_per_1000_weight,
1768 }, {
1769         (0, funding_output_contribution, option),
1770 });
1771
1772 impl_writeable_msg!(TxAckRbf, {
1773         channel_id,
1774 }, {
1775         (0, funding_output_contribution, option),
1776 });
1777
1778 impl_writeable_msg!(TxAbort, {
1779         channel_id,
1780         data,
1781 }, {});
1782
1783 impl_writeable_msg!(AnnouncementSignatures, {
1784         channel_id,
1785         short_channel_id,
1786         node_signature,
1787         bitcoin_signature
1788 }, {});
1789
1790 impl_writeable_msg!(ChannelReestablish, {
1791         channel_id,
1792         next_local_commitment_number,
1793         next_remote_commitment_number,
1794         your_last_per_commitment_secret,
1795         my_current_per_commitment_point,
1796 }, {
1797         (0, next_funding_txid, option),
1798 });
1799
1800 impl_writeable_msg!(ClosingSigned,
1801         { channel_id, fee_satoshis, signature },
1802         { (1, fee_range, option) }
1803 );
1804
1805 impl_writeable!(ClosingSignedFeeRange, {
1806         min_fee_satoshis,
1807         max_fee_satoshis
1808 });
1809
1810 #[cfg(not(taproot))]
1811 impl_writeable_msg!(CommitmentSigned, {
1812         channel_id,
1813         signature,
1814         htlc_signatures
1815 }, {});
1816
1817 #[cfg(taproot)]
1818 impl_writeable_msg!(CommitmentSigned, {
1819         channel_id,
1820         signature,
1821         htlc_signatures
1822 }, {
1823         (2, partial_signature_with_nonce, option)
1824 });
1825
1826 impl_writeable!(DecodedOnionErrorPacket, {
1827         hmac,
1828         failuremsg,
1829         pad
1830 });
1831
1832 #[cfg(not(taproot))]
1833 impl_writeable_msg!(FundingCreated, {
1834         temporary_channel_id,
1835         funding_txid,
1836         funding_output_index,
1837         signature
1838 }, {});
1839 #[cfg(taproot)]
1840 impl_writeable_msg!(FundingCreated, {
1841         temporary_channel_id,
1842         funding_txid,
1843         funding_output_index,
1844         signature
1845 }, {
1846         (2, partial_signature_with_nonce, option),
1847         (4, next_local_nonce, option)
1848 });
1849
1850 #[cfg(not(taproot))]
1851 impl_writeable_msg!(FundingSigned, {
1852         channel_id,
1853         signature
1854 }, {});
1855
1856 #[cfg(taproot)]
1857 impl_writeable_msg!(FundingSigned, {
1858         channel_id,
1859         signature
1860 }, {
1861         (2, partial_signature_with_nonce, option)
1862 });
1863
1864 impl_writeable_msg!(ChannelReady, {
1865         channel_id,
1866         next_per_commitment_point,
1867 }, {
1868         (1, short_channel_id_alias, option),
1869 });
1870
1871 impl Writeable for Init {
1872         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1873                 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1874                 // our relevant feature bits. This keeps us compatible with old nodes.
1875                 self.features.write_up_to_13(w)?;
1876                 self.features.write(w)?;
1877                 encode_tlv_stream!(w, {
1878                         (1, self.networks.as_ref().map(|n| WithoutLength(n)), option),
1879                         (3, self.remote_network_address, option),
1880                 });
1881                 Ok(())
1882         }
1883 }
1884
1885 impl Readable for Init {
1886         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1887                 let global_features: InitFeatures = Readable::read(r)?;
1888                 let features: InitFeatures = Readable::read(r)?;
1889                 let mut remote_network_address: Option<SocketAddress> = None;
1890                 let mut networks: Option<WithoutLength<Vec<ChainHash>>> = None;
1891                 decode_tlv_stream!(r, {
1892                         (1, networks, option),
1893                         (3, remote_network_address, option)
1894                 });
1895                 Ok(Init {
1896                         features: features | global_features,
1897                         networks: networks.map(|n| n.0),
1898                         remote_network_address,
1899                 })
1900         }
1901 }
1902
1903 impl_writeable_msg!(OpenChannel, {
1904         chain_hash,
1905         temporary_channel_id,
1906         funding_satoshis,
1907         push_msat,
1908         dust_limit_satoshis,
1909         max_htlc_value_in_flight_msat,
1910         channel_reserve_satoshis,
1911         htlc_minimum_msat,
1912         feerate_per_kw,
1913         to_self_delay,
1914         max_accepted_htlcs,
1915         funding_pubkey,
1916         revocation_basepoint,
1917         payment_point,
1918         delayed_payment_basepoint,
1919         htlc_basepoint,
1920         first_per_commitment_point,
1921         channel_flags,
1922 }, {
1923         (0, shutdown_scriptpubkey, (option, encoding: (Script, WithoutLength))), // Don't encode length twice.
1924         (1, channel_type, option),
1925 });
1926
1927 impl_writeable_msg!(OpenChannelV2, {
1928         chain_hash,
1929         temporary_channel_id,
1930         funding_feerate_sat_per_1000_weight,
1931         commitment_feerate_sat_per_1000_weight,
1932         funding_satoshis,
1933         dust_limit_satoshis,
1934         max_htlc_value_in_flight_msat,
1935         htlc_minimum_msat,
1936         to_self_delay,
1937         max_accepted_htlcs,
1938         locktime,
1939         funding_pubkey,
1940         revocation_basepoint,
1941         payment_basepoint,
1942         delayed_payment_basepoint,
1943         htlc_basepoint,
1944         first_per_commitment_point,
1945         second_per_commitment_point,
1946         channel_flags,
1947 }, {
1948         (0, shutdown_scriptpubkey, option),
1949         (1, channel_type, option),
1950         (2, require_confirmed_inputs, option),
1951 });
1952
1953 #[cfg(not(taproot))]
1954 impl_writeable_msg!(RevokeAndACK, {
1955         channel_id,
1956         per_commitment_secret,
1957         next_per_commitment_point
1958 }, {});
1959
1960 #[cfg(taproot)]
1961 impl_writeable_msg!(RevokeAndACK, {
1962         channel_id,
1963         per_commitment_secret,
1964         next_per_commitment_point
1965 }, {
1966         (4, next_local_nonce, option)
1967 });
1968
1969 impl_writeable_msg!(Shutdown, {
1970         channel_id,
1971         scriptpubkey
1972 }, {});
1973
1974 impl_writeable_msg!(UpdateFailHTLC, {
1975         channel_id,
1976         htlc_id,
1977         reason
1978 }, {});
1979
1980 impl_writeable_msg!(UpdateFailMalformedHTLC, {
1981         channel_id,
1982         htlc_id,
1983         sha256_of_onion,
1984         failure_code
1985 }, {});
1986
1987 impl_writeable_msg!(UpdateFee, {
1988         channel_id,
1989         feerate_per_kw
1990 }, {});
1991
1992 impl_writeable_msg!(UpdateFulfillHTLC, {
1993         channel_id,
1994         htlc_id,
1995         payment_preimage
1996 }, {});
1997
1998 // Note that this is written as a part of ChannelManager objects, and thus cannot change its
1999 // serialization format in a way which assumes we know the total serialized length/message end
2000 // position.
2001 impl_writeable!(OnionErrorPacket, {
2002         data
2003 });
2004
2005 // Note that this is written as a part of ChannelManager objects, and thus cannot change its
2006 // serialization format in a way which assumes we know the total serialized length/message end
2007 // position.
2008 impl Writeable for OnionPacket {
2009         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2010                 self.version.write(w)?;
2011                 match self.public_key {
2012                         Ok(pubkey) => pubkey.write(w)?,
2013                         Err(_) => [0u8;33].write(w)?,
2014                 }
2015                 w.write_all(&self.hop_data)?;
2016                 self.hmac.write(w)?;
2017                 Ok(())
2018         }
2019 }
2020
2021 impl Readable for OnionPacket {
2022         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2023                 Ok(OnionPacket {
2024                         version: Readable::read(r)?,
2025                         public_key: {
2026                                 let mut buf = [0u8;33];
2027                                 r.read_exact(&mut buf)?;
2028                                 PublicKey::from_slice(&buf)
2029                         },
2030                         hop_data: Readable::read(r)?,
2031                         hmac: Readable::read(r)?,
2032                 })
2033         }
2034 }
2035
2036 impl_writeable_msg!(UpdateAddHTLC, {
2037         channel_id,
2038         htlc_id,
2039         amount_msat,
2040         payment_hash,
2041         cltv_expiry,
2042         onion_routing_packet,
2043 }, {
2044         (65537, skimmed_fee_msat, option)
2045 });
2046
2047 impl Readable for OnionMessage {
2048         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2049                 let blinding_point: PublicKey = Readable::read(r)?;
2050                 let len: u16 = Readable::read(r)?;
2051                 let mut packet_reader = FixedLengthReader::new(r, len as u64);
2052                 let onion_routing_packet: onion_message::Packet = <onion_message::Packet as LengthReadable>::read(&mut packet_reader)?;
2053                 Ok(Self {
2054                         blinding_point,
2055                         onion_routing_packet,
2056                 })
2057         }
2058 }
2059
2060 impl Writeable for OnionMessage {
2061         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2062                 self.blinding_point.write(w)?;
2063                 let onion_packet_len = self.onion_routing_packet.serialized_length();
2064                 (onion_packet_len as u16).write(w)?;
2065                 self.onion_routing_packet.write(w)?;
2066                 Ok(())
2067         }
2068 }
2069
2070 impl Writeable for FinalOnionHopData {
2071         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2072                 self.payment_secret.0.write(w)?;
2073                 HighZeroBytesDroppedBigSize(self.total_msat).write(w)
2074         }
2075 }
2076
2077 impl Readable for FinalOnionHopData {
2078         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2079                 let secret: [u8; 32] = Readable::read(r)?;
2080                 let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
2081                 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
2082         }
2083 }
2084
2085 impl Writeable for OutboundOnionPayload {
2086         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2087                 match self {
2088                         Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } => {
2089                                 _encode_varint_length_prefixed_tlv!(w, {
2090                                         (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
2091                                         (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2092                                         (6, short_channel_id, required)
2093                                 });
2094                         },
2095                         Self::Receive {
2096                                 ref payment_data, ref payment_metadata, ref keysend_preimage, amt_msat,
2097                                 outgoing_cltv_value, ref custom_tlvs,
2098                         } => {
2099                                 // We need to update [`ln::outbound_payment::RecipientOnionFields::with_custom_tlvs`]
2100                                 // to reject any reserved types in the experimental range if new ones are ever
2101                                 // standardized.
2102                                 let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
2103                                 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs.iter().chain(keysend_tlv.iter()).collect();
2104                                 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
2105                                 _encode_varint_length_prefixed_tlv!(w, {
2106                                         (2, HighZeroBytesDroppedBigSize(*amt_msat), required),
2107                                         (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2108                                         (8, payment_data, option),
2109                                         (16, payment_metadata.as_ref().map(|m| WithoutLength(m)), option)
2110                                 }, custom_tlvs.iter());
2111                         },
2112                         Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
2113                                 _encode_varint_length_prefixed_tlv!(w, {
2114                                         (10, *encrypted_tlvs, required_vec),
2115                                         (12, intro_node_blinding_point, option)
2116                                 });
2117                         },
2118                         Self::BlindedReceive {
2119                                 amt_msat, total_msat, outgoing_cltv_value, encrypted_tlvs,
2120                                 intro_node_blinding_point,
2121                         } => {
2122                                 _encode_varint_length_prefixed_tlv!(w, {
2123                                         (2, HighZeroBytesDroppedBigSize(*amt_msat), required),
2124                                         (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2125                                         (10, *encrypted_tlvs, required_vec),
2126                                         (12, intro_node_blinding_point, option),
2127                                         (18, HighZeroBytesDroppedBigSize(*total_msat), required)
2128                                 });
2129                         },
2130                 }
2131                 Ok(())
2132         }
2133 }
2134
2135 impl Readable for InboundOnionPayload {
2136         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2137                 let mut amt = HighZeroBytesDroppedBigSize(0u64);
2138                 let mut cltv_value = HighZeroBytesDroppedBigSize(0u32);
2139                 let mut short_id: Option<u64> = None;
2140                 let mut payment_data: Option<FinalOnionHopData> = None;
2141                 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
2142                 let mut keysend_preimage: Option<PaymentPreimage> = None;
2143                 let mut custom_tlvs = Vec::new();
2144
2145                 let tlv_len = BigSize::read(r)?;
2146                 let rd = FixedLengthReader::new(r, tlv_len.0);
2147                 decode_tlv_stream_with_custom_tlv_decode!(rd, {
2148                         (2, amt, required),
2149                         (4, cltv_value, required),
2150                         (6, short_id, option),
2151                         (8, payment_data, option),
2152                         (16, payment_metadata, option),
2153                         // See https://github.com/lightning/blips/blob/master/blip-0003.md
2154                         (5482373484, keysend_preimage, option)
2155                 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
2156                         if msg_type < 1 << 16 { return Ok(false) }
2157                         let mut value = Vec::new();
2158                         msg_reader.read_to_end(&mut value)?;
2159                         custom_tlvs.push((msg_type, value));
2160                         Ok(true)
2161                 });
2162
2163                 if amt.0 > MAX_VALUE_MSAT { return Err(DecodeError::InvalidValue) }
2164                 if let Some(short_channel_id) = short_id {
2165                         if payment_data.is_some() { return Err(DecodeError::InvalidValue) }
2166                         if payment_metadata.is_some() { return Err(DecodeError::InvalidValue); }
2167                         Ok(Self::Forward {
2168                                 short_channel_id,
2169                                 amt_to_forward: amt.0,
2170                                 outgoing_cltv_value: cltv_value.0,
2171                         })
2172                 } else {
2173                         if let Some(data) = &payment_data {
2174                                 if data.total_msat > MAX_VALUE_MSAT {
2175                                         return Err(DecodeError::InvalidValue);
2176                                 }
2177                         }
2178                         Ok(Self::Receive {
2179                                 payment_data,
2180                                 payment_metadata: payment_metadata.map(|w| w.0),
2181                                 keysend_preimage,
2182                                 amt_msat: amt.0,
2183                                 outgoing_cltv_value: cltv_value.0,
2184                                 custom_tlvs,
2185                         })
2186                 }
2187         }
2188 }
2189
2190 // ReadableArgs because we need onion_utils::decode_next_hop to accommodate payment packets and
2191 // onion message packets.
2192 impl ReadableArgs<()> for InboundOnionPayload {
2193         fn read<R: Read>(r: &mut R, _arg: ()) -> Result<Self, DecodeError> {
2194                 <Self as Readable>::read(r)
2195         }
2196 }
2197
2198 impl Writeable for Ping {
2199         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2200                 self.ponglen.write(w)?;
2201                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
2202                 Ok(())
2203         }
2204 }
2205
2206 impl Readable for Ping {
2207         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2208                 Ok(Ping {
2209                         ponglen: Readable::read(r)?,
2210                         byteslen: {
2211                                 let byteslen = Readable::read(r)?;
2212                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
2213                                 byteslen
2214                         }
2215                 })
2216         }
2217 }
2218
2219 impl Writeable for Pong {
2220         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2221                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
2222                 Ok(())
2223         }
2224 }
2225
2226 impl Readable for Pong {
2227         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2228                 Ok(Pong {
2229                         byteslen: {
2230                                 let byteslen = Readable::read(r)?;
2231                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
2232                                 byteslen
2233                         }
2234                 })
2235         }
2236 }
2237
2238 impl Writeable for UnsignedChannelAnnouncement {
2239         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2240                 self.features.write(w)?;
2241                 self.chain_hash.write(w)?;
2242                 self.short_channel_id.write(w)?;
2243                 self.node_id_1.write(w)?;
2244                 self.node_id_2.write(w)?;
2245                 self.bitcoin_key_1.write(w)?;
2246                 self.bitcoin_key_2.write(w)?;
2247                 w.write_all(&self.excess_data[..])?;
2248                 Ok(())
2249         }
2250 }
2251
2252 impl Readable for UnsignedChannelAnnouncement {
2253         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2254                 Ok(Self {
2255                         features: Readable::read(r)?,
2256                         chain_hash: Readable::read(r)?,
2257                         short_channel_id: Readable::read(r)?,
2258                         node_id_1: Readable::read(r)?,
2259                         node_id_2: Readable::read(r)?,
2260                         bitcoin_key_1: Readable::read(r)?,
2261                         bitcoin_key_2: Readable::read(r)?,
2262                         excess_data: read_to_end(r)?,
2263                 })
2264         }
2265 }
2266
2267 impl_writeable!(ChannelAnnouncement, {
2268         node_signature_1,
2269         node_signature_2,
2270         bitcoin_signature_1,
2271         bitcoin_signature_2,
2272         contents
2273 });
2274
2275 impl Writeable for UnsignedChannelUpdate {
2276         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2277                 // `message_flags` used to indicate presence of `htlc_maximum_msat`, but was deprecated in the spec.
2278                 const MESSAGE_FLAGS: u8 = 1;
2279                 self.chain_hash.write(w)?;
2280                 self.short_channel_id.write(w)?;
2281                 self.timestamp.write(w)?;
2282                 let all_flags = self.flags as u16 | ((MESSAGE_FLAGS as u16) << 8);
2283                 all_flags.write(w)?;
2284                 self.cltv_expiry_delta.write(w)?;
2285                 self.htlc_minimum_msat.write(w)?;
2286                 self.fee_base_msat.write(w)?;
2287                 self.fee_proportional_millionths.write(w)?;
2288                 self.htlc_maximum_msat.write(w)?;
2289                 w.write_all(&self.excess_data[..])?;
2290                 Ok(())
2291         }
2292 }
2293
2294 impl Readable for UnsignedChannelUpdate {
2295         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2296                 Ok(Self {
2297                         chain_hash: Readable::read(r)?,
2298                         short_channel_id: Readable::read(r)?,
2299                         timestamp: Readable::read(r)?,
2300                         flags: {
2301                                 let flags: u16 = Readable::read(r)?;
2302                                 // Note: we ignore the `message_flags` for now, since it was deprecated by the spec.
2303                                 flags as u8
2304                         },
2305                         cltv_expiry_delta: Readable::read(r)?,
2306                         htlc_minimum_msat: Readable::read(r)?,
2307                         fee_base_msat: Readable::read(r)?,
2308                         fee_proportional_millionths: Readable::read(r)?,
2309                         htlc_maximum_msat: Readable::read(r)?,
2310                         excess_data: read_to_end(r)?,
2311                 })
2312         }
2313 }
2314
2315 impl_writeable!(ChannelUpdate, {
2316         signature,
2317         contents
2318 });
2319
2320 impl Writeable for ErrorMessage {
2321         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2322                 self.channel_id.write(w)?;
2323                 (self.data.len() as u16).write(w)?;
2324                 w.write_all(self.data.as_bytes())?;
2325                 Ok(())
2326         }
2327 }
2328
2329 impl Readable for ErrorMessage {
2330         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2331                 Ok(Self {
2332                         channel_id: Readable::read(r)?,
2333                         data: {
2334                                 let sz: usize = <u16 as Readable>::read(r)? as usize;
2335                                 let mut data = Vec::with_capacity(sz);
2336                                 data.resize(sz, 0);
2337                                 r.read_exact(&mut data)?;
2338                                 match String::from_utf8(data) {
2339                                         Ok(s) => s,
2340                                         Err(_) => return Err(DecodeError::InvalidValue),
2341                                 }
2342                         }
2343                 })
2344         }
2345 }
2346
2347 impl Writeable for WarningMessage {
2348         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2349                 self.channel_id.write(w)?;
2350                 (self.data.len() as u16).write(w)?;
2351                 w.write_all(self.data.as_bytes())?;
2352                 Ok(())
2353         }
2354 }
2355
2356 impl Readable for WarningMessage {
2357         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2358                 Ok(Self {
2359                         channel_id: Readable::read(r)?,
2360                         data: {
2361                                 let sz: usize = <u16 as Readable>::read(r)? as usize;
2362                                 let mut data = Vec::with_capacity(sz);
2363                                 data.resize(sz, 0);
2364                                 r.read_exact(&mut data)?;
2365                                 match String::from_utf8(data) {
2366                                         Ok(s) => s,
2367                                         Err(_) => return Err(DecodeError::InvalidValue),
2368                                 }
2369                         }
2370                 })
2371         }
2372 }
2373
2374 impl Writeable for UnsignedNodeAnnouncement {
2375         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2376                 self.features.write(w)?;
2377                 self.timestamp.write(w)?;
2378                 self.node_id.write(w)?;
2379                 w.write_all(&self.rgb)?;
2380                 self.alias.write(w)?;
2381
2382                 let mut addr_len = 0;
2383                 for addr in self.addresses.iter() {
2384                         addr_len += 1 + addr.len();
2385                 }
2386                 (addr_len + self.excess_address_data.len() as u16).write(w)?;
2387                 for addr in self.addresses.iter() {
2388                         addr.write(w)?;
2389                 }
2390                 w.write_all(&self.excess_address_data[..])?;
2391                 w.write_all(&self.excess_data[..])?;
2392                 Ok(())
2393         }
2394 }
2395
2396 impl Readable for UnsignedNodeAnnouncement {
2397         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2398                 let features: NodeFeatures = Readable::read(r)?;
2399                 let timestamp: u32 = Readable::read(r)?;
2400                 let node_id: NodeId = Readable::read(r)?;
2401                 let mut rgb = [0; 3];
2402                 r.read_exact(&mut rgb)?;
2403                 let alias: NodeAlias = Readable::read(r)?;
2404
2405                 let addr_len: u16 = Readable::read(r)?;
2406                 let mut addresses: Vec<SocketAddress> = Vec::new();
2407                 let mut addr_readpos = 0;
2408                 let mut excess = false;
2409                 let mut excess_byte = 0;
2410                 loop {
2411                         if addr_len <= addr_readpos { break; }
2412                         match Readable::read(r) {
2413                                 Ok(Ok(addr)) => {
2414                                         if addr_len < addr_readpos + 1 + addr.len() {
2415                                                 return Err(DecodeError::BadLengthDescriptor);
2416                                         }
2417                                         addr_readpos += (1 + addr.len()) as u16;
2418                                         addresses.push(addr);
2419                                 },
2420                                 Ok(Err(unknown_descriptor)) => {
2421                                         excess = true;
2422                                         excess_byte = unknown_descriptor;
2423                                         break;
2424                                 },
2425                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
2426                                 Err(e) => return Err(e),
2427                         }
2428                 }
2429
2430                 let mut excess_data = vec![];
2431                 let excess_address_data = if addr_readpos < addr_len {
2432                         let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
2433                         r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
2434                         if excess {
2435                                 excess_address_data[0] = excess_byte;
2436                         }
2437                         excess_address_data
2438                 } else {
2439                         if excess {
2440                                 excess_data.push(excess_byte);
2441                         }
2442                         Vec::new()
2443                 };
2444                 excess_data.extend(read_to_end(r)?.iter());
2445                 Ok(UnsignedNodeAnnouncement {
2446                         features,
2447                         timestamp,
2448                         node_id,
2449                         rgb,
2450                         alias,
2451                         addresses,
2452                         excess_address_data,
2453                         excess_data,
2454                 })
2455         }
2456 }
2457
2458 impl_writeable!(NodeAnnouncement, {
2459         signature,
2460         contents
2461 });
2462
2463 impl Readable for QueryShortChannelIds {
2464         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2465                 let chain_hash: BlockHash = Readable::read(r)?;
2466
2467                 let encoding_len: u16 = Readable::read(r)?;
2468                 let encoding_type: u8 = Readable::read(r)?;
2469
2470                 // Must be encoding_type=0 uncompressed serialization. We do not
2471                 // support encoding_type=1 zlib serialization.
2472                 if encoding_type != EncodingType::Uncompressed as u8 {
2473                         return Err(DecodeError::UnsupportedCompression);
2474                 }
2475
2476                 // We expect the encoding_len to always includes the 1-byte
2477                 // encoding_type and that short_channel_ids are 8-bytes each
2478                 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
2479                         return Err(DecodeError::InvalidValue);
2480                 }
2481
2482                 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
2483                 // less the 1-byte encoding_type
2484                 let short_channel_id_count: u16 = (encoding_len - 1)/8;
2485                 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
2486                 for _ in 0..short_channel_id_count {
2487                         short_channel_ids.push(Readable::read(r)?);
2488                 }
2489
2490                 Ok(QueryShortChannelIds {
2491                         chain_hash,
2492                         short_channel_ids,
2493                 })
2494         }
2495 }
2496
2497 impl Writeable for QueryShortChannelIds {
2498         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2499                 // Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
2500                 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
2501
2502                 self.chain_hash.write(w)?;
2503                 encoding_len.write(w)?;
2504
2505                 // We only support type=0 uncompressed serialization
2506                 (EncodingType::Uncompressed as u8).write(w)?;
2507
2508                 for scid in self.short_channel_ids.iter() {
2509                         scid.write(w)?;
2510                 }
2511
2512                 Ok(())
2513         }
2514 }
2515
2516 impl_writeable_msg!(ReplyShortChannelIdsEnd, {
2517         chain_hash,
2518         full_information,
2519 }, {});
2520
2521 impl QueryChannelRange {
2522         /// Calculates the overflow safe ending block height for the query.
2523         ///
2524         /// Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`.
2525         pub fn end_blocknum(&self) -> u32 {
2526                 match self.first_blocknum.checked_add(self.number_of_blocks) {
2527                         Some(block) => block,
2528                         None => u32::max_value(),
2529                 }
2530         }
2531 }
2532
2533 impl_writeable_msg!(QueryChannelRange, {
2534         chain_hash,
2535         first_blocknum,
2536         number_of_blocks
2537 }, {});
2538
2539 impl Readable for ReplyChannelRange {
2540         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2541                 let chain_hash: BlockHash = Readable::read(r)?;
2542                 let first_blocknum: u32 = Readable::read(r)?;
2543                 let number_of_blocks: u32 = Readable::read(r)?;
2544                 let sync_complete: bool = Readable::read(r)?;
2545
2546                 let encoding_len: u16 = Readable::read(r)?;
2547                 let encoding_type: u8 = Readable::read(r)?;
2548
2549                 // Must be encoding_type=0 uncompressed serialization. We do not
2550                 // support encoding_type=1 zlib serialization.
2551                 if encoding_type != EncodingType::Uncompressed as u8 {
2552                         return Err(DecodeError::UnsupportedCompression);
2553                 }
2554
2555                 // We expect the encoding_len to always includes the 1-byte
2556                 // encoding_type and that short_channel_ids are 8-bytes each
2557                 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
2558                         return Err(DecodeError::InvalidValue);
2559                 }
2560
2561                 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
2562                 // less the 1-byte encoding_type
2563                 let short_channel_id_count: u16 = (encoding_len - 1)/8;
2564                 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
2565                 for _ in 0..short_channel_id_count {
2566                         short_channel_ids.push(Readable::read(r)?);
2567                 }
2568
2569                 Ok(ReplyChannelRange {
2570                         chain_hash,
2571                         first_blocknum,
2572                         number_of_blocks,
2573                         sync_complete,
2574                         short_channel_ids
2575                 })
2576         }
2577 }
2578
2579 impl Writeable for ReplyChannelRange {
2580         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2581                 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
2582                 self.chain_hash.write(w)?;
2583                 self.first_blocknum.write(w)?;
2584                 self.number_of_blocks.write(w)?;
2585                 self.sync_complete.write(w)?;
2586
2587                 encoding_len.write(w)?;
2588                 (EncodingType::Uncompressed as u8).write(w)?;
2589                 for scid in self.short_channel_ids.iter() {
2590                         scid.write(w)?;
2591                 }
2592
2593                 Ok(())
2594         }
2595 }
2596
2597 impl_writeable_msg!(GossipTimestampFilter, {
2598         chain_hash,
2599         first_timestamp,
2600         timestamp_range,
2601 }, {});
2602
2603 #[cfg(test)]
2604 mod tests {
2605         use std::convert::TryFrom;
2606         use bitcoin::blockdata::constants::ChainHash;
2607         use bitcoin::{Transaction, PackedLockTime, TxIn, Script, Sequence, Witness, TxOut};
2608         use hex;
2609         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
2610         use crate::ln::ChannelId;
2611         use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
2612         use crate::ln::msgs::{self, FinalOnionHopData, OnionErrorPacket};
2613         use crate::ln::msgs::SocketAddress;
2614         use crate::routing::gossip::{NodeAlias, NodeId};
2615         use crate::util::ser::{Writeable, Readable, Hostname, TransactionU16LenLimited};
2616
2617         use bitcoin::hashes::hex::FromHex;
2618         use bitcoin::util::address::Address;
2619         use bitcoin::network::constants::Network;
2620         use bitcoin::blockdata::script::Builder;
2621         use bitcoin::blockdata::opcodes;
2622         use bitcoin::hash_types::{Txid, BlockHash};
2623
2624         use bitcoin::secp256k1::{PublicKey,SecretKey};
2625         use bitcoin::secp256k1::{Secp256k1, Message};
2626
2627         use crate::io::{self, Cursor};
2628         use crate::prelude::*;
2629         use core::str::FromStr;
2630         use crate::chain::transaction::OutPoint;
2631
2632         #[cfg(feature = "std")]
2633         use std::net::{Ipv4Addr, Ipv6Addr};
2634         use crate::ln::msgs::SocketAddressParseError;
2635
2636         #[test]
2637         fn encoding_channel_reestablish() {
2638                 let public_key = {
2639                         let secp_ctx = Secp256k1::new();
2640                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
2641                 };
2642
2643                 let cr = msgs::ChannelReestablish {
2644                         channel_id: ChannelId::from_bytes([4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0]),
2645                         next_local_commitment_number: 3,
2646                         next_remote_commitment_number: 4,
2647                         your_last_per_commitment_secret: [9;32],
2648                         my_current_per_commitment_point: public_key,
2649                         next_funding_txid: None,
2650                 };
2651
2652                 let encoded_value = cr.encode();
2653                 assert_eq!(
2654                         encoded_value,
2655                         vec![
2656                                 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, // channel_id
2657                                 0, 0, 0, 0, 0, 0, 0, 3, // next_local_commitment_number
2658                                 0, 0, 0, 0, 0, 0, 0, 4, // next_remote_commitment_number
2659                                 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // your_last_per_commitment_secret
2660                                 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143, // my_current_per_commitment_point
2661                         ]
2662                 );
2663         }
2664
2665         #[test]
2666         fn encoding_channel_reestablish_with_next_funding_txid() {
2667                 let public_key = {
2668                         let secp_ctx = Secp256k1::new();
2669                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
2670                 };
2671
2672                 let cr = msgs::ChannelReestablish {
2673                         channel_id: ChannelId::from_bytes([4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0]),
2674                         next_local_commitment_number: 3,
2675                         next_remote_commitment_number: 4,
2676                         your_last_per_commitment_secret: [9;32],
2677                         my_current_per_commitment_point: public_key,
2678                         next_funding_txid: Some(Txid::from_hash(bitcoin::hashes::Hash::from_slice(&[
2679                                 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
2680                         ]).unwrap())),
2681                 };
2682
2683                 let encoded_value = cr.encode();
2684                 assert_eq!(
2685                         encoded_value,
2686                         vec![
2687                                 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, // channel_id
2688                                 0, 0, 0, 0, 0, 0, 0, 3, // next_local_commitment_number
2689                                 0, 0, 0, 0, 0, 0, 0, 4, // next_remote_commitment_number
2690                                 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // your_last_per_commitment_secret
2691                                 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143, // my_current_per_commitment_point
2692                                 0, // Type (next_funding_txid)
2693                                 32, // Length
2694                                 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, // Value
2695                         ]
2696                 );
2697         }
2698
2699         macro_rules! get_keys_from {
2700                 ($slice: expr, $secp_ctx: expr) => {
2701                         {
2702                                 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
2703                                 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
2704                                 (privkey, pubkey)
2705                         }
2706                 }
2707         }
2708
2709         macro_rules! get_sig_on {
2710                 ($privkey: expr, $ctx: expr, $string: expr) => {
2711                         {
2712                                 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
2713                                 $ctx.sign_ecdsa(&sighash, &$privkey)
2714                         }
2715                 }
2716         }
2717
2718         #[test]
2719         fn encoding_announcement_signatures() {
2720                 let secp_ctx = Secp256k1::new();
2721                 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2722                 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
2723                 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
2724                 let announcement_signatures = msgs::AnnouncementSignatures {
2725                         channel_id: ChannelId::from_bytes([4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0]),
2726                         short_channel_id: 2316138423780173,
2727                         node_signature: sig_1,
2728                         bitcoin_signature: sig_2,
2729                 };
2730
2731                 let encoded_value = announcement_signatures.encode();
2732                 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
2733         }
2734
2735         fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
2736                 let secp_ctx = Secp256k1::new();
2737                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2738                 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2739                 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2740                 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2741                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2742                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2743                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2744                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2745                 let mut features = ChannelFeatures::empty();
2746                 if unknown_features_bits {
2747                         features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
2748                 }
2749                 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
2750                         features,
2751                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2752                         short_channel_id: 2316138423780173,
2753                         node_id_1: NodeId::from_pubkey(&pubkey_1),
2754                         node_id_2: NodeId::from_pubkey(&pubkey_2),
2755                         bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
2756                         bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
2757                         excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
2758                 };
2759                 let channel_announcement = msgs::ChannelAnnouncement {
2760                         node_signature_1: sig_1,
2761                         node_signature_2: sig_2,
2762                         bitcoin_signature_1: sig_3,
2763                         bitcoin_signature_2: sig_4,
2764                         contents: unsigned_channel_announcement,
2765                 };
2766                 let encoded_value = channel_announcement.encode();
2767                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
2768                 if unknown_features_bits {
2769                         target_value.append(&mut hex::decode("0002ffff").unwrap());
2770                 } else {
2771                         target_value.append(&mut hex::decode("0000").unwrap());
2772                 }
2773                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2774                 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
2775                 if excess_data {
2776                         target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
2777                 }
2778                 assert_eq!(encoded_value, target_value);
2779         }
2780
2781         #[test]
2782         fn encoding_channel_announcement() {
2783                 do_encoding_channel_announcement(true, false);
2784                 do_encoding_channel_announcement(false, true);
2785                 do_encoding_channel_announcement(false, false);
2786                 do_encoding_channel_announcement(true, true);
2787         }
2788
2789         fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, hostname: bool, excess_address_data: bool, excess_data: bool) {
2790                 let secp_ctx = Secp256k1::new();
2791                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2792                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2793                 let features = if unknown_features_bits {
2794                         NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
2795                 } else {
2796                         // Set to some features we may support
2797                         NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
2798                 };
2799                 let mut addresses = Vec::new();
2800                 if ipv4 {
2801                         addresses.push(SocketAddress::TcpIpV4 {
2802                                 addr: [255, 254, 253, 252],
2803                                 port: 9735
2804                         });
2805                 }
2806                 if ipv6 {
2807                         addresses.push(SocketAddress::TcpIpV6 {
2808                                 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
2809                                 port: 9735
2810                         });
2811                 }
2812                 if onionv2 {
2813                         addresses.push(msgs::SocketAddress::OnionV2(
2814                                 [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]
2815                         ));
2816                 }
2817                 if onionv3 {
2818                         addresses.push(msgs::SocketAddress::OnionV3 {
2819                                 ed25519_pubkey: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224],
2820                                 checksum: 32,
2821                                 version: 16,
2822                                 port: 9735
2823                         });
2824                 }
2825                 if hostname {
2826                         addresses.push(SocketAddress::Hostname {
2827                                 hostname: Hostname::try_from(String::from("host")).unwrap(),
2828                                 port: 9735,
2829                         });
2830                 }
2831                 let mut addr_len = 0;
2832                 for addr in &addresses {
2833                         addr_len += addr.len() + 1;
2834                 }
2835                 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
2836                         features,
2837                         timestamp: 20190119,
2838                         node_id: NodeId::from_pubkey(&pubkey_1),
2839                         rgb: [32; 3],
2840                         alias: NodeAlias([16;32]),
2841                         addresses,
2842                         excess_address_data: if excess_address_data { vec![33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34, 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105] } else { Vec::new() },
2843                         excess_data: if excess_data { vec![59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160, 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253] } else { Vec::new() },
2844                 };
2845                 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
2846                 let node_announcement = msgs::NodeAnnouncement {
2847                         signature: sig_1,
2848                         contents: unsigned_node_announcement,
2849                 };
2850                 let encoded_value = node_announcement.encode();
2851                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2852                 if unknown_features_bits {
2853                         target_value.append(&mut hex::decode("0002ffff").unwrap());
2854                 } else {
2855                         target_value.append(&mut hex::decode("000122").unwrap());
2856                 }
2857                 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
2858                 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
2859                 if ipv4 {
2860                         target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
2861                 }
2862                 if ipv6 {
2863                         target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
2864                 }
2865                 if onionv2 {
2866                         target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
2867                 }
2868                 if onionv3 {
2869                         target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
2870                 }
2871                 if hostname {
2872                         target_value.append(&mut hex::decode("0504686f73742607").unwrap());
2873                 }
2874                 if excess_address_data {
2875                         target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
2876                 }
2877                 if excess_data {
2878                         target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2879                 }
2880                 assert_eq!(encoded_value, target_value);
2881         }
2882
2883         #[test]
2884         fn encoding_node_announcement() {
2885                 do_encoding_node_announcement(true, true, true, true, true, true, true, true);
2886                 do_encoding_node_announcement(false, false, false, false, false, false, false, false);
2887                 do_encoding_node_announcement(false, true, false, false, false, false, false, false);
2888                 do_encoding_node_announcement(false, false, true, false, false, false, false, false);
2889                 do_encoding_node_announcement(false, false, false, true, false, false, false, false);
2890                 do_encoding_node_announcement(false, false, false, false, true, false, false, false);
2891                 do_encoding_node_announcement(false, false, false, false, false, true, false, false);
2892                 do_encoding_node_announcement(false, false, false, false, false, false, true, false);
2893                 do_encoding_node_announcement(false, true, false, true, false, false, true, false);
2894                 do_encoding_node_announcement(false, false, true, false, true, false, false, false);
2895         }
2896
2897         fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
2898                 let secp_ctx = Secp256k1::new();
2899                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2900                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2901                 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
2902                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2903                         short_channel_id: 2316138423780173,
2904                         timestamp: 20190119,
2905                         flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
2906                         cltv_expiry_delta: 144,
2907                         htlc_minimum_msat: 1000000,
2908                         htlc_maximum_msat: 131355275467161,
2909                         fee_base_msat: 10000,
2910                         fee_proportional_millionths: 20,
2911                         excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
2912                 };
2913                 let channel_update = msgs::ChannelUpdate {
2914                         signature: sig_1,
2915                         contents: unsigned_channel_update
2916                 };
2917                 let encoded_value = channel_update.encode();
2918                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2919                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2920                 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
2921                 target_value.append(&mut hex::decode("01").unwrap());
2922                 target_value.append(&mut hex::decode("00").unwrap());
2923                 if direction {
2924                         let flag = target_value.last_mut().unwrap();
2925                         *flag = 1;
2926                 }
2927                 if disable {
2928                         let flag = target_value.last_mut().unwrap();
2929                         *flag = *flag | 1 << 1;
2930                 }
2931                 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
2932                 target_value.append(&mut hex::decode("0000777788889999").unwrap());
2933                 if excess_data {
2934                         target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
2935                 }
2936                 assert_eq!(encoded_value, target_value);
2937         }
2938
2939         #[test]
2940         fn encoding_channel_update() {
2941                 do_encoding_channel_update(false, false, false);
2942                 do_encoding_channel_update(false, false, true);
2943                 do_encoding_channel_update(true, false, false);
2944                 do_encoding_channel_update(true, false, true);
2945                 do_encoding_channel_update(false, true, false);
2946                 do_encoding_channel_update(false, true, true);
2947                 do_encoding_channel_update(true, true, false);
2948                 do_encoding_channel_update(true, true, true);
2949         }
2950
2951         fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
2952                 let secp_ctx = Secp256k1::new();
2953                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2954                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2955                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2956                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2957                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2958                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2959                 let open_channel = msgs::OpenChannel {
2960                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2961                         temporary_channel_id: ChannelId::from_bytes([2; 32]),
2962                         funding_satoshis: 1311768467284833366,
2963                         push_msat: 2536655962884945560,
2964                         dust_limit_satoshis: 3608586615801332854,
2965                         max_htlc_value_in_flight_msat: 8517154655701053848,
2966                         channel_reserve_satoshis: 8665828695742877976,
2967                         htlc_minimum_msat: 2316138423780173,
2968                         feerate_per_kw: 821716,
2969                         to_self_delay: 49340,
2970                         max_accepted_htlcs: 49340,
2971                         funding_pubkey: pubkey_1,
2972                         revocation_basepoint: pubkey_2,
2973                         payment_point: pubkey_3,
2974                         delayed_payment_basepoint: pubkey_4,
2975                         htlc_basepoint: pubkey_5,
2976                         first_per_commitment_point: pubkey_6,
2977                         channel_flags: if random_bit { 1 << 5 } else { 0 },
2978                         shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
2979                         channel_type: if incl_chan_type { Some(ChannelTypeFeatures::empty()) } else { None },
2980                 };
2981                 let encoded_value = open_channel.encode();
2982                 let mut target_value = Vec::new();
2983                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2984                 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
2985                 if random_bit {
2986                         target_value.append(&mut hex::decode("20").unwrap());
2987                 } else {
2988                         target_value.append(&mut hex::decode("00").unwrap());
2989                 }
2990                 if shutdown {
2991                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2992                 }
2993                 if incl_chan_type {
2994                         target_value.append(&mut hex::decode("0100").unwrap());
2995                 }
2996                 assert_eq!(encoded_value, target_value);
2997         }
2998
2999         #[test]
3000         fn encoding_open_channel() {
3001                 do_encoding_open_channel(false, false, false);
3002                 do_encoding_open_channel(false, false, true);
3003                 do_encoding_open_channel(false, true, false);
3004                 do_encoding_open_channel(false, true, true);
3005                 do_encoding_open_channel(true, false, false);
3006                 do_encoding_open_channel(true, false, true);
3007                 do_encoding_open_channel(true, true, false);
3008                 do_encoding_open_channel(true, true, true);
3009         }
3010
3011         fn do_encoding_open_channelv2(random_bit: bool, shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool) {
3012                 let secp_ctx = Secp256k1::new();
3013                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3014                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3015                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3016                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3017                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3018                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3019                 let (_, pubkey_7) = get_keys_from!("0707070707070707070707070707070707070707070707070707070707070707", secp_ctx);
3020                 let open_channelv2 = msgs::OpenChannelV2 {
3021                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
3022                         temporary_channel_id: ChannelId::from_bytes([2; 32]),
3023                         funding_feerate_sat_per_1000_weight: 821716,
3024                         commitment_feerate_sat_per_1000_weight: 821716,
3025                         funding_satoshis: 1311768467284833366,
3026                         dust_limit_satoshis: 3608586615801332854,
3027                         max_htlc_value_in_flight_msat: 8517154655701053848,
3028                         htlc_minimum_msat: 2316138423780173,
3029                         to_self_delay: 49340,
3030                         max_accepted_htlcs: 49340,
3031                         locktime: 305419896,
3032                         funding_pubkey: pubkey_1,
3033                         revocation_basepoint: pubkey_2,
3034                         payment_basepoint: pubkey_3,
3035                         delayed_payment_basepoint: pubkey_4,
3036                         htlc_basepoint: pubkey_5,
3037                         first_per_commitment_point: pubkey_6,
3038                         second_per_commitment_point: pubkey_7,
3039                         channel_flags: if random_bit { 1 << 5 } else { 0 },
3040                         shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3041                         channel_type: if incl_chan_type { Some(ChannelTypeFeatures::empty()) } else { None },
3042                         require_confirmed_inputs: if require_confirmed_inputs { Some(()) } else { None },
3043                 };
3044                 let encoded_value = open_channelv2.encode();
3045                 let mut target_value = Vec::new();
3046                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
3047                 target_value.append(&mut hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap());
3048                 target_value.append(&mut hex::decode("000c89d4").unwrap());
3049                 target_value.append(&mut hex::decode("000c89d4").unwrap());
3050                 target_value.append(&mut hex::decode("1234567890123456").unwrap());
3051                 target_value.append(&mut hex::decode("3214466870114476").unwrap());
3052                 target_value.append(&mut hex::decode("7633030896203198").unwrap());
3053                 target_value.append(&mut hex::decode("00083a840000034d").unwrap());
3054                 target_value.append(&mut hex::decode("c0bc").unwrap());
3055                 target_value.append(&mut hex::decode("c0bc").unwrap());
3056                 target_value.append(&mut hex::decode("12345678").unwrap());
3057                 target_value.append(&mut hex::decode("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap());
3058                 target_value.append(&mut hex::decode("024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766").unwrap());
3059                 target_value.append(&mut hex::decode("02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337").unwrap());
3060                 target_value.append(&mut hex::decode("03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
3061                 target_value.append(&mut hex::decode("0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7").unwrap());
3062                 target_value.append(&mut hex::decode("03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
3063                 target_value.append(&mut hex::decode("02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f").unwrap());
3064
3065                 if random_bit {
3066                         target_value.append(&mut hex::decode("20").unwrap());
3067                 } else {
3068                         target_value.append(&mut hex::decode("00").unwrap());
3069                 }
3070                 if shutdown {
3071                         target_value.append(&mut hex::decode("001b").unwrap()); // Type 0 + Length 27
3072                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3073                 }
3074                 if incl_chan_type {
3075                         target_value.append(&mut hex::decode("0100").unwrap());
3076                 }
3077                 if require_confirmed_inputs {
3078                         target_value.append(&mut hex::decode("0200").unwrap());
3079                 }
3080                 assert_eq!(encoded_value, target_value);
3081         }
3082
3083         #[test]
3084         fn encoding_open_channelv2() {
3085                 do_encoding_open_channelv2(false, false, false, false);
3086                 do_encoding_open_channelv2(false, false, false, true);
3087                 do_encoding_open_channelv2(false, false, true, false);
3088                 do_encoding_open_channelv2(false, false, true, true);
3089                 do_encoding_open_channelv2(false, true, false, false);
3090                 do_encoding_open_channelv2(false, true, false, true);
3091                 do_encoding_open_channelv2(false, true, true, false);
3092                 do_encoding_open_channelv2(false, true, true, true);
3093                 do_encoding_open_channelv2(true, false, false, false);
3094                 do_encoding_open_channelv2(true, false, false, true);
3095                 do_encoding_open_channelv2(true, false, true, false);
3096                 do_encoding_open_channelv2(true, false, true, true);
3097                 do_encoding_open_channelv2(true, true, false, false);
3098                 do_encoding_open_channelv2(true, true, false, true);
3099                 do_encoding_open_channelv2(true, true, true, false);
3100                 do_encoding_open_channelv2(true, true, true, true);
3101         }
3102
3103         fn do_encoding_accept_channel(shutdown: bool) {
3104                 let secp_ctx = Secp256k1::new();
3105                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3106                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3107                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3108                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3109                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3110                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3111                 let accept_channel = msgs::AcceptChannel {
3112                         temporary_channel_id: ChannelId::from_bytes([2; 32]),
3113                         dust_limit_satoshis: 1311768467284833366,
3114                         max_htlc_value_in_flight_msat: 2536655962884945560,
3115                         channel_reserve_satoshis: 3608586615801332854,
3116                         htlc_minimum_msat: 2316138423780173,
3117                         minimum_depth: 821716,
3118                         to_self_delay: 49340,
3119                         max_accepted_htlcs: 49340,
3120                         funding_pubkey: pubkey_1,
3121                         revocation_basepoint: pubkey_2,
3122                         payment_point: pubkey_3,
3123                         delayed_payment_basepoint: pubkey_4,
3124                         htlc_basepoint: pubkey_5,
3125                         first_per_commitment_point: pubkey_6,
3126                         shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3127                         channel_type: None,
3128                         #[cfg(taproot)]
3129                         next_local_nonce: None,
3130                 };
3131                 let encoded_value = accept_channel.encode();
3132                 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
3133                 if shutdown {
3134                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3135                 }
3136                 assert_eq!(encoded_value, target_value);
3137         }
3138
3139         #[test]
3140         fn encoding_accept_channel() {
3141                 do_encoding_accept_channel(false);
3142                 do_encoding_accept_channel(true);
3143         }
3144
3145         fn do_encoding_accept_channelv2(shutdown: bool) {
3146                 let secp_ctx = Secp256k1::new();
3147                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3148                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3149                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3150                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3151                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3152                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3153                 let (_, pubkey_7) = get_keys_from!("0707070707070707070707070707070707070707070707070707070707070707", secp_ctx);
3154                 let accept_channelv2 = msgs::AcceptChannelV2 {
3155                         temporary_channel_id: ChannelId::from_bytes([2; 32]),
3156                         funding_satoshis: 1311768467284833366,
3157                         dust_limit_satoshis: 1311768467284833366,
3158                         max_htlc_value_in_flight_msat: 2536655962884945560,
3159                         htlc_minimum_msat: 2316138423780173,
3160                         minimum_depth: 821716,
3161                         to_self_delay: 49340,
3162                         max_accepted_htlcs: 49340,
3163                         funding_pubkey: pubkey_1,
3164                         revocation_basepoint: pubkey_2,
3165                         payment_basepoint: pubkey_3,
3166                         delayed_payment_basepoint: pubkey_4,
3167                         htlc_basepoint: pubkey_5,
3168                         first_per_commitment_point: pubkey_6,
3169                         second_per_commitment_point: pubkey_7,
3170                         shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3171                         channel_type: None,
3172                         require_confirmed_inputs: None,
3173                 };
3174                 let encoded_value = accept_channelv2.encode();
3175                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); // temporary_channel_id
3176                 target_value.append(&mut hex::decode("1234567890123456").unwrap()); // funding_satoshis
3177                 target_value.append(&mut hex::decode("1234567890123456").unwrap()); // dust_limit_satoshis
3178                 target_value.append(&mut hex::decode("2334032891223698").unwrap()); // max_htlc_value_in_flight_msat
3179                 target_value.append(&mut hex::decode("00083a840000034d").unwrap()); // htlc_minimum_msat
3180                 target_value.append(&mut hex::decode("000c89d4").unwrap()); //  minimum_depth
3181                 target_value.append(&mut hex::decode("c0bc").unwrap()); // to_self_delay
3182                 target_value.append(&mut hex::decode("c0bc").unwrap()); // max_accepted_htlcs
3183                 target_value.append(&mut hex::decode("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap()); // funding_pubkey
3184                 target_value.append(&mut hex::decode("024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766").unwrap()); // revocation_basepoint
3185                 target_value.append(&mut hex::decode("02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337").unwrap()); // payment_basepoint
3186                 target_value.append(&mut hex::decode("03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap()); // delayed_payment_basepoint
3187                 target_value.append(&mut hex::decode("0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7").unwrap()); // htlc_basepoint
3188                 target_value.append(&mut hex::decode("03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap()); // first_per_commitment_point
3189                 target_value.append(&mut hex::decode("02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f").unwrap()); // second_per_commitment_point
3190                 if shutdown {
3191                         target_value.append(&mut hex::decode("001b").unwrap()); // Type 0 + Length 27
3192                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3193                 }
3194                 assert_eq!(encoded_value, target_value);
3195         }
3196
3197         #[test]
3198         fn encoding_accept_channelv2() {
3199                 do_encoding_accept_channelv2(false);
3200                 do_encoding_accept_channelv2(true);
3201         }
3202
3203         #[test]
3204         fn encoding_funding_created() {
3205                 let secp_ctx = Secp256k1::new();
3206                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3207                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3208                 let funding_created = msgs::FundingCreated {
3209                         temporary_channel_id: ChannelId::from_bytes([2; 32]),
3210                         funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
3211                         funding_output_index: 255,
3212                         signature: sig_1,
3213                         #[cfg(taproot)]
3214                         partial_signature_with_nonce: None,
3215                         #[cfg(taproot)]
3216                         next_local_nonce: None,
3217                 };
3218                 let encoded_value = funding_created.encode();
3219                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3220                 assert_eq!(encoded_value, target_value);
3221         }
3222
3223         #[test]
3224         fn encoding_funding_signed() {
3225                 let secp_ctx = Secp256k1::new();
3226                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3227                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3228                 let funding_signed = msgs::FundingSigned {
3229                         channel_id: ChannelId::from_bytes([2; 32]),
3230                         signature: sig_1,
3231                         #[cfg(taproot)]
3232                         partial_signature_with_nonce: None,
3233                 };
3234                 let encoded_value = funding_signed.encode();
3235                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3236                 assert_eq!(encoded_value, target_value);
3237         }
3238
3239         #[test]
3240         fn encoding_channel_ready() {
3241                 let secp_ctx = Secp256k1::new();
3242                 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3243                 let channel_ready = msgs::ChannelReady {
3244                         channel_id: ChannelId::from_bytes([2; 32]),
3245                         next_per_commitment_point: pubkey_1,
3246                         short_channel_id_alias: None,
3247                 };
3248                 let encoded_value = channel_ready.encode();
3249                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
3250                 assert_eq!(encoded_value, target_value);
3251         }
3252
3253         #[test]
3254         fn encoding_tx_add_input() {
3255                 let tx_add_input = msgs::TxAddInput {
3256                         channel_id: ChannelId::from_bytes([2; 32]),
3257                         serial_id: 4886718345,
3258                         prevtx: TransactionU16LenLimited::new(Transaction {
3259                                 version: 2,
3260                                 lock_time: PackedLockTime(0),
3261                                 input: vec![TxIn {
3262                                         previous_output: OutPoint { txid: Txid::from_hex("305bab643ee297b8b6b76b320792c8223d55082122cb606bf89382146ced9c77").unwrap(), index: 2 }.into_bitcoin_outpoint(),
3263                                         script_sig: Script::new(),
3264                                         sequence: Sequence(0xfffffffd),
3265                                         witness: Witness::from_vec(vec![
3266                                                 hex::decode("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
3267                                                 hex::decode("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
3268                                 }],
3269                                 output: vec![
3270                                         TxOut {
3271                                                 value: 12704566,
3272                                                 script_pubkey: Address::from_str("bc1qzlffunw52jav8vwdu5x3jfk6sr8u22rmq3xzw2").unwrap().script_pubkey(),
3273                                         },
3274                                         TxOut {
3275                                                 value: 245148,
3276                                                 script_pubkey: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().script_pubkey(),
3277                                         },
3278                                 ],
3279                         }).unwrap(),
3280                         prevtx_out: 305419896,
3281                         sequence: 305419896,
3282                 };
3283                 let encoded_value = tx_add_input.encode();
3284                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000000012345678900de02000000000101779ced6c148293f86b60cb222108553d22c89207326bb7b6b897e23e64ab5b300200000000fdffffff0236dbc1000000000016001417d29e4dd454bac3b1cde50d1926da80cfc5287b9cbd03000000000016001436ec78d514df462da95e6a00c24daa8915362d420247304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701210301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944000000001234567812345678").unwrap();
3285                 assert_eq!(encoded_value, target_value);
3286         }
3287
3288         #[test]
3289         fn encoding_tx_add_output() {
3290                 let tx_add_output = msgs::TxAddOutput {
3291                         channel_id: ChannelId::from_bytes([2; 32]),
3292                         serial_id: 4886718345,
3293                         sats: 4886718345,
3294                         script: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().script_pubkey(),
3295                 };
3296                 let encoded_value = tx_add_output.encode();
3297                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000000012345678900000001234567890016001436ec78d514df462da95e6a00c24daa8915362d42").unwrap();
3298                 assert_eq!(encoded_value, target_value);
3299         }
3300
3301         #[test]
3302         fn encoding_tx_remove_input() {
3303                 let tx_remove_input = msgs::TxRemoveInput {
3304                         channel_id: ChannelId::from_bytes([2; 32]),
3305                         serial_id: 4886718345,
3306                 };
3307                 let encoded_value = tx_remove_input.encode();
3308                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020000000123456789").unwrap();
3309                 assert_eq!(encoded_value, target_value);
3310         }
3311
3312         #[test]
3313         fn encoding_tx_remove_output() {
3314                 let tx_remove_output = msgs::TxRemoveOutput {
3315                         channel_id: ChannelId::from_bytes([2; 32]),
3316                         serial_id: 4886718345,
3317                 };
3318                 let encoded_value = tx_remove_output.encode();
3319                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020000000123456789").unwrap();
3320                 assert_eq!(encoded_value, target_value);
3321         }
3322
3323         #[test]
3324         fn encoding_tx_complete() {
3325                 let tx_complete = msgs::TxComplete {
3326                         channel_id: ChannelId::from_bytes([2; 32]),
3327                 };
3328                 let encoded_value = tx_complete.encode();
3329                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
3330                 assert_eq!(encoded_value, target_value);
3331         }
3332
3333         #[test]
3334         fn encoding_tx_signatures() {
3335                 let tx_signatures = msgs::TxSignatures {
3336                         channel_id: ChannelId::from_bytes([2; 32]),
3337                         tx_hash: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
3338                         witnesses: vec![
3339                                 Witness::from_vec(vec![
3340                                         hex::decode("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
3341                                         hex::decode("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
3342                                 Witness::from_vec(vec![
3343                                         hex::decode("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap(),
3344                                         hex::decode("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap()]),
3345                         ],
3346                 };
3347                 let encoded_value = tx_signatures.encode();
3348                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); // channel_id
3349                 target_value.append(&mut hex::decode("6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2").unwrap()); // tx_hash (sha256) (big endian byte order)
3350                 target_value.append(&mut hex::decode("0002").unwrap()); // num_witnesses (u16)
3351                 // Witness 1
3352                 target_value.append(&mut hex::decode("006b").unwrap()); // len of witness_data
3353                 target_value.append(&mut hex::decode("02").unwrap()); // num_witness_elements (VarInt)
3354                 target_value.append(&mut hex::decode("47").unwrap()); // len of witness element data (VarInt)
3355                 target_value.append(&mut hex::decode("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap());
3356                 target_value.append(&mut hex::decode("21").unwrap()); // len of witness element data (VarInt)
3357                 target_value.append(&mut hex::decode("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap());
3358                 // Witness 2
3359                 target_value.append(&mut hex::decode("006c").unwrap()); // len of witness_data
3360                 target_value.append(&mut hex::decode("02").unwrap()); // num_witness_elements (VarInt)
3361                 target_value.append(&mut hex::decode("48").unwrap()); // len of witness element data (VarInt)
3362                 target_value.append(&mut hex::decode("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap());
3363                 target_value.append(&mut hex::decode("21").unwrap()); // len of witness element data (VarInt)
3364                 target_value.append(&mut hex::decode("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap());
3365                 assert_eq!(encoded_value, target_value);
3366         }
3367
3368         fn do_encoding_tx_init_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
3369                 let tx_init_rbf = msgs::TxInitRbf {
3370                         channel_id: ChannelId::from_bytes([2; 32]),
3371                         locktime: 305419896,
3372                         feerate_sat_per_1000_weight: 20190119,
3373                         funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target { Some(value) } else { None },
3374                 };
3375                 let encoded_value = tx_init_rbf.encode();
3376                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); // channel_id
3377                 target_value.append(&mut hex::decode("12345678").unwrap()); // locktime
3378                 target_value.append(&mut hex::decode("013413a7").unwrap()); // feerate_sat_per_1000_weight
3379                 if let Some((_, target)) = funding_value_with_hex_target {
3380                         target_value.push(0x00); // Type
3381                         target_value.push(target.len() as u8 / 2); // Length
3382                         target_value.append(&mut hex::decode(target).unwrap()); // Value (i64)
3383                 }
3384                 assert_eq!(encoded_value, target_value);
3385         }
3386
3387         #[test]
3388         fn encoding_tx_init_rbf() {
3389                 do_encoding_tx_init_rbf(Some((1311768467284833366, "1234567890123456")));
3390                 do_encoding_tx_init_rbf(Some((13117684672, "000000030DDFFBC0")));
3391                 do_encoding_tx_init_rbf(None);
3392         }
3393
3394         fn do_encoding_tx_ack_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
3395                 let tx_ack_rbf = msgs::TxAckRbf {
3396                         channel_id: ChannelId::from_bytes([2; 32]),
3397                         funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target { Some(value) } else { None },
3398                 };
3399                 let encoded_value = tx_ack_rbf.encode();
3400                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
3401                 if let Some((_, target)) = funding_value_with_hex_target {
3402                         target_value.push(0x00); // Type
3403                         target_value.push(target.len() as u8 / 2); // Length
3404                         target_value.append(&mut hex::decode(target).unwrap()); // Value (i64)
3405                 }
3406                 assert_eq!(encoded_value, target_value);
3407         }
3408
3409         #[test]
3410         fn encoding_tx_ack_rbf() {
3411                 do_encoding_tx_ack_rbf(Some((1311768467284833366, "1234567890123456")));
3412                 do_encoding_tx_ack_rbf(Some((13117684672, "000000030DDFFBC0")));
3413                 do_encoding_tx_ack_rbf(None);
3414         }
3415
3416         #[test]
3417         fn encoding_tx_abort() {
3418                 let tx_abort = msgs::TxAbort {
3419                         channel_id: ChannelId::from_bytes([2; 32]),
3420                         data: hex::decode("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(),
3421                 };
3422                 let encoded_value = tx_abort.encode();
3423                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap();
3424                 assert_eq!(encoded_value, target_value);
3425         }
3426
3427         fn do_encoding_shutdown(script_type: u8) {
3428                 let secp_ctx = Secp256k1::new();
3429                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3430                 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
3431                 let shutdown = msgs::Shutdown {
3432                         channel_id: ChannelId::from_bytes([2; 32]),
3433                         scriptpubkey:
3434                                 if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey() }
3435                                 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey() }
3436                                 else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).unwrap().script_pubkey() }
3437                                 else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
3438                 };
3439                 let encoded_value = shutdown.encode();
3440                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
3441                 if script_type == 1 {
3442                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3443                 } else if script_type == 2 {
3444                         target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
3445                 } else if script_type == 3 {
3446                         target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
3447                 } else if script_type == 4 {
3448                         target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
3449                 }
3450                 assert_eq!(encoded_value, target_value);
3451         }
3452
3453         #[test]
3454         fn encoding_shutdown() {
3455                 do_encoding_shutdown(1);
3456                 do_encoding_shutdown(2);
3457                 do_encoding_shutdown(3);
3458                 do_encoding_shutdown(4);
3459         }
3460
3461         #[test]
3462         fn encoding_closing_signed() {
3463                 let secp_ctx = Secp256k1::new();
3464                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3465                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3466                 let closing_signed = msgs::ClosingSigned {
3467                         channel_id: ChannelId::from_bytes([2; 32]),
3468                         fee_satoshis: 2316138423780173,
3469                         signature: sig_1,
3470                         fee_range: None,
3471                 };
3472                 let encoded_value = closing_signed.encode();
3473                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3474                 assert_eq!(encoded_value, target_value);
3475                 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value)).unwrap(), closing_signed);
3476
3477                 let closing_signed_with_range = msgs::ClosingSigned {
3478                         channel_id: ChannelId::from_bytes([2; 32]),
3479                         fee_satoshis: 2316138423780173,
3480                         signature: sig_1,
3481                         fee_range: Some(msgs::ClosingSignedFeeRange {
3482                                 min_fee_satoshis: 0xdeadbeef,
3483                                 max_fee_satoshis: 0x1badcafe01234567,
3484                         }),
3485                 };
3486                 let encoded_value_with_range = closing_signed_with_range.encode();
3487                 let target_value_with_range = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
3488                 assert_eq!(encoded_value_with_range, target_value_with_range);
3489                 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value_with_range)).unwrap(),
3490                         closing_signed_with_range);
3491         }
3492
3493         #[test]
3494         fn encoding_update_add_htlc() {
3495                 let secp_ctx = Secp256k1::new();
3496                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3497                 let onion_routing_packet = msgs::OnionPacket {
3498                         version: 255,
3499                         public_key: Ok(pubkey_1),
3500                         hop_data: [1; 20*65],
3501                         hmac: [2; 32]
3502                 };
3503                 let update_add_htlc = msgs::UpdateAddHTLC {
3504                         channel_id: ChannelId::from_bytes([2; 32]),
3505                         htlc_id: 2316138423780173,
3506                         amount_msat: 3608586615801332854,
3507                         payment_hash: PaymentHash([1; 32]),
3508                         cltv_expiry: 821716,
3509                         onion_routing_packet,
3510                         skimmed_fee_msat: None,
3511                 };
3512                 let encoded_value = update_add_htlc.encode();
3513                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
3514                 assert_eq!(encoded_value, target_value);
3515         }
3516
3517         #[test]
3518         fn encoding_update_fulfill_htlc() {
3519                 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
3520                         channel_id: ChannelId::from_bytes([2; 32]),
3521                         htlc_id: 2316138423780173,
3522                         payment_preimage: PaymentPreimage([1; 32]),
3523                 };
3524                 let encoded_value = update_fulfill_htlc.encode();
3525                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
3526                 assert_eq!(encoded_value, target_value);
3527         }
3528
3529         #[test]
3530         fn encoding_update_fail_htlc() {
3531                 let reason = OnionErrorPacket {
3532                         data: [1; 32].to_vec(),
3533                 };
3534                 let update_fail_htlc = msgs::UpdateFailHTLC {
3535                         channel_id: ChannelId::from_bytes([2; 32]),
3536                         htlc_id: 2316138423780173,
3537                         reason
3538                 };
3539                 let encoded_value = update_fail_htlc.encode();
3540                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
3541                 assert_eq!(encoded_value, target_value);
3542         }
3543
3544         #[test]
3545         fn encoding_update_fail_malformed_htlc() {
3546                 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
3547                         channel_id: ChannelId::from_bytes([2; 32]),
3548                         htlc_id: 2316138423780173,
3549                         sha256_of_onion: [1; 32],
3550                         failure_code: 255
3551                 };
3552                 let encoded_value = update_fail_malformed_htlc.encode();
3553                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
3554                 assert_eq!(encoded_value, target_value);
3555         }
3556
3557         fn do_encoding_commitment_signed(htlcs: bool) {
3558                 let secp_ctx = Secp256k1::new();
3559                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3560                 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3561                 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3562                 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3563                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3564                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
3565                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
3566                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
3567                 let commitment_signed = msgs::CommitmentSigned {
3568                         channel_id: ChannelId::from_bytes([2; 32]),
3569                         signature: sig_1,
3570                         htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
3571                         #[cfg(taproot)]
3572                         partial_signature_with_nonce: None,
3573                 };
3574                 let encoded_value = commitment_signed.encode();
3575                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3576                 if htlcs {
3577                         target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
3578                 } else {
3579                         target_value.append(&mut hex::decode("0000").unwrap());
3580                 }
3581                 assert_eq!(encoded_value, target_value);
3582         }
3583
3584         #[test]
3585         fn encoding_commitment_signed() {
3586                 do_encoding_commitment_signed(true);
3587                 do_encoding_commitment_signed(false);
3588         }
3589
3590         #[test]
3591         fn encoding_revoke_and_ack() {
3592                 let secp_ctx = Secp256k1::new();
3593                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3594                 let raa = msgs::RevokeAndACK {
3595                         channel_id: ChannelId::from_bytes([2; 32]),
3596                         per_commitment_secret: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
3597                         next_per_commitment_point: pubkey_1,
3598                         #[cfg(taproot)]
3599                         next_local_nonce: None,
3600                 };
3601                 let encoded_value = raa.encode();
3602                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
3603                 assert_eq!(encoded_value, target_value);
3604         }
3605
3606         #[test]
3607         fn encoding_update_fee() {
3608                 let update_fee = msgs::UpdateFee {
3609                         channel_id: ChannelId::from_bytes([2; 32]),
3610                         feerate_per_kw: 20190119,
3611                 };
3612                 let encoded_value = update_fee.encode();
3613                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
3614                 assert_eq!(encoded_value, target_value);
3615         }
3616
3617         #[test]
3618         fn encoding_init() {
3619                 let mainnet_hash = ChainHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap();
3620                 assert_eq!(msgs::Init {
3621                         features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
3622                         networks: Some(vec![mainnet_hash]),
3623                         remote_network_address: None,
3624                 }.encode(), hex::decode("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3625                 assert_eq!(msgs::Init {
3626                         features: InitFeatures::from_le_bytes(vec![0xFF]),
3627                         networks: None,
3628                         remote_network_address: None,
3629                 }.encode(), hex::decode("0001ff0001ff").unwrap());
3630                 assert_eq!(msgs::Init {
3631                         features: InitFeatures::from_le_bytes(vec![]),
3632                         networks: Some(vec![mainnet_hash]),
3633                         remote_network_address: None,
3634                 }.encode(), hex::decode("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3635                 assert_eq!(msgs::Init {
3636                         features: InitFeatures::from_le_bytes(vec![]),
3637                         networks: Some(vec![ChainHash::from(&[1; 32][..]), ChainHash::from(&[2; 32][..])]),
3638                         remote_network_address: None,
3639                 }.encode(), hex::decode("00000000014001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap());
3640                 let init_msg = msgs::Init { features: InitFeatures::from_le_bytes(vec![]),
3641                         networks: Some(vec![mainnet_hash]),
3642                         remote_network_address: Some(SocketAddress::TcpIpV4 {
3643                                 addr: [127, 0, 0, 1],
3644                                 port: 1000,
3645                         }),
3646                 };
3647                 let encoded_value = init_msg.encode();
3648                 let target_value = hex::decode("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap();
3649                 assert_eq!(encoded_value, target_value);
3650                 assert_eq!(msgs::Init::read(&mut Cursor::new(&target_value)).unwrap(), init_msg);
3651         }
3652
3653         #[test]
3654         fn encoding_error() {
3655                 let error = msgs::ErrorMessage {
3656                         channel_id: ChannelId::from_bytes([2; 32]),
3657                         data: String::from("rust-lightning"),
3658                 };
3659                 let encoded_value = error.encode();
3660                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
3661                 assert_eq!(encoded_value, target_value);
3662         }
3663
3664         #[test]
3665         fn encoding_warning() {
3666                 let error = msgs::WarningMessage {
3667                         channel_id: ChannelId::from_bytes([2; 32]),
3668                         data: String::from("rust-lightning"),
3669                 };
3670                 let encoded_value = error.encode();
3671                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
3672                 assert_eq!(encoded_value, target_value);
3673         }
3674
3675         #[test]
3676         fn encoding_ping() {
3677                 let ping = msgs::Ping {
3678                         ponglen: 64,
3679                         byteslen: 64
3680                 };
3681                 let encoded_value = ping.encode();
3682                 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
3683                 assert_eq!(encoded_value, target_value);
3684         }
3685
3686         #[test]
3687         fn encoding_pong() {
3688                 let pong = msgs::Pong {
3689                         byteslen: 64
3690                 };
3691                 let encoded_value = pong.encode();
3692                 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
3693                 assert_eq!(encoded_value, target_value);
3694         }
3695
3696         #[test]
3697         fn encoding_nonfinal_onion_hop_data() {
3698                 let outbound_msg = msgs::OutboundOnionPayload::Forward {
3699                         short_channel_id: 0xdeadbeef1bad1dea,
3700                         amt_to_forward: 0x0badf00d01020304,
3701                         outgoing_cltv_value: 0xffffffff,
3702                 };
3703                 let encoded_value = outbound_msg.encode();
3704                 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
3705                 assert_eq!(encoded_value, target_value);
3706
3707                 let inbound_msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3708                 if let msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } = inbound_msg {
3709                         assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
3710                         assert_eq!(amt_to_forward, 0x0badf00d01020304);
3711                         assert_eq!(outgoing_cltv_value, 0xffffffff);
3712                 } else { panic!(); }
3713         }
3714
3715         #[test]
3716         fn encoding_final_onion_hop_data() {
3717                 let outbound_msg = msgs::OutboundOnionPayload::Receive {
3718                         payment_data: None,
3719                         payment_metadata: None,
3720                         keysend_preimage: None,
3721                         amt_msat: 0x0badf00d01020304,
3722                         outgoing_cltv_value: 0xffffffff,
3723                         custom_tlvs: vec![],
3724                 };
3725                 let encoded_value = outbound_msg.encode();
3726                 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
3727                 assert_eq!(encoded_value, target_value);
3728
3729                 let inbound_msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3730                 if let msgs::InboundOnionPayload::Receive { payment_data: None, amt_msat, outgoing_cltv_value, .. } = inbound_msg {
3731                         assert_eq!(amt_msat, 0x0badf00d01020304);
3732                         assert_eq!(outgoing_cltv_value, 0xffffffff);
3733                 } else { panic!(); }
3734         }
3735
3736         #[test]
3737         fn encoding_final_onion_hop_data_with_secret() {
3738                 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
3739                 let outbound_msg = msgs::OutboundOnionPayload::Receive {
3740                         payment_data: Some(FinalOnionHopData {
3741                                 payment_secret: expected_payment_secret,
3742                                 total_msat: 0x1badca1f
3743                         }),
3744                         payment_metadata: None,
3745                         keysend_preimage: None,
3746                         amt_msat: 0x0badf00d01020304,
3747                         outgoing_cltv_value: 0xffffffff,
3748                         custom_tlvs: vec![],
3749                 };
3750                 let encoded_value = outbound_msg.encode();
3751                 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
3752                 assert_eq!(encoded_value, target_value);
3753
3754                 let inbound_msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3755                 if let msgs::InboundOnionPayload::Receive {
3756                         payment_data: Some(FinalOnionHopData {
3757                                 payment_secret,
3758                                 total_msat: 0x1badca1f
3759                         }),
3760                         amt_msat, outgoing_cltv_value,
3761                         payment_metadata: None,
3762                         keysend_preimage: None,
3763                         custom_tlvs,
3764                 } = inbound_msg  {
3765                         assert_eq!(payment_secret, expected_payment_secret);
3766                         assert_eq!(amt_msat, 0x0badf00d01020304);
3767                         assert_eq!(outgoing_cltv_value, 0xffffffff);
3768                         assert_eq!(custom_tlvs, vec![]);
3769                 } else { panic!(); }
3770         }
3771
3772         #[test]
3773         fn encoding_final_onion_hop_data_with_bad_custom_tlvs() {
3774                 // If custom TLVs have type number within the range reserved for protocol, treat them as if
3775                 // they're unknown
3776                 let bad_type_range_tlvs = vec![
3777                         ((1 << 16) - 4, vec![42]),
3778                         ((1 << 16) - 2, vec![42; 32]),
3779                 ];
3780                 let mut msg = msgs::OutboundOnionPayload::Receive {
3781                         payment_data: None,
3782                         payment_metadata: None,
3783                         keysend_preimage: None,
3784                         custom_tlvs: bad_type_range_tlvs,
3785                         amt_msat: 0x0badf00d01020304,
3786                         outgoing_cltv_value: 0xffffffff,
3787                 };
3788                 let encoded_value = msg.encode();
3789                 assert!(msgs::InboundOnionPayload::read(&mut Cursor::new(&encoded_value[..])).is_err());
3790                 let good_type_range_tlvs = vec![
3791                         ((1 << 16) - 3, vec![42]),
3792                         ((1 << 16) - 1, vec![42; 32]),
3793                 ];
3794                 if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg {
3795                         *custom_tlvs = good_type_range_tlvs.clone();
3796                 }
3797                 let encoded_value = msg.encode();
3798                 let inbound_msg = Readable::read(&mut Cursor::new(&encoded_value[..])).unwrap();
3799                 match inbound_msg {
3800                         msgs::InboundOnionPayload::Receive { custom_tlvs, .. } => assert!(custom_tlvs.is_empty()),
3801                         _ => panic!(),
3802                 }
3803         }
3804
3805         #[test]
3806         fn encoding_final_onion_hop_data_with_custom_tlvs() {
3807                 let expected_custom_tlvs = vec![
3808                         (5482373483, vec![0x12, 0x34]),
3809                         (5482373487, vec![0x42u8; 8]),
3810                 ];
3811                 let msg = msgs::OutboundOnionPayload::Receive {
3812                         payment_data: None,
3813                         payment_metadata: None,
3814                         keysend_preimage: None,
3815                         custom_tlvs: expected_custom_tlvs.clone(),
3816                         amt_msat: 0x0badf00d01020304,
3817                         outgoing_cltv_value: 0xffffffff,
3818                 };
3819                 let encoded_value = msg.encode();
3820                 let target_value = hex::decode("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap();
3821                 assert_eq!(encoded_value, target_value);
3822                 let inbound_msg: msgs::InboundOnionPayload = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3823                 if let msgs::InboundOnionPayload::Receive {
3824                         payment_data: None,
3825                         payment_metadata: None,
3826                         keysend_preimage: None,
3827                         custom_tlvs,
3828                         amt_msat,
3829                         outgoing_cltv_value,
3830                         ..
3831                 } = inbound_msg {
3832                         assert_eq!(custom_tlvs, expected_custom_tlvs);
3833                         assert_eq!(amt_msat, 0x0badf00d01020304);
3834                         assert_eq!(outgoing_cltv_value, 0xffffffff);
3835                 } else { panic!(); }
3836         }
3837
3838         #[test]
3839         fn query_channel_range_end_blocknum() {
3840                 let tests: Vec<(u32, u32, u32)> = vec![
3841                         (10000, 1500, 11500),
3842                         (0, 0xffffffff, 0xffffffff),
3843                         (1, 0xffffffff, 0xffffffff),
3844                 ];
3845
3846                 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
3847                         let sut = msgs::QueryChannelRange {
3848                                 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
3849                                 first_blocknum,
3850                                 number_of_blocks,
3851                         };
3852                         assert_eq!(sut.end_blocknum(), expected);
3853                 }
3854         }
3855
3856         #[test]
3857         fn encoding_query_channel_range() {
3858                 let mut query_channel_range = msgs::QueryChannelRange {
3859                         chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
3860                         first_blocknum: 100000,
3861                         number_of_blocks: 1500,
3862                 };
3863                 let encoded_value = query_channel_range.encode();
3864                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000186a0000005dc").unwrap();
3865                 assert_eq!(encoded_value, target_value);
3866
3867                 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3868                 assert_eq!(query_channel_range.first_blocknum, 100000);
3869                 assert_eq!(query_channel_range.number_of_blocks, 1500);
3870         }
3871
3872         #[test]
3873         fn encoding_reply_channel_range() {
3874                 do_encoding_reply_channel_range(0);
3875                 do_encoding_reply_channel_range(1);
3876         }
3877
3878         fn do_encoding_reply_channel_range(encoding_type: u8) {
3879                 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000b8a06000005dc01").unwrap();
3880                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
3881                 let mut reply_channel_range = msgs::ReplyChannelRange {
3882                         chain_hash: expected_chain_hash,
3883                         first_blocknum: 756230,
3884                         number_of_blocks: 1500,
3885                         sync_complete: true,
3886                         short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
3887                 };
3888
3889                 if encoding_type == 0 {
3890                         target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
3891                         let encoded_value = reply_channel_range.encode();
3892                         assert_eq!(encoded_value, target_value);
3893
3894                         reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3895                         assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
3896                         assert_eq!(reply_channel_range.first_blocknum, 756230);
3897                         assert_eq!(reply_channel_range.number_of_blocks, 1500);
3898                         assert_eq!(reply_channel_range.sync_complete, true);
3899                         assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
3900                         assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
3901                         assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
3902                 } else {
3903                         target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
3904                         let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
3905                         assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
3906                 }
3907         }
3908
3909         #[test]
3910         fn encoding_query_short_channel_ids() {
3911                 do_encoding_query_short_channel_ids(0);
3912                 do_encoding_query_short_channel_ids(1);
3913         }
3914
3915         fn do_encoding_query_short_channel_ids(encoding_type: u8) {
3916                 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206").unwrap();
3917                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
3918                 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
3919                         chain_hash: expected_chain_hash,
3920                         short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
3921                 };
3922
3923                 if encoding_type == 0 {
3924                         target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
3925                         let encoded_value = query_short_channel_ids.encode();
3926                         assert_eq!(encoded_value, target_value);
3927
3928                         query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3929                         assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
3930                         assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
3931                         assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
3932                         assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
3933                 } else {
3934                         target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
3935                         let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
3936                         assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
3937                 }
3938         }
3939
3940         #[test]
3941         fn encoding_reply_short_channel_ids_end() {
3942                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
3943                 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
3944                         chain_hash: expected_chain_hash,
3945                         full_information: true,
3946                 };
3947                 let encoded_value = reply_short_channel_ids_end.encode();
3948                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e220601").unwrap();
3949                 assert_eq!(encoded_value, target_value);
3950
3951                 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3952                 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
3953                 assert_eq!(reply_short_channel_ids_end.full_information, true);
3954         }
3955
3956         #[test]
3957         fn encoding_gossip_timestamp_filter(){
3958                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
3959                 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
3960                         chain_hash: expected_chain_hash,
3961                         first_timestamp: 1590000000,
3962                         timestamp_range: 0xffff_ffff,
3963                 };
3964                 let encoded_value = gossip_timestamp_filter.encode();
3965                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e22065ec57980ffffffff").unwrap();
3966                 assert_eq!(encoded_value, target_value);
3967
3968                 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
3969                 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
3970                 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
3971                 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
3972         }
3973
3974         #[test]
3975         fn decode_onion_hop_data_len_as_bigsize() {
3976                 // Tests that we can decode an onion payload that is >253 bytes.
3977                 // Previously, receiving a payload of this size could've caused us to fail to decode a valid
3978                 // payload, because we were decoding the length (a BigSize, big-endian) as a VarInt
3979                 // (little-endian).
3980
3981                 // Encode a test onion payload with a big custom TLV such that it's >253 bytes, forcing the
3982                 // payload length to be encoded over multiple bytes rather than a single u8.
3983                 let big_payload = encode_big_payload().unwrap();
3984                 let mut rd = Cursor::new(&big_payload[..]);
3985                 <msgs::InboundOnionPayload as Readable>::read(&mut rd).unwrap();
3986         }
3987         // see above test, needs to be a separate method for use of the serialization macros.
3988         fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
3989                 use crate::util::ser::HighZeroBytesDroppedBigSize;
3990                 let payload = msgs::OutboundOnionPayload::Forward {
3991                         short_channel_id: 0xdeadbeef1bad1dea,
3992                         amt_to_forward: 1000,
3993                         outgoing_cltv_value: 0xffffffff,
3994                 };
3995                 let mut encoded_payload = Vec::new();
3996                 let test_bytes = vec![42u8; 1000];
3997                 if let msgs::OutboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } = payload {
3998                         _encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
3999                                 (1, test_bytes, required_vec),
4000                                 (2, HighZeroBytesDroppedBigSize(amt_to_forward), required),
4001                                 (4, HighZeroBytesDroppedBigSize(outgoing_cltv_value), required),
4002                                 (6, short_channel_id, required)
4003                         });
4004                 }
4005                 Ok(encoded_payload)
4006         }
4007
4008         #[test]
4009         #[cfg(feature = "std")]
4010         fn test_socket_address_from_str() {
4011                 assert_eq!(SocketAddress::TcpIpV4 {
4012                         addr: Ipv4Addr::new(127, 0, 0, 1).octets(),
4013                         port: 1234,
4014                 }, SocketAddress::from_str("127.0.0.1:1234").unwrap());
4015
4016                 assert_eq!(SocketAddress::TcpIpV6 {
4017                         addr: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).octets(),
4018                         port: 1234,
4019                 }, SocketAddress::from_str("[0:0:0:0:0:0:0:1]:1234").unwrap());
4020                 assert_eq!(
4021                         SocketAddress::Hostname {
4022                                 hostname: Hostname::try_from("lightning-node.mydomain.com".to_string()).unwrap(),
4023                                 port: 1234,
4024                         }, SocketAddress::from_str("lightning-node.mydomain.com:1234").unwrap());
4025                 assert_eq!(
4026                         SocketAddress::Hostname {
4027                                 hostname: Hostname::try_from("example.com".to_string()).unwrap(),
4028                                 port: 1234,
4029                         }, SocketAddress::from_str("example.com:1234").unwrap());
4030                 assert_eq!(SocketAddress::OnionV3 {
4031                         ed25519_pubkey: [37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85,
4032                         111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3],
4033                         checksum: 48326,
4034                         version: 121,
4035                         port: 1234
4036                 }, SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:1234").unwrap());
4037                 assert_eq!(Err(SocketAddressParseError::InvalidOnionV3), SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6.onion:1234"));
4038                 assert_eq!(Err(SocketAddressParseError::InvalidInput), SocketAddress::from_str("127.0.0.1@1234"));
4039                 assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::<SocketAddress>());
4040                 assert!(SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94").is_err());
4041                 assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err());
4042                 assert_eq!(Err(SocketAddressParseError::InvalidPort), SocketAddress::from_str("example.com:wrong"));
4043                 assert!("localhost".parse::<SocketAddress>().is_err());
4044                 assert!("localhost:invalid-port".parse::<SocketAddress>().is_err());
4045                 assert!( "invalid-onion-v3-hostname.onion:8080".parse::<SocketAddress>().is_err());
4046                 assert!("b32.example.onion:invalid-port".parse::<SocketAddress>().is_err());
4047                 assert!("invalid-address".parse::<SocketAddress>().is_err());
4048                 assert!(SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234").is_err());
4049         }
4050 }