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