lightning/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
27use bitcoin::constants::ChainHash;
28use bitcoin::hash_types::Txid;
29use bitcoin::script::ScriptBuf;
30use bitcoin::secp256k1::ecdsa::Signature;
31use bitcoin::secp256k1::PublicKey;
32use bitcoin::{secp256k1, Transaction, Witness};
33
34use crate::blinded_path::message::BlindedMessagePath;
35use crate::blinded_path::payment::{
36	BlindedPaymentTlvs, ForwardTlvs, ReceiveTlvs, UnauthenticatedReceiveTlvs,
37};
38use crate::blinded_path::payment::{BlindedTrampolineTlvs, TrampolineForwardTlvs};
39use crate::ln::channelmanager::Verification;
40use crate::ln::onion_utils;
41use crate::ln::types::ChannelId;
42use crate::offers::invoice_request::InvoiceRequest;
43use crate::onion_message;
44use crate::sign::{NodeSigner, Recipient};
45use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
46use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
47
48#[allow(unused_imports)]
49use crate::prelude::*;
50
51use crate::io::{self, Cursor, Read};
52use crate::io_extras::read_to_end;
53use core::fmt;
54use core::fmt::Debug;
55use core::fmt::Display;
56use core::ops::Deref;
57#[cfg(feature = "std")]
58use core::str::FromStr;
59#[cfg(feature = "std")]
60use std::net::SocketAddr;
61
62use crate::crypto::streams::ChaChaPolyReadAdapter;
63use crate::util::base32;
64use crate::util::logger;
65use crate::util::ser::{
66	BigSize, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, LengthLimitedRead,
67	LengthReadable, LengthReadableArgs, Readable, ReadableArgs, WithoutLength, Writeable, Writer,
68};
69
70use crate::routing::gossip::{NodeAlias, NodeId};
71
72/// 21 million * 10^8 * 1000
73pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
74
75#[cfg(taproot)]
76/// A partial signature that also contains the Musig2 nonce its signer used
77#[derive(Clone, Debug, Hash, PartialEq, Eq)]
78pub struct PartialSignatureWithNonce(
79	pub musig2::types::PartialSignature,
80	pub musig2::types::PublicNonce,
81);
82
83/// An error in decoding a message or struct.
84#[derive(Clone, Debug, Hash, PartialEq, Eq)]
85pub enum DecodeError {
86	/// A version byte specified something we don't know how to handle.
87	///
88	/// Includes unknown realm byte in an onion hop data packet.
89	UnknownVersion,
90	/// Unknown feature mandating we fail to parse message (e.g., TLV with an even, unknown type)
91	UnknownRequiredFeature,
92	/// Value was invalid.
93	///
94	/// For example, a byte which was supposed to be a bool was something other than a 0
95	/// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was
96	/// syntactically incorrect, etc.
97	InvalidValue,
98	/// The buffer to be read was too short.
99	ShortRead,
100	/// A length descriptor in the packet didn't describe the later data correctly.
101	BadLengthDescriptor,
102	/// Error from [`crate::io`].
103	Io(io::ErrorKind),
104	/// The message included zlib-compressed values, which we don't support.
105	UnsupportedCompression,
106	/// Value is validly encoded but is dangerous to use.
107	///
108	/// This is used for things like [`ChannelManager`] deserialization where we want to ensure
109	/// that we don't use a [`ChannelManager`] which is in out of sync with the [`ChannelMonitor`].
110	/// This indicates that there is a critical implementation flaw in the storage implementation
111	/// and it's unsafe to continue.
112	///
113	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
114	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
115	DangerousValue,
116}
117
118/// An [`init`] message to be sent to or received from a peer.
119///
120/// [`init`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-init-message
121#[derive(Clone, Debug, Hash, PartialEq, Eq)]
122pub struct Init {
123	/// The relevant features which the sender supports.
124	pub features: InitFeatures,
125	/// Indicates chains the sender is interested in.
126	///
127	/// If there are no common chains, the connection will be closed.
128	pub networks: Option<Vec<ChainHash>>,
129	/// The receipient's network address.
130	///
131	/// This adds the option to report a remote IP address back to a connecting peer using the init
132	/// message. A node can decide to use that information to discover a potential update to its
133	/// public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing
134	/// the new address.
135	pub remote_network_address: Option<SocketAddress>,
136}
137
138/// An [`error`] message to be sent to or received from a peer.
139///
140/// [`error`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages
141#[derive(Clone, Debug, Hash, PartialEq, Eq)]
142pub struct ErrorMessage {
143	/// The channel ID involved in the error.
144	///
145	/// All-0s indicates a general error unrelated to a specific channel, after which all channels
146	/// with the sending peer should be closed.
147	pub channel_id: ChannelId,
148	/// A possibly human-readable error description.
149	///
150	/// The string should be sanitized before it is used (e.g., emitted to logs or printed to
151	/// `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in
152	/// the terminal emulator or the logging subsystem.
153	pub data: String,
154}
155
156/// A [`warning`] message to be sent to or received from a peer.
157///
158/// [`warning`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages
159#[derive(Clone, Debug, Hash, PartialEq, Eq)]
160pub struct WarningMessage {
161	/// The channel ID involved in the warning.
162	///
163	/// All-0s indicates a warning unrelated to a specific channel.
164	pub channel_id: ChannelId,
165	/// A possibly human-readable warning description.
166	///
167	/// The string should be sanitized before it is used (e.g. emitted to logs or printed to
168	/// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in
169	/// the terminal emulator or the logging subsystem.
170	pub data: String,
171}
172
173/// A [`ping`] message to be sent to or received from a peer.
174///
175/// [`ping`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages
176#[derive(Clone, Debug, Hash, PartialEq, Eq)]
177pub struct Ping {
178	/// The desired response length.
179	pub ponglen: u16,
180	/// The ping packet size.
181	///
182	/// This field is not sent on the wire. byteslen zeros are sent.
183	pub byteslen: u16,
184}
185
186/// A [`pong`] message to be sent to or received from a peer.
187///
188/// [`pong`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages
189#[derive(Clone, Debug, Hash, PartialEq, Eq)]
190pub struct Pong {
191	/// The pong packet size.
192	///
193	/// This field is not sent on the wire. byteslen zeros are sent.
194	pub byteslen: u16,
195}
196
197/// Contains fields that are both common to [`open_channel`] and [`open_channel2`] messages.
198///
199/// [`open_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message
200/// [`open_channel2`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel2-message
201#[derive(Clone, Debug, Hash, PartialEq, Eq)]
202pub struct CommonOpenChannelFields {
203	/// The genesis hash of the blockchain where the channel is to be opened
204	pub chain_hash: ChainHash,
205	/// A temporary channel ID
206	/// For V2 channels: derived using a zeroed out value for the channel acceptor's revocation basepoint
207	/// For V1 channels: a temporary channel ID, until the funding outpoint is announced
208	pub temporary_channel_id: ChannelId,
209	/// For V1 channels: The channel value
210	/// For V2 channels: Part of the channel value contributed by the channel initiator
211	pub funding_satoshis: u64,
212	/// The threshold below which outputs on transactions broadcast by the channel initiator will be
213	/// omitted
214	pub dust_limit_satoshis: u64,
215	/// The maximum inbound HTLC value in flight towards channel initiator, in milli-satoshi
216	pub max_htlc_value_in_flight_msat: u64,
217	/// The minimum HTLC size incoming to channel initiator, in milli-satoshi
218	pub htlc_minimum_msat: u64,
219	/// The feerate for the commitment transaction set by the channel initiator until updated by
220	/// [`UpdateFee`]
221	pub commitment_feerate_sat_per_1000_weight: u32,
222	/// The number of blocks which the counterparty will have to wait to claim on-chain funds if they
223	/// broadcast a commitment transaction
224	pub to_self_delay: u16,
225	/// The maximum number of inbound HTLCs towards channel initiator
226	pub max_accepted_htlcs: u16,
227	/// The channel initiator's key controlling the funding transaction
228	pub funding_pubkey: PublicKey,
229	/// Used to derive a revocation key for transactions broadcast by counterparty
230	pub revocation_basepoint: PublicKey,
231	/// A payment key to channel initiator for transactions broadcast by counterparty
232	pub payment_basepoint: PublicKey,
233	/// Used to derive a payment key to channel initiator for transactions broadcast by channel
234	/// initiator
235	pub delayed_payment_basepoint: PublicKey,
236	/// Used to derive an HTLC payment key to channel initiator
237	pub htlc_basepoint: PublicKey,
238	/// The first to-be-broadcast-by-channel-initiator transaction's per commitment point
239	pub first_per_commitment_point: PublicKey,
240	/// The channel flags to be used
241	pub channel_flags: u8,
242	/// Optionally, a request to pre-set the to-channel-initiator output's scriptPubkey for when we
243	/// collaboratively close
244	pub shutdown_scriptpubkey: Option<ScriptBuf>,
245	/// The channel type that this channel will represent. As defined in the latest
246	/// specification, this field is required. However, it is an `Option` for legacy reasons.
247	pub channel_type: Option<ChannelTypeFeatures>,
248}
249
250impl CommonOpenChannelFields {
251	/// The [`ChannelParameters`] for this channel.
252	pub fn channel_parameters(&self) -> ChannelParameters {
253		ChannelParameters {
254			dust_limit_satoshis: self.dust_limit_satoshis,
255			max_htlc_value_in_flight_msat: self.max_htlc_value_in_flight_msat,
256			htlc_minimum_msat: self.htlc_minimum_msat,
257			commitment_feerate_sat_per_1000_weight: self.commitment_feerate_sat_per_1000_weight,
258			to_self_delay: self.to_self_delay,
259			max_accepted_htlcs: self.max_accepted_htlcs,
260		}
261	}
262}
263
264/// A subset of [`CommonOpenChannelFields`], containing various parameters which are set by the
265/// channel initiator and which are not part of the channel funding transaction.
266#[derive(Clone, Debug, Hash, PartialEq, Eq)]
267pub struct ChannelParameters {
268	/// The threshold below which outputs on transactions broadcast by the channel initiator will be
269	/// omitted.
270	pub dust_limit_satoshis: u64,
271	/// The maximum inbound HTLC value in flight towards channel initiator, in milli-satoshi
272	pub max_htlc_value_in_flight_msat: u64,
273	/// The minimum HTLC size for HTLCs towards the channel initiator, in milli-satoshi
274	pub htlc_minimum_msat: u64,
275	/// The feerate for the commitment transaction set by the channel initiator until updated by
276	/// [`UpdateFee`]
277	pub commitment_feerate_sat_per_1000_weight: u32,
278	/// The number of blocks which the non-channel-initator will have to wait to claim on-chain
279	/// funds if they broadcast a commitment transaction.
280	pub to_self_delay: u16,
281	/// The maximum number of pending HTLCs towards the channel initiator.
282	pub max_accepted_htlcs: u16,
283}
284
285/// An [`open_channel`] message to be sent to or received from a peer.
286///
287/// Used in V1 channel establishment
288///
289/// [`open_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message
290#[derive(Clone, Debug, Hash, PartialEq, Eq)]
291pub struct OpenChannel {
292	/// Common fields of `open_channel(2)`-like messages
293	pub common_fields: CommonOpenChannelFields,
294	/// The amount to push to the counterparty as part of the open, in milli-satoshi
295	pub push_msat: u64,
296	/// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
297	pub channel_reserve_satoshis: u64,
298}
299
300/// An [`open_channel2`] message to be sent by or received from the channel initiator.
301///
302/// Used in V2 channel establishment
303///
304/// [`open_channel2`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel2-message
305#[derive(Clone, Debug, Hash, PartialEq, Eq)]
306pub struct OpenChannelV2 {
307	/// Common fields of `open_channel(2)`-like messages
308	pub common_fields: CommonOpenChannelFields,
309	/// The feerate for the funding transaction set by the channel initiator
310	pub funding_feerate_sat_per_1000_weight: u32,
311	/// The locktime for the funding transaction
312	pub locktime: u32,
313	/// The second to-be-broadcast-by-channel-initiator transaction's per commitment point
314	pub second_per_commitment_point: PublicKey,
315	/// Optionally, a requirement that only confirmed inputs can be added
316	pub require_confirmed_inputs: Option<()>,
317}
318
319/// Contains fields that are both common to [`accept_channel`] and [`accept_channel2`] messages.
320///
321/// [`accept_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel-message
322/// [`accept_channel2`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel2-message
323#[derive(Clone, Debug, Hash, PartialEq, Eq)]
324pub struct CommonAcceptChannelFields {
325	/// The same `temporary_channel_id` received from the initiator's `open_channel2` or `open_channel` message.
326	pub temporary_channel_id: ChannelId,
327	/// The threshold below which outputs on transactions broadcast by the channel acceptor will be
328	/// omitted
329	pub dust_limit_satoshis: u64,
330	/// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
331	pub max_htlc_value_in_flight_msat: u64,
332	/// The minimum HTLC size incoming to channel acceptor, in milli-satoshi
333	pub htlc_minimum_msat: u64,
334	/// Minimum depth of the funding transaction before the channel is considered open
335	pub minimum_depth: u32,
336	/// The number of blocks which the counterparty will have to wait to claim on-chain funds if they
337	/// broadcast a commitment transaction
338	pub to_self_delay: u16,
339	/// The maximum number of inbound HTLCs towards channel acceptor
340	pub max_accepted_htlcs: u16,
341	/// The channel acceptor's key controlling the funding transaction
342	pub funding_pubkey: PublicKey,
343	/// Used to derive a revocation key for transactions broadcast by counterparty
344	pub revocation_basepoint: PublicKey,
345	/// A payment key to channel acceptor for transactions broadcast by counterparty
346	pub payment_basepoint: PublicKey,
347	/// Used to derive a payment key to channel acceptor for transactions broadcast by channel
348	/// acceptor
349	pub delayed_payment_basepoint: PublicKey,
350	/// Used to derive an HTLC payment key to channel acceptor for transactions broadcast by counterparty
351	pub htlc_basepoint: PublicKey,
352	/// The first to-be-broadcast-by-channel-acceptor transaction's per commitment point
353	pub first_per_commitment_point: PublicKey,
354	/// Optionally, a request to pre-set the to-channel-acceptor output's scriptPubkey for when we
355	/// collaboratively close
356	pub shutdown_scriptpubkey: Option<ScriptBuf>,
357	/// The channel type that this channel will represent. As defined in the latest
358	/// specification, this field is required. However, it is an `Option` for legacy reasons.
359	///
360	/// This is required to match the equivalent field in [`OpenChannel`] or [`OpenChannelV2`]'s
361	/// [`CommonOpenChannelFields::channel_type`].
362	pub channel_type: Option<ChannelTypeFeatures>,
363}
364
365/// An [`accept_channel`] message to be sent to or received from a peer.
366///
367/// Used in V1 channel establishment
368///
369/// [`accept_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel-message
370#[derive(Clone, Debug, Hash, PartialEq, Eq)]
371pub struct AcceptChannel {
372	/// Common fields of `accept_channel(2)`-like messages
373	pub common_fields: CommonAcceptChannelFields,
374	/// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
375	pub channel_reserve_satoshis: u64,
376	#[cfg(taproot)]
377	/// Next nonce the channel initiator should use to create a funding output signature against
378	pub next_local_nonce: Option<musig2::types::PublicNonce>,
379}
380
381/// An [`accept_channel2`] message to be sent by or received from the channel accepter.
382///
383/// Used in V2 channel establishment
384///
385/// [`accept_channel2`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel2-message
386#[derive(Clone, Debug, Hash, PartialEq, Eq)]
387pub struct AcceptChannelV2 {
388	/// Common fields of `accept_channel(2)`-like messages
389	pub common_fields: CommonAcceptChannelFields,
390	/// Part of the channel value contributed by the channel acceptor
391	pub funding_satoshis: u64,
392	/// The second to-be-broadcast-by-channel-acceptor transaction's per commitment point
393	pub second_per_commitment_point: PublicKey,
394	/// Optionally, a requirement that only confirmed inputs can be added
395	pub require_confirmed_inputs: Option<()>,
396}
397
398/// A [`funding_created`] message to be sent to or received from a peer.
399///
400/// Used in V1 channel establishment
401///
402/// [`funding_created`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_created-message
403#[derive(Clone, Debug, Hash, PartialEq, Eq)]
404pub struct FundingCreated {
405	/// A temporary channel ID, until the funding is established
406	pub temporary_channel_id: ChannelId,
407	/// The funding transaction ID
408	pub funding_txid: Txid,
409	/// The specific output index funding this channel
410	pub funding_output_index: u16,
411	/// The signature of the channel initiator (funder) on the initial commitment transaction
412	pub signature: Signature,
413	#[cfg(taproot)]
414	/// The partial signature of the channel initiator (funder)
415	pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
416	#[cfg(taproot)]
417	/// Next nonce the channel acceptor should use to finalize the funding output signature
418	pub next_local_nonce: Option<musig2::types::PublicNonce>,
419}
420
421/// A [`funding_signed`] message to be sent to or received from a peer.
422///
423/// Used in V1 channel establishment
424///
425/// [`funding_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_signed-message
426#[derive(Clone, Debug, Hash, PartialEq, Eq)]
427pub struct FundingSigned {
428	/// The channel ID
429	pub channel_id: ChannelId,
430	/// The signature of the channel acceptor (fundee) on the initial commitment transaction
431	pub signature: Signature,
432	#[cfg(taproot)]
433	/// The partial signature of the channel acceptor (fundee)
434	pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
435}
436
437/// A [`channel_ready`] message to be sent to or received from a peer.
438///
439/// [`channel_ready`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message
440#[derive(Clone, Debug, Hash, PartialEq, Eq)]
441pub struct ChannelReady {
442	/// The channel ID
443	pub channel_id: ChannelId,
444	/// The per-commitment point of the second commitment transaction
445	pub next_per_commitment_point: PublicKey,
446	/// If set, provides a `short_channel_id` alias for this channel.
447	///
448	/// The sender will accept payments to be forwarded over this SCID and forward them to this
449	/// messages' recipient.
450	pub short_channel_id_alias: Option<u64>,
451}
452
453/// A randomly chosen number that is used to identify inputs within an interactive transaction
454/// construction.
455pub type SerialId = u64;
456
457/// An `stfu` (quiescence) message to be sent by or received from the stfu initiator.
458///
459// TODO(splicing): Add spec link for `stfu`; still in draft, using from https://github.com/lightning/bolts/pull/1160
460#[derive(Clone, Debug, PartialEq, Eq)]
461pub struct Stfu {
462	/// The channel ID where quiescence is intended
463	pub channel_id: ChannelId,
464	/// Initiator flag, true if initiating, false if replying to an stfu.
465	pub initiator: bool,
466}
467
468/// A `splice_init` message to be sent by or received from the stfu initiator (splice initiator).
469///
470// TODO(splicing): Add spec link for `splice_init`; still in draft, using from https://github.com/lightning/bolts/pull/1160
471#[derive(Clone, Debug, PartialEq, Eq)]
472pub struct SpliceInit {
473	/// The channel ID where splicing is intended
474	pub channel_id: ChannelId,
475	/// The amount the splice initiator is intending to add to its channel balance (splice-in)
476	/// or remove from its channel balance (splice-out).
477	pub funding_contribution_satoshis: i64,
478	/// The feerate for the new funding transaction, set by the splice initiator
479	pub funding_feerate_per_kw: u32,
480	/// The locktime for the new funding transaction
481	pub locktime: u32,
482	/// The key of the sender (splice initiator) controlling the new funding transaction
483	pub funding_pubkey: PublicKey,
484	/// If set, only confirmed inputs added (by the splice acceptor) will be accepted
485	pub require_confirmed_inputs: Option<()>,
486}
487
488/// A `splice_ack` message to be received by or sent to the splice initiator.
489///
490// TODO(splicing): Add spec link for `splice_ack`; still in draft, using from https://github.com/lightning/bolts/pull/1160
491#[derive(Clone, Debug, PartialEq, Eq)]
492pub struct SpliceAck {
493	/// The channel ID where splicing is intended
494	pub channel_id: ChannelId,
495	/// The amount the splice acceptor is intending to add to its channel balance (splice-in)
496	/// or remove from its channel balance (splice-out).
497	pub funding_contribution_satoshis: i64,
498	/// The key of the sender (splice acceptor) controlling the new funding transaction
499	pub funding_pubkey: PublicKey,
500	/// If set, only confirmed inputs added (by the splice initiator) will be accepted
501	pub require_confirmed_inputs: Option<()>,
502}
503
504/// A `splice_locked` message to be sent to or received from a peer.
505///
506// TODO(splicing): Add spec link for `splice_locked`; still in draft, using from https://github.com/lightning/bolts/pull/1160
507#[derive(Clone, Debug, PartialEq, Eq)]
508pub struct SpliceLocked {
509	/// The channel ID
510	pub channel_id: ChannelId,
511	/// The ID of the new funding transaction that has been locked
512	pub splice_txid: Txid,
513}
514
515/// A [`tx_add_input`] message for adding an input during interactive transaction construction
516///
517/// [`tx_add_input`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_add_input-message
518#[derive(Clone, Debug, Hash, PartialEq, Eq)]
519pub struct TxAddInput {
520	/// The channel ID
521	pub channel_id: ChannelId,
522	/// A randomly chosen unique identifier for this input, which is even for initiators and odd for
523	/// non-initiators.
524	pub serial_id: SerialId,
525	/// Serialized transaction that contains the output this input spends to verify that it is
526	/// non-malleable. Omitted for shared input.
527	pub prevtx: Option<Transaction>,
528	/// The index of the output being spent
529	pub prevtx_out: u32,
530	/// The sequence number of this input
531	pub sequence: u32,
532	/// The ID of the previous funding transaction, when it is being added as an input during splicing
533	pub shared_input_txid: Option<Txid>,
534}
535
536/// A [`tx_add_output`] message for adding an output during interactive transaction construction.
537///
538/// [`tx_add_output`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_add_output-message
539#[derive(Clone, Debug, Hash, PartialEq, Eq)]
540pub struct TxAddOutput {
541	/// The channel ID
542	pub channel_id: ChannelId,
543	/// A randomly chosen unique identifier for this output, which is even for initiators and odd for
544	/// non-initiators.
545	pub serial_id: SerialId,
546	/// The satoshi value of the output
547	pub sats: u64,
548	/// The scriptPubKey for the output
549	pub script: ScriptBuf,
550}
551
552/// A [`tx_remove_input`] message for removing an input during interactive transaction construction.
553///
554/// [`tx_remove_input`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_remove_input-and-tx_remove_output-messages
555#[derive(Clone, Debug, Hash, PartialEq, Eq)]
556pub struct TxRemoveInput {
557	/// The channel ID
558	pub channel_id: ChannelId,
559	/// The serial ID of the input to be removed
560	pub serial_id: SerialId,
561}
562
563/// A [`tx_remove_output`] message for removing an output during interactive transaction construction.
564///
565/// [`tx_remove_output`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_remove_input-and-tx_remove_output-messages
566#[derive(Clone, Debug, Hash, PartialEq, Eq)]
567pub struct TxRemoveOutput {
568	/// The channel ID
569	pub channel_id: ChannelId,
570	/// The serial ID of the output to be removed
571	pub serial_id: SerialId,
572}
573
574/// [`A tx_complete`] message signalling the conclusion of a peer's transaction contributions during
575/// interactive transaction construction.
576///
577/// [`tx_complete`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_complete-message
578#[derive(Clone, Debug, Hash, PartialEq, Eq)]
579pub struct TxComplete {
580	/// The channel ID
581	pub channel_id: ChannelId,
582}
583
584/// A [`tx_signatures`] message containing the sender's signatures for a transaction constructed with
585/// interactive transaction construction.
586///
587/// [`tx_signatures`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_signatures-message
588#[derive(Clone, Debug, Hash, PartialEq, Eq)]
589pub struct TxSignatures {
590	/// The channel ID
591	pub channel_id: ChannelId,
592	/// The TXID
593	pub tx_hash: Txid,
594	/// The list of witnesses
595	pub witnesses: Vec<Witness>,
596	/// Optional signature for the shared input -- the previous funding outpoint -- signed by both peers
597	pub shared_input_signature: Option<Signature>,
598}
599
600/// A [`tx_init_rbf`] message which initiates a replacement of the transaction after it's been
601/// completed.
602///
603/// [`tx_init_rbf`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_init_rbf-message
604#[derive(Clone, Debug, Hash, PartialEq, Eq)]
605pub struct TxInitRbf {
606	/// The channel ID
607	pub channel_id: ChannelId,
608	/// The locktime of the transaction
609	pub locktime: u32,
610	/// The feerate of the transaction
611	pub feerate_sat_per_1000_weight: u32,
612	/// The number of satoshis the sender will contribute to or, if negative, remove from
613	/// (e.g. splice-out) the funding output of the transaction
614	pub funding_output_contribution: Option<i64>,
615}
616
617/// A [`tx_ack_rbf`] message which acknowledges replacement of the transaction after it's been
618/// completed.
619///
620/// [`tx_ack_rbf`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_ack_rbf-message
621#[derive(Clone, Debug, Hash, PartialEq, Eq)]
622pub struct TxAckRbf {
623	/// The channel ID
624	pub channel_id: ChannelId,
625	/// The number of satoshis the sender will contribute to or, if negative, remove from
626	/// (e.g. splice-out) the funding output of the transaction
627	pub funding_output_contribution: Option<i64>,
628}
629
630/// A [`tx_abort`] message which signals the cancellation of an in-progress transaction negotiation.
631///
632/// [`tx_abort`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-tx_abort-message
633#[derive(Clone, Debug, Hash, PartialEq, Eq)]
634pub struct TxAbort {
635	/// The channel ID
636	pub channel_id: ChannelId,
637	/// Message data
638	pub data: Vec<u8>,
639}
640
641/// A [`shutdown`] message to be sent to or received from a peer.
642///
643/// [`shutdown`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-initiation-shutdown
644#[derive(Clone, Debug, Hash, PartialEq, Eq)]
645pub struct Shutdown {
646	/// The channel ID
647	pub channel_id: ChannelId,
648	/// The destination of this peer's funds on closing.
649	///
650	/// Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR.
651	pub scriptpubkey: ScriptBuf,
652}
653
654/// The minimum and maximum fees which the sender is willing to place on the closing transaction.
655///
656/// This is provided in [`ClosingSigned`] by both sides to indicate the fee range they are willing
657/// to use.
658#[derive(Clone, Debug, Hash, PartialEq, Eq)]
659pub struct ClosingSignedFeeRange {
660	/// The minimum absolute fee, in satoshis, which the sender is willing to place on the closing
661	/// transaction.
662	pub min_fee_satoshis: u64,
663	/// The maximum absolute fee, in satoshis, which the sender is willing to place on the closing
664	/// transaction.
665	pub max_fee_satoshis: u64,
666}
667
668/// A [`closing_signed`] message to be sent to or received from a peer.
669///
670/// [`closing_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_signed
671#[derive(Clone, Debug, Hash, PartialEq, Eq)]
672pub struct ClosingSigned {
673	/// The channel ID
674	pub channel_id: ChannelId,
675	/// The proposed total fee for the closing transaction
676	pub fee_satoshis: u64,
677	/// A signature on the closing transaction
678	pub signature: Signature,
679	/// The minimum and maximum fees which the sender is willing to accept, provided only by new
680	/// nodes.
681	pub fee_range: Option<ClosingSignedFeeRange>,
682}
683
684/// A [`closing_complete`] message to be sent to or received from a peer.
685///
686/// [`closing_complete`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_complete-and-closing_sig
687#[derive(Clone, Debug, Hash, PartialEq, Eq)]
688pub struct ClosingComplete {
689	/// The channel ID.
690	pub channel_id: ChannelId,
691	/// The destination of the closer's funds on closing.
692	pub closer_scriptpubkey: ScriptBuf,
693	/// The destination of the closee's funds on closing.
694	pub closee_scriptpubkey: ScriptBuf,
695	/// The proposed total fee for the closing transaction.
696	pub fee_satoshis: u64,
697	/// The locktime of the closing transaction.
698	pub locktime: u32,
699	/// A signature on the closing transaction omitting the `closee` output.
700	pub closer_output_only: Option<Signature>,
701	/// A signature on the closing transaction omitting the `closer` output.
702	pub closee_output_only: Option<Signature>,
703	/// A signature on the closing transaction covering both `closer` and `closee` outputs.
704	pub closer_and_closee_outputs: Option<Signature>,
705}
706
707/// A [`closing_sig`] message to be sent to or received from a peer.
708///
709/// [`closing_sig`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_complete-and-closing_sig
710#[derive(Clone, Debug, Hash, PartialEq, Eq)]
711pub struct ClosingSig {
712	/// The channel ID.
713	pub channel_id: ChannelId,
714	/// The destination of the closer's funds on closing.
715	pub closer_scriptpubkey: ScriptBuf,
716	/// The destination of the closee's funds on closing.
717	pub closee_scriptpubkey: ScriptBuf,
718	/// The proposed total fee for the closing transaction.
719	pub fee_satoshis: u64,
720	/// The locktime of the closing transaction.
721	pub locktime: u32,
722	/// A signature on the closing transaction omitting the `closee` output.
723	pub closer_output_only: Option<Signature>,
724	/// A signature on the closing transaction omitting the `closer` output.
725	pub closee_output_only: Option<Signature>,
726	/// A signature on the closing transaction covering both `closer` and `closee` outputs.
727	pub closer_and_closee_outputs: Option<Signature>,
728}
729
730/// A [`start_batch`] message to be sent to group together multiple channel messages as a single
731/// logical message.
732///
733/// [`start_batch`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#batching-channel-messages
734#[derive(Clone, Debug, Hash, PartialEq, Eq)]
735pub struct StartBatch {
736	/// The channel ID of all messages in the batch.
737	pub channel_id: ChannelId,
738	/// The number of messages to follow.
739	pub batch_size: u16,
740	/// The type of all messages expected in the batch.
741	pub message_type: Option<u16>,
742}
743
744/// An [`update_add_htlc`] message to be sent to or received from a peer.
745///
746/// [`update_add_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc
747#[derive(Clone, Debug, Hash, PartialEq, Eq)]
748pub struct UpdateAddHTLC {
749	/// The channel ID
750	pub channel_id: ChannelId,
751	/// The HTLC ID
752	pub htlc_id: u64,
753	/// The HTLC value in milli-satoshi
754	pub amount_msat: u64,
755	/// The payment hash, the pre-image of which controls HTLC redemption
756	pub payment_hash: PaymentHash,
757	/// The expiry height of the HTLC
758	pub cltv_expiry: u32,
759	/// The extra fee skimmed by the sender of this message. See
760	/// [`ChannelConfig::accept_underpaying_htlcs`].
761	///
762	/// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
763	pub skimmed_fee_msat: Option<u64>,
764	/// The onion routing packet with encrypted data for the next hop.
765	pub onion_routing_packet: OnionPacket,
766	/// Provided if we are relaying or receiving a payment within a blinded path, to decrypt the onion
767	/// routing packet and the recipient-provided encrypted payload within.
768	pub blinding_point: Option<PublicKey>,
769	/// Set to `Some` if the sender wants the receiver of this message to hold onto this HTLC until
770	/// receipt of a [`ReleaseHeldHtlc`] onion message from the payment recipient.
771	///
772	/// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc
773	pub hold_htlc: Option<()>,
774}
775
776/// An [`onion message`] to be sent to or received from a peer.
777///
778/// [`onion message`]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md#onion-messages
779#[derive(Clone, Debug, Hash, PartialEq, Eq)]
780pub struct OnionMessage {
781	/// Used in decrypting the onion packet's payload.
782	pub blinding_point: PublicKey,
783	/// The full onion packet including hop data, pubkey, and hmac
784	pub onion_routing_packet: onion_message::packet::Packet,
785}
786
787/// An [`update_fulfill_htlc`] message to be sent to or received from a peer.
788///
789/// [`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
790#[derive(Clone, Debug, Hash, PartialEq, Eq)]
791pub struct UpdateFulfillHTLC {
792	/// The channel ID
793	pub channel_id: ChannelId,
794	/// The HTLC ID
795	pub htlc_id: u64,
796	/// The pre-image of the payment hash, allowing HTLC redemption
797	pub payment_preimage: PaymentPreimage,
798	/// Optional field for attribution data that allows the sender to receive per hop HTLC hold times.
799	pub attribution_data: Option<AttributionData>,
800}
801
802/// A [`peer_storage`] message that can be sent to or received from a peer.
803///
804/// This message is used to distribute backup data to peers.
805/// If data is lost or corrupted, users can retrieve it through [`PeerStorageRetrieval`]
806/// to recover critical information, such as channel states, for fund recovery.
807///
808/// [`peer_storage`] is used to send our own encrypted backup data to a peer.
809///
810/// [`peer_storage`]: https://github.com/lightning/bolts/pull/1110
811#[derive(Clone, Debug, Hash, PartialEq, Eq)]
812pub struct PeerStorage {
813	/// Our encrypted backup data included in the msg.
814	pub data: Vec<u8>,
815}
816
817/// A [`peer_storage_retrieval`] message that can be sent to or received from a peer.
818///
819/// This message is sent to peers for whom we store backup data.
820/// If we receive this message, it indicates that the peer had stored our backup data.
821/// This data can be used for fund recovery in case of data loss.
822///
823/// [`peer_storage_retrieval`] is used to send the most recent backup of the peer.
824///
825/// [`peer_storage_retrieval`]: https://github.com/lightning/bolts/pull/1110
826#[derive(Clone, Debug, Hash, PartialEq, Eq)]
827pub struct PeerStorageRetrieval {
828	/// Most recent peer's data included in the msg.
829	pub data: Vec<u8>,
830}
831
832/// An [`update_fail_htlc`] message to be sent to or received from a peer.
833///
834/// [`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
835#[derive(Clone, Debug, Hash, PartialEq, Eq)]
836pub struct UpdateFailHTLC {
837	/// The channel ID
838	pub channel_id: ChannelId,
839	/// The HTLC ID
840	pub htlc_id: u64,
841	pub(crate) reason: Vec<u8>,
842
843	/// Optional field for the attribution data that allows the sender to pinpoint the failing node under all conditions
844	pub attribution_data: Option<AttributionData>,
845}
846/// An [`update_fail_malformed_htlc`] message to be sent to or received from a peer.
847///
848/// [`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
849#[derive(Clone, Debug, Hash, PartialEq, Eq)]
850pub struct UpdateFailMalformedHTLC {
851	/// The channel ID
852	pub channel_id: ChannelId,
853	/// The HTLC ID
854	pub htlc_id: u64,
855	pub(crate) sha256_of_onion: [u8; 32],
856	/// The failure code
857	pub failure_code: u16,
858}
859
860/// A [`commitment_signed`] message to be sent to or received from a peer.
861///
862/// [`commitment_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#committing-updates-so-far-commitment_signed
863#[derive(Clone, Debug, Hash, PartialEq, Eq)]
864pub struct CommitmentSigned {
865	/// The channel ID
866	pub channel_id: ChannelId,
867	/// A signature on the commitment transaction
868	pub signature: Signature,
869	/// Signatures on the HTLC transactions
870	pub htlc_signatures: Vec<Signature>,
871	/// The funding transaction, to discriminate among multiple pending funding transactions (e.g. in case of splicing)
872	pub funding_txid: Option<Txid>,
873	#[cfg(taproot)]
874	/// The partial Taproot signature on the commitment transaction
875	pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
876}
877
878/// A [`revoke_and_ack`] message to be sent to or received from a peer.
879///
880/// [`revoke_and_ack`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#completing-the-transition-to-the-updated-state-revoke_and_ack
881#[derive(Clone, Debug, Hash, PartialEq, Eq)]
882pub struct RevokeAndACK {
883	/// The channel ID
884	pub channel_id: ChannelId,
885	/// The secret corresponding to the per-commitment point
886	pub per_commitment_secret: [u8; 32],
887	/// The next sender-broadcast commitment transaction's per-commitment point
888	pub next_per_commitment_point: PublicKey,
889	#[cfg(taproot)]
890	/// Musig nonce the recipient should use in their next commitment signature message
891	pub next_local_nonce: Option<musig2::types::PublicNonce>,
892	/// A list of `(htlc_id, blinded_path)`. The receiver of this message will use the blinded paths
893	/// as reply paths to [`HeldHtlcAvailable`] onion messages that they send to the often-offline
894	/// receiver of this HTLC. The `htlc_id` is used by the receiver of this message to identify which
895	/// held HTLC a given blinded path corresponds to.
896	///
897	/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
898	pub release_htlc_message_paths: Vec<(u64, BlindedMessagePath)>,
899}
900
901/// An [`update_fee`] message to be sent to or received from a peer
902///
903/// [`update_fee`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#updating-fees-update_fee
904#[derive(Clone, Debug, Hash, PartialEq, Eq)]
905pub struct UpdateFee {
906	/// The channel ID
907	pub channel_id: ChannelId,
908	/// Fee rate per 1000-weight of the transaction
909	pub feerate_per_kw: u32,
910}
911
912/// A [`channel_reestablish`] message to be sent to or received from a peer.
913///
914/// [`channel_reestablish`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#message-retransmission
915#[derive(Clone, Debug, Hash, PartialEq, Eq)]
916pub struct ChannelReestablish {
917	/// The channel ID
918	pub channel_id: ChannelId,
919	/// The next commitment number for the sender
920	pub next_local_commitment_number: u64,
921	/// The next commitment number for the recipient
922	pub next_remote_commitment_number: u64,
923	/// Proof that the sender knows the per-commitment secret of a specific commitment transaction
924	/// belonging to the recipient
925	pub your_last_per_commitment_secret: [u8; 32],
926	/// The sender's per-commitment point for their current commitment transaction
927	pub my_current_per_commitment_point: PublicKey,
928	/// The next funding transaction ID
929	///
930	/// Allows peers to finalize the signing steps of an interactive transaction construction, or
931	/// safely abort that transaction if it was not signed by one of the peers, who has thus already
932	/// removed it from its state.
933	///
934	/// If we've sent `commtiment_signed` for an interactively constructed transaction
935	/// during a signing session, but have not received `tx_signatures` we MUST set `next_funding`
936	/// to the txid of that interactive transaction, else we MUST NOT set it.
937	///
938	/// See the spec for further details on this:
939	///   * `channel_reestablish`-sending node: https:///github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L2466-L2470
940	///   * `channel_reestablish`-receiving node: https:///github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L2520-L2531
941	pub next_funding: Option<NextFunding>,
942	/// The last funding txid sent by the sending node, which may be:
943	/// - the txid of the last `splice_locked` it sent, otherwise
944	/// - the txid of the funding transaction if it sent `channel_ready`, or else
945	/// - `None` if it has never sent `channel_ready` or `splice_locked`
946	///
947	/// Also contains a bitfield indicating which messages should be retransmitted.
948	pub my_current_funding_locked: Option<FundingLocked>,
949}
950
951/// Information exchanged during channel reestablishment about the next funding from interactive
952/// transaction construction.
953#[derive(Clone, Debug, Hash, PartialEq, Eq)]
954pub struct NextFunding {
955	/// The txid of the interactive transaction construction.
956	pub txid: Txid,
957
958	/// A bitfield indicating which messages should be retransmitted by the receiving node.
959	///
960	/// See [`NextFundingFlag`] for details.
961	pub retransmit_flags: u8,
962}
963
964impl NextFunding {
965	/// Sets the bit in `retransmit_flags` for retransmitting the message corresponding to `flag`.
966	pub fn retransmit(&mut self, flag: NextFundingFlag) {
967		self.retransmit_flags |= 1 << flag as u8;
968	}
969
970	/// Returns whether the message corresponding to `flag` should be retransmitted.
971	pub fn should_retransmit(&self, flag: NextFundingFlag) -> bool {
972		self.retransmit_flags & (1 << flag as u8) != 0
973	}
974}
975
976/// Bit positions used in [`NextFunding::retransmit_flags`] for requesting message retransmission.
977#[repr(u8)]
978pub enum NextFundingFlag {
979	/// Retransmit `commitment_signed`.
980	CommitmentSigned = 0,
981}
982
983/// Information exchanged during channel reestablishment about the last funding locked.
984#[derive(Clone, Debug, Hash, PartialEq, Eq)]
985pub struct FundingLocked {
986	/// The last txid sent by the sending node, which may be either from the last `splice_locked` or
987	/// for the initial funding transaction if it sent `channel_ready`.
988	pub txid: Txid,
989
990	/// A bitfield indicating which messages should be retransmitted by the receiving node.
991	///
992	/// See [`FundingLockedFlags`] for details.
993	pub retransmit_flags: u8,
994}
995
996impl FundingLocked {
997	/// Sets the bit in `retransmit_flags` for retransmitting the message corresponding to `flag`.
998	pub fn retransmit(&mut self, flag: FundingLockedFlags) {
999		self.retransmit_flags |= 1 << flag as u8;
1000	}
1001
1002	/// Returns whether the message corresponding to `flag` should be retransmitted.
1003	pub fn should_retransmit(&self, flag: FundingLockedFlags) -> bool {
1004		self.retransmit_flags & (1 << flag as u8) != 0
1005	}
1006}
1007
1008/// Bit positions used in [`FundingLocked::retransmit_flags`] for requesting message retransmission.
1009#[repr(u8)]
1010pub enum FundingLockedFlags {
1011	/// Retransmit `announcement_signatures`.
1012	AnnouncementSignatures = 0,
1013}
1014
1015/// An [`announcement_signatures`] message to be sent to or received from a peer.
1016///
1017/// [`announcement_signatures`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message
1018#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1019pub struct AnnouncementSignatures {
1020	/// The channel ID
1021	pub channel_id: ChannelId,
1022	/// The short channel ID
1023	pub short_channel_id: u64,
1024	/// A signature by the node key
1025	pub node_signature: Signature,
1026	/// A signature by the funding key
1027	pub bitcoin_signature: Signature,
1028}
1029
1030/// An address which can be used to connect to a remote peer.
1031#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1032pub enum SocketAddress {
1033	/// An IPv4 address and port on which the peer is listening.
1034	TcpIpV4 {
1035		/// The 4-byte IPv4 address
1036		addr: [u8; 4],
1037		/// The port on which the node is listening
1038		port: u16,
1039	},
1040	/// An IPv6 address and port on which the peer is listening.
1041	TcpIpV6 {
1042		/// The 16-byte IPv6 address
1043		addr: [u8; 16],
1044		/// The port on which the node is listening
1045		port: u16,
1046	},
1047	/// An old-style Tor onion address/port on which the peer is listening.
1048	///
1049	/// This field is deprecated and the Tor network generally no longer supports V2 Onion
1050	/// addresses. Thus, the details are not parsed here.
1051	OnionV2([u8; 12]),
1052	/// A new-style Tor onion address/port on which the peer is listening.
1053	///
1054	/// To create the human-readable "hostname", concatenate the ED25519 pubkey, checksum, and version,
1055	/// wrap as base32 and append ".onion".
1056	OnionV3 {
1057		/// The ed25519 long-term public key of the peer
1058		ed25519_pubkey: [u8; 32],
1059		/// The checksum of the pubkey and version, as included in the onion address
1060		checksum: u16,
1061		/// The version byte, as defined by the Tor Onion v3 spec.
1062		version: u8,
1063		/// The port on which the node is listening
1064		port: u16,
1065	},
1066	/// A hostname/port on which the peer is listening.
1067	Hostname {
1068		/// The hostname on which the node is listening.
1069		hostname: Hostname,
1070		/// The port on which the node is listening.
1071		port: u16,
1072	},
1073}
1074impl SocketAddress {
1075	/// Gets the ID of this address type. Addresses in [`NodeAnnouncement`] messages should be sorted
1076	/// by this.
1077	pub(crate) fn get_id(&self) -> u8 {
1078		match self {
1079			&SocketAddress::TcpIpV4 { .. } => 1,
1080			&SocketAddress::TcpIpV6 { .. } => 2,
1081			&SocketAddress::OnionV2(_) => 3,
1082			&SocketAddress::OnionV3 { .. } => 4,
1083			&SocketAddress::Hostname { .. } => 5,
1084		}
1085	}
1086
1087	/// Strict byte-length of address descriptor, 1-byte type not recorded
1088	fn len(&self) -> u16 {
1089		match self {
1090			&SocketAddress::TcpIpV4 { .. } => 6,
1091			&SocketAddress::TcpIpV6 { .. } => 18,
1092			&SocketAddress::OnionV2(_) => 12,
1093			&SocketAddress::OnionV3 { .. } => 37,
1094			// Consists of 1-byte hostname length, hostname bytes, and 2-byte port.
1095			&SocketAddress::Hostname { ref hostname, .. } => u16::from(hostname.len()) + 3,
1096		}
1097	}
1098
1099	/// The maximum length of any address descriptor, not including the 1-byte type.
1100	/// This maximum length is reached by a hostname address descriptor:
1101	/// a hostname with a maximum length of 255, its 1-byte length and a 2-byte port.
1102	pub(crate) const MAX_LEN: u16 = 258;
1103
1104	pub(crate) fn is_tor(&self) -> bool {
1105		match self {
1106			&SocketAddress::TcpIpV4 { .. } => false,
1107			&SocketAddress::TcpIpV6 { .. } => false,
1108			&SocketAddress::OnionV2(_) => true,
1109			&SocketAddress::OnionV3 { .. } => true,
1110			&SocketAddress::Hostname { .. } => false,
1111		}
1112	}
1113}
1114
1115impl Writeable for SocketAddress {
1116	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1117		match self {
1118			&SocketAddress::TcpIpV4 { ref addr, ref port } => {
1119				1u8.write(writer)?;
1120				addr.write(writer)?;
1121				port.write(writer)?;
1122			},
1123			&SocketAddress::TcpIpV6 { ref addr, ref port } => {
1124				2u8.write(writer)?;
1125				addr.write(writer)?;
1126				port.write(writer)?;
1127			},
1128			&SocketAddress::OnionV2(bytes) => {
1129				3u8.write(writer)?;
1130				bytes.write(writer)?;
1131			},
1132			&SocketAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
1133				4u8.write(writer)?;
1134				ed25519_pubkey.write(writer)?;
1135				checksum.write(writer)?;
1136				version.write(writer)?;
1137				port.write(writer)?;
1138			},
1139			&SocketAddress::Hostname { ref hostname, ref port } => {
1140				5u8.write(writer)?;
1141				hostname.write(writer)?;
1142				port.write(writer)?;
1143			},
1144		}
1145		Ok(())
1146	}
1147}
1148
1149impl Readable for Result<SocketAddress, u8> {
1150	fn read<R: Read>(reader: &mut R) -> Result<Result<SocketAddress, u8>, DecodeError> {
1151		let byte = <u8 as Readable>::read(reader)?;
1152		match byte {
1153			1 => Ok(Ok(SocketAddress::TcpIpV4 {
1154				addr: Readable::read(reader)?,
1155				port: Readable::read(reader)?,
1156			})),
1157			2 => Ok(Ok(SocketAddress::TcpIpV6 {
1158				addr: Readable::read(reader)?,
1159				port: Readable::read(reader)?,
1160			})),
1161			3 => Ok(Ok(SocketAddress::OnionV2(Readable::read(reader)?))),
1162			4 => Ok(Ok(SocketAddress::OnionV3 {
1163				ed25519_pubkey: Readable::read(reader)?,
1164				checksum: Readable::read(reader)?,
1165				version: Readable::read(reader)?,
1166				port: Readable::read(reader)?,
1167			})),
1168			5 => Ok(Ok(SocketAddress::Hostname {
1169				hostname: Readable::read(reader)?,
1170				port: Readable::read(reader)?,
1171			})),
1172			_ => return Ok(Err(byte)),
1173		}
1174	}
1175}
1176
1177impl Readable for SocketAddress {
1178	fn read<R: Read>(reader: &mut R) -> Result<SocketAddress, DecodeError> {
1179		match Readable::read(reader) {
1180			Ok(Ok(res)) => Ok(res),
1181			Ok(Err(_)) => Err(DecodeError::UnknownVersion),
1182			Err(e) => Err(e),
1183		}
1184	}
1185}
1186
1187/// [`SocketAddress`] error variants
1188#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1189pub enum SocketAddressParseError {
1190	/// Socket address (IPv4/IPv6) parsing error
1191	SocketAddrParse,
1192	/// Invalid input format
1193	InvalidInput,
1194	/// Invalid port
1195	InvalidPort,
1196	/// Invalid onion v3 address
1197	InvalidOnionV3,
1198}
1199
1200impl fmt::Display for SocketAddressParseError {
1201	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1202		match self {
1203			SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"),
1204			SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \
1205				Expected: \"<ipv4>:<port>\", \"[<ipv6>]:<port>\", \"<onion address>.onion:<port>\" or \"<hostname>:<port>\""),
1206			SocketAddressParseError::InvalidPort => write!(f, "Invalid port"),
1207			SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"),
1208		}
1209	}
1210}
1211
1212#[cfg(feature = "std")]
1213impl std::error::Error for SocketAddressParseError {}
1214
1215#[cfg(feature = "std")]
1216impl From<std::net::SocketAddrV4> for SocketAddress {
1217	fn from(addr: std::net::SocketAddrV4) -> Self {
1218		SocketAddress::TcpIpV4 { addr: addr.ip().octets(), port: addr.port() }
1219	}
1220}
1221
1222#[cfg(feature = "std")]
1223impl From<std::net::SocketAddrV6> for SocketAddress {
1224	fn from(addr: std::net::SocketAddrV6) -> Self {
1225		SocketAddress::TcpIpV6 { addr: addr.ip().octets(), port: addr.port() }
1226	}
1227}
1228
1229#[cfg(feature = "std")]
1230impl From<std::net::SocketAddr> for SocketAddress {
1231	fn from(addr: std::net::SocketAddr) -> Self {
1232		match addr {
1233			std::net::SocketAddr::V4(addr) => addr.into(),
1234			std::net::SocketAddr::V6(addr) => addr.into(),
1235		}
1236	}
1237}
1238
1239#[cfg(feature = "std")]
1240impl std::net::ToSocketAddrs for SocketAddress {
1241	type Iter = std::vec::IntoIter<std::net::SocketAddr>;
1242
1243	fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
1244		match self {
1245			SocketAddress::TcpIpV4 { addr, port } => {
1246				let ip_addr = std::net::Ipv4Addr::from(*addr);
1247				let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1248				Ok(vec![socket_addr].into_iter())
1249			},
1250			SocketAddress::TcpIpV6 { addr, port } => {
1251				let ip_addr = std::net::Ipv6Addr::from(*addr);
1252				let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1253				Ok(vec![socket_addr].into_iter())
1254			},
1255			SocketAddress::Hostname { ref hostname, port } => {
1256				(hostname.as_str(), *port).to_socket_addrs()
1257			},
1258			SocketAddress::OnionV2(..) => Err(std::io::Error::new(
1259				std::io::ErrorKind::Other,
1260				"Resolution of OnionV2 addresses is currently unsupported.",
1261			)),
1262			SocketAddress::OnionV3 { .. } => Err(std::io::Error::new(
1263				std::io::ErrorKind::Other,
1264				"Resolution of OnionV3 addresses is currently unsupported.",
1265			)),
1266		}
1267	}
1268}
1269
1270/// Parses an OnionV3 host and port into a [`SocketAddress::OnionV3`].
1271///
1272/// The host part must end with ".onion".
1273pub fn parse_onion_address(
1274	host: &str, port: u16,
1275) -> Result<SocketAddress, SocketAddressParseError> {
1276	if !host.ends_with(".onion") {
1277		return Err(SocketAddressParseError::InvalidInput);
1278	}
1279	let domain = &host[..host.len() - ".onion".len()];
1280	if domain.len() != 56 {
1281		return Err(SocketAddressParseError::InvalidOnionV3);
1282	}
1283	let onion = base32::Alphabet::RFC4648 { padding: false }
1284		.decode(domain)
1285		.map_err(|_| SocketAddressParseError::InvalidOnionV3)?;
1286	if onion.len() != 35 {
1287		return Err(SocketAddressParseError::InvalidOnionV3);
1288	}
1289
1290	let mut ed25519_pubkey = [0u8; 32];
1291	ed25519_pubkey.copy_from_slice(&onion[0..32]);
1292
1293	let checksum = u16::from_be_bytes([onion[32], onion[33]]);
1294	let version = onion[34];
1295
1296	Ok(SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port })
1297}
1298
1299impl Display for SocketAddress {
1300	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1301		match self {
1302			SocketAddress::TcpIpV4{addr, port} => write!(
1303				f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)?,
1304			SocketAddress::TcpIpV6{addr, port} => write!(
1305				f,
1306				"[{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}]:{}",
1307				addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15], port
1308			)?,
1309			SocketAddress::OnionV2(bytes) => write!(f, "OnionV2({:?})", bytes)?,
1310			SocketAddress::OnionV3 {
1311				ed25519_pubkey,
1312				checksum,
1313				version,
1314				port,
1315			} => {
1316				let mut addr = Vec::with_capacity(35);
1317				addr.extend_from_slice(ed25519_pubkey);
1318				let [c0, c1] = checksum.to_be_bytes();
1319				addr.push(c0);
1320				addr.push(c1);
1321				addr.push(*version);
1322				let onion = base32::Alphabet::RFC4648 { padding: false }.encode(&addr).to_lowercase();
1323				write!(f, "{}.onion:{}", onion, port)?
1324			},
1325			SocketAddress::Hostname { hostname, port } => write!(f, "{}:{}", hostname, port)?,
1326		}
1327		Ok(())
1328	}
1329}
1330
1331#[cfg(feature = "std")]
1332impl FromStr for SocketAddress {
1333	type Err = SocketAddressParseError;
1334
1335	fn from_str(s: &str) -> Result<Self, Self::Err> {
1336		match std::net::SocketAddr::from_str(s) {
1337			Ok(addr) => Ok(addr.into()),
1338			Err(_) => {
1339				let trimmed_input = match s.rfind(":") {
1340					Some(pos) => pos,
1341					None => return Err(SocketAddressParseError::InvalidInput),
1342				};
1343				let host = &s[..trimmed_input];
1344				let port: u16 = s[trimmed_input + 1..]
1345					.parse()
1346					.map_err(|_| SocketAddressParseError::InvalidPort)?;
1347				if host.ends_with(".onion") {
1348					return parse_onion_address(host, port);
1349				};
1350				if let Ok(hostname) = Hostname::try_from(s[..trimmed_input].to_string()) {
1351					return Ok(SocketAddress::Hostname { hostname, port });
1352				};
1353				return Err(SocketAddressParseError::SocketAddrParse);
1354			},
1355		}
1356	}
1357}
1358
1359/// Represents the set of gossip messages that require a signature from a node's identity key.
1360pub enum UnsignedGossipMessage<'a> {
1361	/// An unsigned channel announcement.
1362	ChannelAnnouncement(&'a UnsignedChannelAnnouncement),
1363	/// An unsigned channel update.
1364	ChannelUpdate(&'a UnsignedChannelUpdate),
1365	/// An unsigned node announcement.
1366	NodeAnnouncement(&'a UnsignedNodeAnnouncement),
1367}
1368
1369impl<'a> Writeable for UnsignedGossipMessage<'a> {
1370	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1371		match self {
1372			UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer),
1373			UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer),
1374			UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer),
1375		}
1376	}
1377}
1378
1379/// The unsigned part of a [`node_announcement`] message.
1380///
1381/// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message
1382#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1383pub struct UnsignedNodeAnnouncement {
1384	/// The advertised features
1385	pub features: NodeFeatures,
1386	/// A strictly monotonic announcement counter, with gaps allowed
1387	pub timestamp: u32,
1388	/// The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back
1389	/// to this node).
1390	pub node_id: NodeId,
1391	/// An RGB color for UI purposes
1392	pub rgb: [u8; 3],
1393	/// An alias, for UI purposes.
1394	///
1395	/// This should be sanitized before use. There is no guarantee of uniqueness.
1396	pub alias: NodeAlias,
1397	/// List of addresses on which this node is reachable
1398	pub addresses: Vec<SocketAddress>,
1399	/// Excess address data which was signed as a part of the message which we do not (yet) understand how
1400	/// to decode.
1401	///
1402	/// This is stored to ensure forward-compatibility as new address types are added to the lightning gossip protocol.
1403	pub excess_address_data: Vec<u8>,
1404	/// Excess data which was signed as a part of the message which we do not (yet) understand how
1405	/// to decode.
1406	///
1407	/// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol.
1408	pub excess_data: Vec<u8>,
1409}
1410#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1411/// A [`node_announcement`] message to be sent to or received from a peer.
1412///
1413/// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message
1414pub struct NodeAnnouncement {
1415	/// The signature by the node key
1416	pub signature: Signature,
1417	/// The actual content of the announcement
1418	pub contents: UnsignedNodeAnnouncement,
1419}
1420
1421/// The unsigned part of a [`channel_announcement`] message.
1422///
1423/// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
1424#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1425pub struct UnsignedChannelAnnouncement {
1426	/// The advertised channel features
1427	pub features: ChannelFeatures,
1428	/// The genesis hash of the blockchain where the channel is to be opened
1429	pub chain_hash: ChainHash,
1430	/// The short channel ID
1431	pub short_channel_id: u64,
1432	/// One of the two `node_id`s which are endpoints of this channel
1433	pub node_id_1: NodeId,
1434	/// The other of the two `node_id`s which are endpoints of this channel
1435	pub node_id_2: NodeId,
1436	/// The funding key for the first node
1437	pub bitcoin_key_1: NodeId,
1438	/// The funding key for the second node
1439	pub bitcoin_key_2: NodeId,
1440	/// Excess data which was signed as a part of the message which we do not (yet) understand how
1441	/// to decode.
1442	///
1443	/// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol.
1444	pub excess_data: Vec<u8>,
1445}
1446/// A [`channel_announcement`] message to be sent to or received from a peer.
1447///
1448/// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message
1449#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1450pub struct ChannelAnnouncement {
1451	/// Authentication of the announcement by the first public node
1452	pub node_signature_1: Signature,
1453	/// Authentication of the announcement by the second public node
1454	pub node_signature_2: Signature,
1455	/// Proof of funding UTXO ownership by the first public node
1456	pub bitcoin_signature_1: Signature,
1457	/// Proof of funding UTXO ownership by the second public node
1458	pub bitcoin_signature_2: Signature,
1459	/// The actual announcement
1460	pub contents: UnsignedChannelAnnouncement,
1461}
1462
1463/// The unsigned part of a [`channel_update`] message.
1464///
1465/// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
1466#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1467pub struct UnsignedChannelUpdate {
1468	/// The genesis hash of the blockchain where the channel is to be opened
1469	pub chain_hash: ChainHash,
1470	/// The short channel ID
1471	pub short_channel_id: u64,
1472	/// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
1473	pub timestamp: u32,
1474	/// Flags pertaining to this message.
1475	pub message_flags: u8,
1476	/// Flags pertaining to the channel, including to which direction in the channel this update
1477	/// applies and whether the direction is currently able to forward HTLCs.
1478	pub channel_flags: u8,
1479	/// The number of blocks such that if:
1480	/// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta`
1481	/// then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines
1482	/// the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a
1483	/// `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10,
1484	/// then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before
1485	/// forwarding. Note that the HTLC sender is the one who originally sets this value when
1486	/// constructing the route.
1487	pub cltv_expiry_delta: u16,
1488	/// The minimum HTLC size incoming to sender, in milli-satoshi
1489	pub htlc_minimum_msat: u64,
1490	/// The maximum HTLC value incoming to sender, in milli-satoshi.
1491	///
1492	/// This used to be optional.
1493	pub htlc_maximum_msat: u64,
1494	/// The base HTLC fee charged by sender, in milli-satoshi
1495	pub fee_base_msat: u32,
1496	/// The amount to fee multiplier, in micro-satoshi
1497	pub fee_proportional_millionths: u32,
1498	/// Excess data which was signed as a part of the message which we do not (yet) understand how
1499	/// to decode.
1500	///
1501	/// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol.
1502	pub excess_data: Vec<u8>,
1503}
1504/// A [`channel_update`] message to be sent to or received from a peer.
1505///
1506/// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
1507#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1508pub struct ChannelUpdate {
1509	/// A signature of the channel update
1510	pub signature: Signature,
1511	/// The actual channel update
1512	pub contents: UnsignedChannelUpdate,
1513}
1514
1515/// A [`query_channel_range`] message is used to query a peer for channel
1516/// UTXOs in a range of blocks. The recipient of a query makes a best
1517/// effort to reply to the query using one or more [`ReplyChannelRange`]
1518/// messages.
1519///
1520/// [`query_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages
1521#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1522pub struct QueryChannelRange {
1523	/// The genesis hash of the blockchain being queried
1524	pub chain_hash: ChainHash,
1525	/// The height of the first block for the channel UTXOs being queried
1526	pub first_blocknum: u32,
1527	/// The number of blocks to include in the query results
1528	pub number_of_blocks: u32,
1529}
1530
1531/// A [`reply_channel_range`] message is a reply to a [`QueryChannelRange`]
1532/// message.
1533///
1534/// Multiple `reply_channel_range` messages can be sent in reply
1535/// to a single [`QueryChannelRange`] message. The query recipient makes a
1536/// best effort to respond based on their local network view which may
1537/// not be a perfect view of the network. The `short_channel_id`s in the
1538/// reply are encoded. We only support `encoding_type=0` uncompressed
1539/// serialization and do not support `encoding_type=1` zlib serialization.
1540///
1541/// [`reply_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages
1542#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1543pub struct ReplyChannelRange {
1544	/// The genesis hash of the blockchain being queried
1545	pub chain_hash: ChainHash,
1546	/// The height of the first block in the range of the reply
1547	pub first_blocknum: u32,
1548	/// The number of blocks included in the range of the reply
1549	pub number_of_blocks: u32,
1550	/// True when this is the final reply for a query
1551	pub sync_complete: bool,
1552	/// The `short_channel_id`s in the channel range
1553	pub short_channel_ids: Vec<u64>,
1554}
1555
1556/// A [`query_short_channel_ids`] message is used to query a peer for
1557/// routing gossip messages related to one or more `short_channel_id`s.
1558///
1559/// The query recipient will reply with the latest, if available,
1560/// [`ChannelAnnouncement`], [`ChannelUpdate`] and [`NodeAnnouncement`] messages
1561/// it maintains for the requested `short_channel_id`s followed by a
1562/// [`ReplyShortChannelIdsEnd`] message. The `short_channel_id`s sent in
1563/// this query are encoded. We only support `encoding_type=0` uncompressed
1564/// serialization and do not support `encoding_type=1` zlib serialization.
1565///
1566/// [`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
1567#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1568pub struct QueryShortChannelIds {
1569	/// The genesis hash of the blockchain being queried
1570	pub chain_hash: ChainHash,
1571	/// The short_channel_ids that are being queried
1572	pub short_channel_ids: Vec<u64>,
1573}
1574
1575/// A [`reply_short_channel_ids_end`] message is sent as a reply to a
1576/// message. The query recipient makes a best
1577/// effort to respond based on their local network view which may not be
1578/// a perfect view of the network.
1579///
1580/// [`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
1581#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1582pub struct ReplyShortChannelIdsEnd {
1583	/// The genesis hash of the blockchain that was queried
1584	pub chain_hash: ChainHash,
1585	/// Indicates if the query recipient maintains up-to-date channel
1586	/// information for the `chain_hash`
1587	pub full_information: bool,
1588}
1589
1590/// A [`gossip_timestamp_filter`] message is used by a node to request
1591/// gossip relay for messages in the requested time range when the
1592/// `gossip_queries` feature has been negotiated.
1593///
1594/// [`gossip_timestamp_filter`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-gossip_timestamp_filter-message
1595#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1596pub struct GossipTimestampFilter {
1597	/// The genesis hash of the blockchain for channel and node information
1598	pub chain_hash: ChainHash,
1599	/// The starting unix timestamp
1600	pub first_timestamp: u32,
1601	/// The range of information in seconds
1602	pub timestamp_range: u32,
1603}
1604
1605/// Encoding type for data compression of collections in gossip queries.
1606///
1607/// We do not support `encoding_type=1` zlib serialization [defined in BOLT
1608/// #7](https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages).
1609enum EncodingType {
1610	Uncompressed = 0x00,
1611}
1612
1613/// Used to put an error message in a [`LightningError`].
1614#[derive(Clone, Debug, Hash, PartialEq)]
1615pub enum ErrorAction {
1616	/// The peer took some action which made us think they were useless. Disconnect them.
1617	DisconnectPeer {
1618		/// An error message which we should make an effort to send before we disconnect.
1619		msg: Option<ErrorMessage>,
1620	},
1621	/// The peer did something incorrect. Tell them without closing any channels and disconnect them.
1622	DisconnectPeerWithWarning {
1623		/// A warning message which we should make an effort to send before we disconnect.
1624		msg: WarningMessage,
1625	},
1626	/// The peer did something harmless that we weren't able to process, just log and ignore
1627	// New code should *not* use this. New code must use IgnoreAndLog, below!
1628	IgnoreError,
1629	/// The peer did something harmless that we weren't able to meaningfully process.
1630	/// If the error is logged, log it at the given level.
1631	IgnoreAndLog(logger::Level),
1632	/// The peer provided us with a gossip message which we'd already seen. In most cases this
1633	/// should be ignored, but it may result in the message being forwarded if it is a duplicate of
1634	/// our own channel announcements.
1635	IgnoreDuplicateGossip,
1636	/// The peer did something incorrect. Tell them.
1637	SendErrorMessage {
1638		/// The message to send.
1639		msg: ErrorMessage,
1640	},
1641	/// The peer did something incorrect. Tell them without closing any channels.
1642	SendWarningMessage {
1643		/// The message to send.
1644		msg: WarningMessage,
1645		/// The peer may have done something harmless that we weren't able to meaningfully process,
1646		/// though we should still tell them about it.
1647		/// If this event is logged, log it at the given level.
1648		log_level: logger::Level,
1649	},
1650}
1651
1652/// An Err type for failure to process messages.
1653#[derive(Clone, Debug)]
1654pub struct LightningError {
1655	/// A human-readable message describing the error
1656	pub err: String,
1657	/// The action which should be taken against the offending peer.
1658	pub action: ErrorAction,
1659}
1660
1661/// Struct used to return values from [`RevokeAndACK`] messages, containing a bunch of commitment
1662/// transaction updates if they were pending.
1663#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1664pub struct CommitmentUpdate {
1665	/// `update_add_htlc` messages which should be sent
1666	pub update_add_htlcs: Vec<UpdateAddHTLC>,
1667	/// `update_fulfill_htlc` messages which should be sent
1668	pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
1669	/// `update_fail_htlc` messages which should be sent
1670	pub update_fail_htlcs: Vec<UpdateFailHTLC>,
1671	/// `update_fail_malformed_htlc` messages which should be sent
1672	pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
1673	/// An `update_fee` message which should be sent
1674	pub update_fee: Option<UpdateFee>,
1675	/// `commitment_signed` messages which should be sent
1676	pub commitment_signed: Vec<CommitmentSigned>,
1677}
1678
1679/// An event generated by a [`BaseMessageHandler`] which indicates a message should be sent to a
1680/// peer (or broadcast to most peers).
1681///
1682/// These events are handled by [`PeerManager::process_events`] if you are using a [`PeerManager`].
1683///
1684/// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
1685/// [`PeerManager`]: crate::ln::peer_handler::PeerManager
1686#[derive(Clone, Debug)]
1687#[cfg_attr(any(test, feature = "_test_utils"), derive(PartialEq))]
1688pub enum MessageSendEvent {
1689	/// Used to indicate that we've accepted a channel open and should send the accept_channel
1690	/// message provided to the given peer.
1691	SendAcceptChannel {
1692		/// The node_id of the node which should receive this message
1693		node_id: PublicKey,
1694		/// The message which should be sent.
1695		msg: AcceptChannel,
1696	},
1697	/// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1698	/// message provided to the given peer.
1699	SendAcceptChannelV2 {
1700		/// The node_id of the node which should receive this message
1701		node_id: PublicKey,
1702		/// The message which should be sent.
1703		msg: AcceptChannelV2,
1704	},
1705	/// Used to indicate that we've initiated a channel open and should send the open_channel
1706	/// message provided to the given peer.
1707	SendOpenChannel {
1708		/// The node_id of the node which should receive this message
1709		node_id: PublicKey,
1710		/// The message which should be sent.
1711		msg: OpenChannel,
1712	},
1713	/// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1714	/// message provided to the given peer.
1715	SendOpenChannelV2 {
1716		/// The node_id of the node which should receive this message
1717		node_id: PublicKey,
1718		/// The message which should be sent.
1719		msg: OpenChannelV2,
1720	},
1721	/// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1722	SendFundingCreated {
1723		/// The node_id of the node which should receive this message
1724		node_id: PublicKey,
1725		/// The message which should be sent.
1726		msg: FundingCreated,
1727	},
1728	/// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1729	SendFundingSigned {
1730		/// The node_id of the node which should receive this message
1731		node_id: PublicKey,
1732		/// The message which should be sent.
1733		msg: FundingSigned,
1734	},
1735	/// Used to indicate that a stfu message should be sent to the peer with the given node id.
1736	SendStfu {
1737		/// The node_id of the node which should receive this message
1738		node_id: PublicKey,
1739		/// The message which should be sent.
1740		msg: Stfu,
1741	},
1742	/// Used to indicate that a splice_init message should be sent to the peer with the given node id.
1743	SendSpliceInit {
1744		/// The node_id of the node which should receive this message
1745		node_id: PublicKey,
1746		/// The message which should be sent.
1747		msg: SpliceInit,
1748	},
1749	/// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1750	SendSpliceAck {
1751		/// The node_id of the node which should receive this message
1752		node_id: PublicKey,
1753		/// The message which should be sent.
1754		msg: SpliceAck,
1755	},
1756	/// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1757	SendSpliceLocked {
1758		/// The node_id of the node which should receive this message
1759		node_id: PublicKey,
1760		/// The message which should be sent.
1761		msg: SpliceLocked,
1762	},
1763	/// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1764	SendTxAddInput {
1765		/// The node_id of the node which should receive this message
1766		node_id: PublicKey,
1767		/// The message which should be sent.
1768		msg: TxAddInput,
1769	},
1770	/// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1771	SendTxAddOutput {
1772		/// The node_id of the node which should receive this message
1773		node_id: PublicKey,
1774		/// The message which should be sent.
1775		msg: TxAddOutput,
1776	},
1777	/// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1778	SendTxRemoveInput {
1779		/// The node_id of the node which should receive this message
1780		node_id: PublicKey,
1781		/// The message which should be sent.
1782		msg: TxRemoveInput,
1783	},
1784	/// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1785	SendTxRemoveOutput {
1786		/// The node_id of the node which should receive this message
1787		node_id: PublicKey,
1788		/// The message which should be sent.
1789		msg: TxRemoveOutput,
1790	},
1791	/// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1792	SendTxComplete {
1793		/// The node_id of the node which should receive this message
1794		node_id: PublicKey,
1795		/// The message which should be sent.
1796		msg: TxComplete,
1797	},
1798	/// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1799	SendTxSignatures {
1800		/// The node_id of the node which should receive this message
1801		node_id: PublicKey,
1802		/// The message which should be sent.
1803		msg: TxSignatures,
1804	},
1805	/// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1806	SendTxInitRbf {
1807		/// The node_id of the node which should receive this message
1808		node_id: PublicKey,
1809		/// The message which should be sent.
1810		msg: TxInitRbf,
1811	},
1812	/// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1813	SendTxAckRbf {
1814		/// The node_id of the node which should receive this message
1815		node_id: PublicKey,
1816		/// The message which should be sent.
1817		msg: TxAckRbf,
1818	},
1819	/// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1820	SendTxAbort {
1821		/// The node_id of the node which should receive this message
1822		node_id: PublicKey,
1823		/// The message which should be sent.
1824		msg: TxAbort,
1825	},
1826	/// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1827	SendChannelReady {
1828		/// The node_id of the node which should receive these message(s)
1829		node_id: PublicKey,
1830		/// The channel_ready message which should be sent.
1831		msg: ChannelReady,
1832	},
1833	/// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1834	SendAnnouncementSignatures {
1835		/// The node_id of the node which should receive these message(s)
1836		node_id: PublicKey,
1837		/// The announcement_signatures message which should be sent.
1838		msg: AnnouncementSignatures,
1839	},
1840	/// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1841	/// message should be sent to the peer with the given node_id.
1842	UpdateHTLCs {
1843		/// The node_id of the node which should receive these message(s)
1844		node_id: PublicKey,
1845		/// The channel_id associated with all the update messages.
1846		channel_id: ChannelId,
1847		/// The update messages which should be sent. ALL messages in the struct should be sent!
1848		updates: CommitmentUpdate,
1849	},
1850	/// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1851	SendRevokeAndACK {
1852		/// The node_id of the node which should receive this message
1853		node_id: PublicKey,
1854		/// The message which should be sent.
1855		msg: RevokeAndACK,
1856	},
1857	/// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1858	SendClosingSigned {
1859		/// The node_id of the node which should receive this message
1860		node_id: PublicKey,
1861		/// The message which should be sent.
1862		msg: ClosingSigned,
1863	},
1864	/// Used to indicate that a `closing_complete` message should be sent to the peer with the given `node_id`.
1865	SendClosingComplete {
1866		/// The node_id of the node which should receive this message
1867		node_id: PublicKey,
1868		/// The message which should be sent.
1869		msg: ClosingComplete,
1870	},
1871	/// Used to indicate that a `closing_sig` message should be sent to the peer with the given `node_id`.
1872	SendClosingSig {
1873		/// The node_id of the node which should receive this message
1874		node_id: PublicKey,
1875		/// The message which should be sent.
1876		msg: ClosingSig,
1877	},
1878	/// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1879	SendShutdown {
1880		/// The node_id of the node which should receive this message
1881		node_id: PublicKey,
1882		/// The message which should be sent.
1883		msg: Shutdown,
1884	},
1885	/// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1886	SendChannelReestablish {
1887		/// The node_id of the node which should receive this message
1888		node_id: PublicKey,
1889		/// The message which should be sent.
1890		msg: ChannelReestablish,
1891	},
1892	/// Used to send a channel_announcement and channel_update to a specific peer, likely on
1893	/// initial connection to ensure our peers know about our channels.
1894	SendChannelAnnouncement {
1895		/// The node_id of the node which should receive this message
1896		node_id: PublicKey,
1897		/// The channel_announcement which should be sent.
1898		msg: ChannelAnnouncement,
1899		/// The followup channel_update which should be sent.
1900		update_msg: ChannelUpdate,
1901	},
1902	/// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1903	/// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1904	///
1905	/// Note that after doing so, you very likely (unless you did so very recently) want to
1906	/// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1907	/// ensures that any nodes which see our channel_announcement also have a relevant
1908	/// node_announcement, including relevant feature flags which may be important for routing
1909	/// through or to us.
1910	///
1911	/// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1912	BroadcastChannelAnnouncement {
1913		/// The channel_announcement which should be sent.
1914		msg: ChannelAnnouncement,
1915		/// The followup channel_update which should be sent.
1916		update_msg: Option<ChannelUpdate>,
1917	},
1918	/// Used to indicate that a channel_update should be broadcast to all peers.
1919	BroadcastChannelUpdate {
1920		/// The channel_update which should be sent.
1921		msg: ChannelUpdate,
1922	},
1923	/// Used to indicate that a node_announcement should be broadcast to all peers.
1924	BroadcastNodeAnnouncement {
1925		/// The node_announcement which should be sent.
1926		msg: NodeAnnouncement,
1927	},
1928	/// Used to indicate that a channel_update should be sent to a single peer.
1929	/// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1930	/// private channel and we shouldn't be informing all of our peers of channel parameters.
1931	SendChannelUpdate {
1932		/// The node_id of the node which should receive this message
1933		node_id: PublicKey,
1934		/// The channel_update which should be sent.
1935		msg: ChannelUpdate,
1936	},
1937	/// Broadcast an error downstream to be handled
1938	HandleError {
1939		/// The node_id of the node which should receive this message
1940		node_id: PublicKey,
1941		/// The action which should be taken.
1942		action: ErrorAction,
1943	},
1944	/// Query a peer for channels with funding transaction UTXOs in a block range.
1945	SendChannelRangeQuery {
1946		/// The node_id of this message recipient
1947		node_id: PublicKey,
1948		/// The query_channel_range which should be sent.
1949		msg: QueryChannelRange,
1950	},
1951	/// Request routing gossip messages from a peer for a list of channels identified by
1952	/// their short_channel_ids.
1953	SendShortIdsQuery {
1954		/// The node_id of this message recipient
1955		node_id: PublicKey,
1956		/// The query_short_channel_ids which should be sent.
1957		msg: QueryShortChannelIds,
1958	},
1959	/// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1960	/// emitted during processing of the query.
1961	SendReplyChannelRange {
1962		/// The node_id of this message recipient
1963		node_id: PublicKey,
1964		/// The reply_channel_range which should be sent.
1965		msg: ReplyChannelRange,
1966	},
1967	/// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1968	/// enable receiving gossip messages from the peer.
1969	SendGossipTimestampFilter {
1970		/// The node_id of this message recipient
1971		node_id: PublicKey,
1972		/// The gossip_timestamp_filter which should be sent.
1973		msg: GossipTimestampFilter,
1974	},
1975	/// Sends a channel partner Peer Storage of our backup which they should store.
1976	/// This should be sent on each new connection to the channel partner or whenever we want
1977	/// them to update the backup that they store.
1978	SendPeerStorage {
1979		/// The node_id of this message recipient
1980		node_id: PublicKey,
1981		/// The peer_storage which should be sent.
1982		msg: PeerStorage,
1983	},
1984	/// Sends a channel partner their own peer storage which we store and update when they send
1985	/// a [`PeerStorage`].
1986	SendPeerStorageRetrieval {
1987		/// The node_id of this message recipient
1988		node_id: PublicKey,
1989		/// The peer_storage_retrieval which should be sent.
1990		msg: PeerStorageRetrieval,
1991	},
1992}
1993
1994/// A trait to describe an object which handles when peers connect + disconnect and generates
1995/// outbound messages.
1996///
1997/// It acts as a supertrait for all the P2P message handlers and can contribute to the
1998/// [`InitFeatures`] which we send to peers or decide to refuse connection to peers.
1999pub trait BaseMessageHandler {
2000	/// Gets the list of pending events which were generated by previous actions, clearing the list
2001	/// in the process.
2002	fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2003
2004	/// Indicates a connection to the peer failed/an existing connection was lost.
2005	fn peer_disconnected(&self, their_node_id: PublicKey);
2006
2007	/// Gets the node feature flags which this handler itself supports. All available handlers are
2008	/// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
2009	/// which are broadcasted in our [`NodeAnnouncement`] message.
2010	fn provided_node_features(&self) -> NodeFeatures;
2011
2012	/// Gets the init feature flags which should be sent to the given peer. All available handlers
2013	/// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
2014	/// which are sent in our [`Init`] message.
2015	///
2016	/// Note that this method is called before [`Self::peer_connected`].
2017	fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
2018
2019	/// Handle a peer (re)connecting.
2020	///
2021	/// May return an `Err(())` to indicate that we should immediately disconnect from the peer
2022	/// (e.g. because the features they support are not sufficient to communicate with us).
2023	///
2024	/// Note, of course, that other message handlers may wish to communicate with the peer, which
2025	/// disconnecting them will prevent.
2026	///
2027	/// [`Self::peer_disconnected`] will not be called if `Err(())` is returned.
2028	fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool)
2029		-> Result<(), ()>;
2030}
2031
2032/// A trait to describe an object which can receive channel messages.
2033///
2034/// Messages MAY be called in parallel when they originate from different `their_node_ids`, however
2035/// they MUST NOT be called in parallel when the two calls have the same `their_node_id`.
2036pub trait ChannelMessageHandler: BaseMessageHandler {
2037	// Channel init:
2038	/// Handle an incoming `open_channel` message from the given peer.
2039	fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel);
2040	/// Handle an incoming `open_channel2` message from the given peer.
2041	fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2);
2042	/// Handle an incoming `accept_channel` message from the given peer.
2043	fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel);
2044	/// Handle an incoming `accept_channel2` message from the given peer.
2045	fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2);
2046	/// Handle an incoming `funding_created` message from the given peer.
2047	fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated);
2048	/// Handle an incoming `funding_signed` message from the given peer.
2049	fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned);
2050	/// Handle an incoming `channel_ready` message from the given peer.
2051	fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady);
2052
2053	// Peer Storage
2054	/// Handle an incoming `peer_storage` message from the given peer.
2055	fn handle_peer_storage(&self, their_node_id: PublicKey, msg: PeerStorage);
2056	/// Handle an incoming `peer_storage_retrieval` message from the given peer.
2057	fn handle_peer_storage_retrieval(&self, their_node_id: PublicKey, msg: PeerStorageRetrieval);
2058
2059	// Channel close:
2060	/// Handle an incoming `shutdown` message from the given peer.
2061	fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown);
2062	/// Handle an incoming `closing_signed` message from the given peer.
2063	fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned);
2064	/// Handle an incoming `closing_complete` message from the given peer.
2065	#[cfg(simple_close)]
2066	fn handle_closing_complete(&self, their_node_id: PublicKey, msg: ClosingComplete);
2067	/// Handle an incoming `closing_sig` message from the given peer.
2068	#[cfg(simple_close)]
2069	fn handle_closing_sig(&self, their_node_id: PublicKey, msg: ClosingSig);
2070
2071	// Quiescence
2072	/// Handle an incoming `stfu` message from the given peer.
2073	fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu);
2074
2075	// Splicing
2076	/// Handle an incoming `splice_init` message from the given peer.
2077	fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit);
2078	/// Handle an incoming `splice_ack` message from the given peer.
2079	fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck);
2080	/// Handle an incoming `splice_locked` message from the given peer.
2081	fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked);
2082
2083	// Interactive channel construction
2084	/// Handle an incoming `tx_add_input message` from the given peer.
2085	fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput);
2086	/// Handle an incoming `tx_add_output` message from the given peer.
2087	fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput);
2088	/// Handle an incoming `tx_remove_input` message from the given peer.
2089	fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput);
2090	/// Handle an incoming `tx_remove_output` message from the given peer.
2091	fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput);
2092	/// Handle an incoming `tx_complete message` from the given peer.
2093	fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete);
2094	/// Handle an incoming `tx_signatures` message from the given peer.
2095	fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures);
2096	/// Handle an incoming `tx_init_rbf` message from the given peer.
2097	fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf);
2098	/// Handle an incoming `tx_ack_rbf` message from the given peer.
2099	fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf);
2100	/// Handle an incoming `tx_abort message` from the given peer.
2101	fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort);
2102
2103	// HTLC handling:
2104	/// Handle an incoming `update_add_htlc` message from the given peer.
2105	fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC);
2106	/// Handle an incoming `update_fulfill_htlc` message from the given peer.
2107	fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: UpdateFulfillHTLC);
2108	/// Handle an incoming `update_fail_htlc` message from the given peer.
2109	fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC);
2110	/// Handle an incoming `update_fail_malformed_htlc` message from the given peer.
2111	fn handle_update_fail_malformed_htlc(
2112		&self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC,
2113	);
2114	/// Handle an incoming `commitment_signed` message from the given peer.
2115	fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned);
2116	/// Handle a batch of incoming `commitment_signed` message from the given peer.
2117	fn handle_commitment_signed_batch(
2118		&self, their_node_id: PublicKey, channel_id: ChannelId, batch: Vec<CommitmentSigned>,
2119	);
2120	/// Handle an incoming `revoke_and_ack` message from the given peer.
2121	fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK);
2122
2123	#[cfg(any(test, fuzzing, feature = "_test_utils"))]
2124	fn handle_commitment_signed_batch_test(
2125		&self, their_node_id: PublicKey, batch: &Vec<CommitmentSigned>,
2126	) {
2127		assert!(!batch.is_empty());
2128		if batch.len() == 1 {
2129			self.handle_commitment_signed(their_node_id, &batch[0]);
2130		} else {
2131			let channel_id = batch[0].channel_id;
2132			self.handle_commitment_signed_batch(their_node_id, channel_id, batch.clone());
2133		}
2134	}
2135
2136	/// Handle an incoming `update_fee` message from the given peer.
2137	fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee);
2138
2139	// Channel-to-announce:
2140	/// Handle an incoming `announcement_signatures` message from the given peer.
2141	fn handle_announcement_signatures(
2142		&self, their_node_id: PublicKey, msg: &AnnouncementSignatures,
2143	);
2144
2145	// Channel reestablish:
2146	/// Handle an incoming `channel_reestablish` message from the given peer.
2147	fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish);
2148
2149	/// Handle an incoming `channel_update` message from the given peer.
2150	fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate);
2151
2152	// Error:
2153	/// Handle an incoming `error` message from the given peer.
2154	fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage);
2155
2156	// Handler information:
2157	/// Gets the chain hashes for this `ChannelMessageHandler` indicating which chains it supports.
2158	///
2159	/// If it's `None`, then no particular network chain hash compatibility will be enforced when
2160	/// connecting to peers.
2161	fn get_chain_hashes(&self) -> Option<Vec<ChainHash>>;
2162
2163	/// Indicates that a message was received from any peer for any handler.
2164	/// Called before the message is passed to the appropriate handler.
2165	/// Useful for indicating that a network connection is active.
2166	///
2167	/// Note: Since this function is called frequently, it should be as
2168	/// efficient as possible for its intended purpose.
2169	fn message_received(&self);
2170}
2171
2172/// A trait to describe an object which can receive routing messages.
2173///
2174/// # Implementor DoS Warnings
2175///
2176/// For messages enabled with the `gossip_queries` feature there are potential DoS vectors when
2177/// handling inbound queries. Implementors using an on-disk network graph should be aware of
2178/// repeated disk I/O for queries accessing different parts of the network graph.
2179pub trait RoutingMessageHandler: BaseMessageHandler {
2180	/// Handle an incoming `node_announcement` message, returning `true` if it should be forwarded on,
2181	/// `false` or returning an `Err` otherwise.
2182	///
2183	/// If `their_node_id` is `None`, the message was generated by our own local node.
2184	fn handle_node_announcement(
2185		&self, their_node_id: Option<PublicKey>, msg: &NodeAnnouncement,
2186	) -> Result<bool, LightningError>;
2187	/// Handle a `channel_announcement` message, returning `true` if it should be forwarded on, `false`
2188	/// or returning an `Err` otherwise.
2189	///
2190	/// If `their_node_id` is `None`, the message was generated by our own local node.
2191	fn handle_channel_announcement(
2192		&self, their_node_id: Option<PublicKey>, msg: &ChannelAnnouncement,
2193	) -> Result<bool, LightningError>;
2194	/// Handle an incoming `channel_update` message, returning true if it should be forwarded on,
2195	/// `false` or returning an `Err` otherwise.
2196	///
2197	/// If `their_node_id` is `None`, the message was generated by our own local node.
2198	fn handle_channel_update(
2199		&self, their_node_id: Option<PublicKey>, msg: &ChannelUpdate,
2200	) -> Result<bool, LightningError>;
2201	/// Gets channel announcements and updates required to dump our routing table to a remote node,
2202	/// starting at the `short_channel_id` indicated by `starting_point` and including announcements
2203	/// for a single channel.
2204	fn get_next_channel_announcement(
2205		&self, starting_point: u64,
2206	) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
2207	/// Gets a node announcement required to dump our routing table to a remote node, starting at
2208	/// the node *after* the provided pubkey and including up to one announcement immediately
2209	/// higher (as defined by `<PublicKey as Ord>::cmp`) than `starting_point`.
2210	/// If `None` is provided for `starting_point`, we start at the first node.
2211	fn get_next_node_announcement(
2212		&self, starting_point: Option<&NodeId>,
2213	) -> Option<NodeAnnouncement>;
2214	/// Handles the reply of a query we initiated to learn about channels
2215	/// for a given range of blocks. We can expect to receive one or more
2216	/// replies to a single query.
2217	fn handle_reply_channel_range(
2218		&self, their_node_id: PublicKey, msg: ReplyChannelRange,
2219	) -> Result<(), LightningError>;
2220	/// Handles the reply of a query we initiated asking for routing gossip
2221	/// messages for a list of channels. We should receive this message when
2222	/// a node has completed its best effort to send us the pertaining routing
2223	/// gossip messages.
2224	fn handle_reply_short_channel_ids_end(
2225		&self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd,
2226	) -> Result<(), LightningError>;
2227	/// Handles when a peer asks us to send a list of `short_channel_id`s
2228	/// for the requested range of blocks.
2229	fn handle_query_channel_range(
2230		&self, their_node_id: PublicKey, msg: QueryChannelRange,
2231	) -> Result<(), LightningError>;
2232	/// Handles when a peer asks us to send routing gossip messages for a
2233	/// list of `short_channel_id`s.
2234	fn handle_query_short_channel_ids(
2235		&self, their_node_id: PublicKey, msg: QueryShortChannelIds,
2236	) -> Result<(), LightningError>;
2237
2238	// Handler queueing status:
2239	/// Indicates that there are a large number of [`ChannelAnnouncement`] (or other) messages
2240	/// pending some async action. While there is no guarantee of the rate of future messages, the
2241	/// caller should seek to reduce the rate of new gossip messages handled, especially
2242	/// [`ChannelAnnouncement`]s.
2243	fn processing_queue_high(&self) -> bool;
2244}
2245
2246/// A handler for received [`OnionMessage`]s and for providing generated ones to send.
2247pub trait OnionMessageHandler: BaseMessageHandler {
2248	/// Handle an incoming `onion_message` message from the given peer.
2249	fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage);
2250
2251	/// Returns the next pending onion message for the peer with the given node id.
2252	///
2253	/// Note that onion messages can only be provided upstream via this method and *not* via
2254	/// [`BaseMessageHandler::get_and_clear_pending_msg_events`].
2255	fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage>;
2256
2257	/// Performs actions that should happen roughly every ten seconds after startup. Allows handlers
2258	/// to drop any buffered onion messages intended for prospective peerst.
2259	fn timer_tick_occurred(&self);
2260}
2261
2262/// A handler which can only be used to send messages.
2263///
2264/// This is implemented by [`ChainMonitor`].
2265///
2266/// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
2267pub trait SendOnlyMessageHandler: BaseMessageHandler {}
2268
2269#[derive(Clone, Debug, PartialEq, Eq)]
2270/// Information communicated in the onion to the recipient for multi-part tracking and proof that
2271/// the payment is associated with an invoice.
2272pub struct FinalOnionHopData {
2273	/// When sending a multi-part payment, this secret is used to identify a payment across HTLCs.
2274	/// Because it is generated by the recipient and included in the invoice, it also provides
2275	/// proof to the recipient that the payment was sent by someone with the generated invoice.
2276	pub payment_secret: PaymentSecret,
2277	/// The intended total amount that this payment is for.
2278	///
2279	/// Message serialization may panic if this value is more than 21 million Bitcoin.
2280	pub total_msat: u64,
2281}
2282
2283mod fuzzy_internal_msgs {
2284	use super::{FinalOnionHopData, TrampolineOnionPacket};
2285	use crate::blinded_path::payment::{
2286		BlindedPaymentPath, PaymentConstraints, PaymentContext, PaymentRelay,
2287	};
2288	use crate::ln::onion_utils::AttributionData;
2289	use crate::offers::invoice_request::InvoiceRequest;
2290	use crate::types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
2291	use crate::types::payment::{PaymentPreimage, PaymentSecret};
2292	use bitcoin::secp256k1::PublicKey;
2293
2294	#[allow(unused_imports)]
2295	use crate::prelude::*;
2296
2297	// These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
2298	// them from untrusted input):
2299
2300	pub struct InboundOnionForwardPayload {
2301		pub short_channel_id: u64,
2302		/// The value, in msat, of the payment after this hop's fee is deducted.
2303		pub amt_to_forward: u64,
2304		pub outgoing_cltv_value: u32,
2305	}
2306
2307	#[allow(unused)]
2308	pub struct InboundTrampolineEntrypointPayload {
2309		pub amt_to_forward: u64,
2310		pub outgoing_cltv_value: u32,
2311		pub multipath_trampoline_data: Option<FinalOnionHopData>,
2312		pub trampoline_packet: TrampolineOnionPacket,
2313		/// The blinding point this hop needs to decrypt its Trampoline onion.
2314		/// This is used for Trampoline hops that are not the blinded path intro hop.
2315		pub current_path_key: Option<PublicKey>,
2316	}
2317
2318	pub struct InboundOnionReceivePayload {
2319		pub payment_data: Option<FinalOnionHopData>,
2320		pub payment_metadata: Option<Vec<u8>>,
2321		pub keysend_preimage: Option<PaymentPreimage>,
2322		pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2323		pub sender_intended_htlc_amt_msat: u64,
2324		pub cltv_expiry_height: u32,
2325	}
2326	pub struct InboundOnionBlindedForwardPayload {
2327		pub short_channel_id: u64,
2328		pub payment_relay: PaymentRelay,
2329		pub payment_constraints: PaymentConstraints,
2330		pub features: BlindedHopFeatures,
2331		pub intro_node_blinding_point: Option<PublicKey>,
2332		pub next_blinding_override: Option<PublicKey>,
2333	}
2334	pub struct InboundOnionBlindedReceivePayload {
2335		pub sender_intended_htlc_amt_msat: u64,
2336		pub total_msat: u64,
2337		pub cltv_expiry_height: u32,
2338		pub payment_secret: PaymentSecret,
2339		pub payment_constraints: PaymentConstraints,
2340		pub payment_context: PaymentContext,
2341		pub intro_node_blinding_point: Option<PublicKey>,
2342		pub keysend_preimage: Option<PaymentPreimage>,
2343		pub invoice_request: Option<InvoiceRequest>,
2344		pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2345	}
2346
2347	pub enum InboundOnionPayload {
2348		Forward(InboundOnionForwardPayload),
2349		TrampolineEntrypoint(InboundTrampolineEntrypointPayload),
2350		Receive(InboundOnionReceivePayload),
2351		BlindedForward(InboundOnionBlindedForwardPayload),
2352		BlindedReceive(InboundOnionBlindedReceivePayload),
2353	}
2354
2355	pub struct InboundTrampolineForwardPayload {
2356		pub next_trampoline: PublicKey,
2357		/// The value, in msat, of the payment after this hop's fee is deducted.
2358		pub amt_to_forward: u64,
2359		pub outgoing_cltv_value: u32,
2360	}
2361
2362	pub struct InboundTrampolineBlindedForwardPayload {
2363		pub next_trampoline: PublicKey,
2364		pub payment_relay: PaymentRelay,
2365		pub payment_constraints: PaymentConstraints,
2366		pub features: BlindedHopFeatures,
2367		pub intro_node_blinding_point: Option<PublicKey>,
2368		pub next_blinding_override: Option<PublicKey>,
2369	}
2370
2371	pub enum InboundTrampolinePayload {
2372		Forward(InboundTrampolineForwardPayload),
2373		BlindedForward(InboundTrampolineBlindedForwardPayload),
2374		Receive(InboundOnionReceivePayload),
2375		BlindedReceive(InboundOnionBlindedReceivePayload),
2376	}
2377
2378	pub(crate) enum OutboundOnionPayload<'a> {
2379		Forward {
2380			short_channel_id: u64,
2381			/// The value, in msat, of the payment after this hop's fee is deducted.
2382			amt_to_forward: u64,
2383			outgoing_cltv_value: u32,
2384		},
2385		TrampolineEntrypoint {
2386			amt_to_forward: u64,
2387			outgoing_cltv_value: u32,
2388			multipath_trampoline_data: Option<FinalOnionHopData>,
2389			trampoline_packet: TrampolineOnionPacket,
2390		},
2391		/// This is used for Trampoline hops that are not the blinded path intro hop.
2392		/// We would only ever construct this variant when we are a Trampoline node forwarding a
2393		/// payment along a blinded path.
2394		#[allow(unused)]
2395		BlindedTrampolineEntrypoint {
2396			amt_to_forward: u64,
2397			outgoing_cltv_value: u32,
2398			multipath_trampoline_data: Option<FinalOnionHopData>,
2399			trampoline_packet: TrampolineOnionPacket,
2400			/// The blinding point this hop needs to use for its Trampoline onion.
2401			current_path_key: PublicKey,
2402		},
2403		Receive {
2404			payment_data: Option<FinalOnionHopData>,
2405			payment_metadata: Option<&'a Vec<u8>>,
2406			keysend_preimage: Option<PaymentPreimage>,
2407			custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2408			sender_intended_htlc_amt_msat: u64,
2409			cltv_expiry_height: u32,
2410		},
2411		BlindedForward {
2412			encrypted_tlvs: &'a Vec<u8>,
2413			intro_node_blinding_point: Option<PublicKey>,
2414		},
2415		BlindedReceive {
2416			sender_intended_htlc_amt_msat: u64,
2417			total_msat: u64,
2418			cltv_expiry_height: u32,
2419			encrypted_tlvs: &'a Vec<u8>,
2420			intro_node_blinding_point: Option<PublicKey>, // Set if the introduction node of the blinded path is the final node
2421			keysend_preimage: Option<PaymentPreimage>,
2422			custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2423			invoice_request: Option<&'a InvoiceRequest>,
2424		},
2425	}
2426
2427	pub(crate) enum OutboundTrampolinePayload<'a> {
2428		Forward {
2429			/// The value, in msat, of the payment after this hop's fee is deducted.
2430			amt_to_forward: u64,
2431			outgoing_cltv_value: u32,
2432			/// The node id to which the trampoline node must find a route.
2433			outgoing_node_id: PublicKey,
2434		},
2435		#[cfg(test)]
2436		/// LDK does not support making Trampoline payments to unblinded recipients. However, for
2437		/// the purpose of testing our ability to receive them, we make this variant available in a
2438		/// testing environment.
2439		Receive {
2440			payment_data: Option<FinalOnionHopData>,
2441			sender_intended_htlc_amt_msat: u64,
2442			cltv_expiry_height: u32,
2443		},
2444		#[allow(unused)]
2445		/// This is the last Trampoline hop, whereupon the Trampoline forward mechanism is exited,
2446		/// and payment data is relayed using non-Trampoline blinded hops
2447		LegacyBlindedPathEntry {
2448			/// The value, in msat, of the payment after this hop's fee is deducted.
2449			amt_to_forward: u64,
2450			outgoing_cltv_value: u32,
2451			/// List of blinded path options the last trampoline hop may choose to route through.
2452			payment_paths: Vec<BlindedPaymentPath>,
2453			/// If applicable, features of the BOLT12 invoice being paid.
2454			invoice_features: Option<Bolt12InvoiceFeatures>,
2455		},
2456		BlindedForward {
2457			encrypted_tlvs: &'a Vec<u8>,
2458			intro_node_blinding_point: Option<PublicKey>,
2459		},
2460		BlindedReceive {
2461			sender_intended_htlc_amt_msat: u64,
2462			total_msat: u64,
2463			cltv_expiry_height: u32,
2464			encrypted_tlvs: &'a Vec<u8>,
2465			intro_node_blinding_point: Option<PublicKey>, // Set if the introduction node of the blinded path is the final node
2466			keysend_preimage: Option<PaymentPreimage>,
2467			custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2468		},
2469	}
2470
2471	pub struct DecodedOnionErrorPacket {
2472		pub(crate) hmac: [u8; 32],
2473		pub(crate) failuremsg: Vec<u8>,
2474		pub(crate) pad: Vec<u8>,
2475	}
2476
2477	#[derive(Clone, Debug, Hash, PartialEq, Eq)]
2478	pub struct OnionErrorPacket {
2479		// This really should be a constant size slice, but the spec lets these things be up to 128KB?
2480		// (TODO) We limit it in decode to much lower...
2481		pub data: Vec<u8>,
2482		pub attribution_data: Option<AttributionData>,
2483	}
2484}
2485#[cfg(fuzzing)]
2486pub use self::fuzzy_internal_msgs::*;
2487#[cfg(not(fuzzing))]
2488pub(crate) use self::fuzzy_internal_msgs::*;
2489
2490use super::onion_utils::AttributionData;
2491
2492/// BOLT 4 onion packet including hop data for the next peer.
2493#[derive(Clone, Hash, PartialEq, Eq)]
2494pub struct OnionPacket {
2495	/// BOLT 4 version number.
2496	pub version: u8,
2497	/// In order to ensure we always return an error on onion decode in compliance with [BOLT
2498	/// #4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md), we have to
2499	/// deserialize `OnionPacket`s contained in [`UpdateAddHTLC`] messages even if the ephemeral
2500	/// public key (here) is bogus, so we hold a [`Result`] instead of a [`PublicKey`] as we'd
2501	/// like.
2502	pub public_key: Result<PublicKey, secp256k1::Error>,
2503	/// 1300 bytes encrypted payload for the next hop.
2504	pub hop_data: [u8; 20 * 65],
2505	/// HMAC to verify the integrity of hop_data.
2506	pub hmac: [u8; 32],
2507}
2508
2509impl onion_utils::Packet for OnionPacket {
2510	type Data = onion_utils::FixedSizeOnionPacket;
2511	fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
2512		Self { version: 0, public_key: Ok(pubkey), hop_data: hop_data.0, hmac }
2513	}
2514}
2515
2516impl fmt::Debug for OnionPacket {
2517	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2518		f.write_fmt(format_args!(
2519			"OnionPacket version {} with hmac {:?}",
2520			self.version,
2521			&self.hmac[..]
2522		))
2523	}
2524}
2525
2526/// BOLT 4 onion packet including hop data for the next peer.
2527#[derive(Clone, Hash, PartialEq, Eq)]
2528pub struct TrampolineOnionPacket {
2529	/// Bolt 04 version number
2530	pub version: u8,
2531	/// A random sepc256k1 point, used to build the ECDH shared secret to decrypt hop_data
2532	pub public_key: PublicKey,
2533	/// Encrypted payload for the next hop
2534	//
2535	// Unlike the onion packets used for payments, Trampoline onion packets have to be shorter than
2536	// 1300 bytes. The expected default is 650 bytes.
2537	// TODO: if 650 ends up being the most common size, optimize this to be:
2538	// enum { SixFifty([u8; 650]), VarLen(Vec<u8>) }
2539	pub hop_data: Vec<u8>,
2540	/// HMAC to verify the integrity of hop_data
2541	pub hmac: [u8; 32],
2542}
2543
2544impl onion_utils::Packet for TrampolineOnionPacket {
2545	type Data = Vec<u8>;
2546	fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Self {
2547		Self { version: 0, public_key, hop_data, hmac }
2548	}
2549}
2550
2551impl Writeable for TrampolineOnionPacket {
2552	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2553		self.version.write(w)?;
2554		self.public_key.write(w)?;
2555		w.write_all(&self.hop_data)?;
2556		self.hmac.write(w)?;
2557		Ok(())
2558	}
2559}
2560
2561impl LengthReadable for TrampolineOnionPacket {
2562	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2563		let hop_data_len = r.remaining_bytes().saturating_sub(66); // 1 (version) + 33 (pubkey) + 32 (HMAC) = 66
2564
2565		let version = Readable::read(r)?;
2566		let public_key = Readable::read(r)?;
2567
2568		let mut rd = FixedLengthReader::new(r, hop_data_len);
2569		let hop_data = WithoutLength::<Vec<u8>>::read_from_fixed_length_buffer(&mut rd)?.0;
2570
2571		let hmac = Readable::read(r)?;
2572
2573		Ok(TrampolineOnionPacket { version, public_key, hop_data, hmac })
2574	}
2575}
2576
2577impl Debug for TrampolineOnionPacket {
2578	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2579		f.write_fmt(format_args!(
2580			"TrampolineOnionPacket version {} with hmac {:?}",
2581			self.version,
2582			&self.hmac[..]
2583		))
2584	}
2585}
2586
2587impl From<UpdateFailHTLC> for OnionErrorPacket {
2588	fn from(msg: UpdateFailHTLC) -> Self {
2589		OnionErrorPacket { data: msg.reason, attribution_data: msg.attribution_data }
2590	}
2591}
2592
2593impl fmt::Display for DecodeError {
2594	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2595		match *self {
2596			DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
2597			DecodeError::UnknownRequiredFeature => {
2598				f.write_str("Unknown required feature preventing decode")
2599			},
2600			DecodeError::InvalidValue => {
2601				f.write_str("Nonsense bytes didn't map to the type they were interpreted as")
2602			},
2603			DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
2604			DecodeError::BadLengthDescriptor => f.write_str(
2605				"A length descriptor in the packet didn't describe the later data correctly",
2606			),
2607			DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
2608			DecodeError::UnsupportedCompression => {
2609				f.write_str("We don't support receiving messages with zlib-compressed fields")
2610			},
2611			DecodeError::DangerousValue => {
2612				f.write_str("Value would be dangerous to continue execution with")
2613			},
2614		}
2615	}
2616}
2617
2618impl From<io::Error> for DecodeError {
2619	fn from(e: io::Error) -> Self {
2620		if e.kind() == io::ErrorKind::UnexpectedEof {
2621			DecodeError::ShortRead
2622		} else {
2623			DecodeError::Io(e.kind())
2624		}
2625	}
2626}
2627
2628impl Writeable for AcceptChannel {
2629	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2630		self.common_fields.temporary_channel_id.write(w)?;
2631		self.common_fields.dust_limit_satoshis.write(w)?;
2632		self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2633		self.channel_reserve_satoshis.write(w)?;
2634		self.common_fields.htlc_minimum_msat.write(w)?;
2635		self.common_fields.minimum_depth.write(w)?;
2636		self.common_fields.to_self_delay.write(w)?;
2637		self.common_fields.max_accepted_htlcs.write(w)?;
2638		self.common_fields.funding_pubkey.write(w)?;
2639		self.common_fields.revocation_basepoint.write(w)?;
2640		self.common_fields.payment_basepoint.write(w)?;
2641		self.common_fields.delayed_payment_basepoint.write(w)?;
2642		self.common_fields.htlc_basepoint.write(w)?;
2643		self.common_fields.first_per_commitment_point.write(w)?;
2644		#[cfg(not(taproot))]
2645		encode_tlv_stream!(w, {
2646			(0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), // Don't encode length twice.
2647			(1, self.common_fields.channel_type, option),
2648		});
2649		#[cfg(taproot)]
2650		encode_tlv_stream!(w, {
2651			(0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), // Don't encode length twice.
2652			(1, self.common_fields.channel_type, option),
2653			(4, self.next_local_nonce, option),
2654		});
2655		Ok(())
2656	}
2657}
2658
2659impl LengthReadable for AcceptChannel {
2660	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2661		let temporary_channel_id: ChannelId = Readable::read(r)?;
2662		let dust_limit_satoshis: u64 = Readable::read(r)?;
2663		let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2664		let channel_reserve_satoshis: u64 = Readable::read(r)?;
2665		let htlc_minimum_msat: u64 = Readable::read(r)?;
2666		let minimum_depth: u32 = Readable::read(r)?;
2667		let to_self_delay: u16 = Readable::read(r)?;
2668		let max_accepted_htlcs: u16 = Readable::read(r)?;
2669		let funding_pubkey: PublicKey = Readable::read(r)?;
2670		let revocation_basepoint: PublicKey = Readable::read(r)?;
2671		let payment_basepoint: PublicKey = Readable::read(r)?;
2672		let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2673		let htlc_basepoint: PublicKey = Readable::read(r)?;
2674		let first_per_commitment_point: PublicKey = Readable::read(r)?;
2675
2676		let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2677		let mut channel_type: Option<ChannelTypeFeatures> = None;
2678		#[cfg(not(taproot))]
2679		decode_tlv_stream!(r, {
2680			(0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2681			(1, channel_type, option),
2682		});
2683		#[cfg(taproot)]
2684		let mut next_local_nonce: Option<musig2::types::PublicNonce> = None;
2685		#[cfg(taproot)]
2686		decode_tlv_stream!(r, {
2687			(0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2688			(1, channel_type, option),
2689			(4, next_local_nonce, option),
2690		});
2691
2692		Ok(AcceptChannel {
2693			common_fields: CommonAcceptChannelFields {
2694				temporary_channel_id,
2695				dust_limit_satoshis,
2696				max_htlc_value_in_flight_msat,
2697				htlc_minimum_msat,
2698				minimum_depth,
2699				to_self_delay,
2700				max_accepted_htlcs,
2701				funding_pubkey,
2702				revocation_basepoint,
2703				payment_basepoint,
2704				delayed_payment_basepoint,
2705				htlc_basepoint,
2706				first_per_commitment_point,
2707				shutdown_scriptpubkey,
2708				channel_type,
2709			},
2710			channel_reserve_satoshis,
2711			#[cfg(taproot)]
2712			next_local_nonce,
2713		})
2714	}
2715}
2716
2717impl Writeable for AcceptChannelV2 {
2718	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2719		self.common_fields.temporary_channel_id.write(w)?;
2720		self.funding_satoshis.write(w)?;
2721		self.common_fields.dust_limit_satoshis.write(w)?;
2722		self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2723		self.common_fields.htlc_minimum_msat.write(w)?;
2724		self.common_fields.minimum_depth.write(w)?;
2725		self.common_fields.to_self_delay.write(w)?;
2726		self.common_fields.max_accepted_htlcs.write(w)?;
2727		self.common_fields.funding_pubkey.write(w)?;
2728		self.common_fields.revocation_basepoint.write(w)?;
2729		self.common_fields.payment_basepoint.write(w)?;
2730		self.common_fields.delayed_payment_basepoint.write(w)?;
2731		self.common_fields.htlc_basepoint.write(w)?;
2732		self.common_fields.first_per_commitment_point.write(w)?;
2733		self.second_per_commitment_point.write(w)?;
2734
2735		encode_tlv_stream!(w, {
2736			(0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), // Don't encode length twice.
2737			(1, self.common_fields.channel_type, option),
2738			(2, self.require_confirmed_inputs, option),
2739		});
2740		Ok(())
2741	}
2742}
2743
2744impl LengthReadable for AcceptChannelV2 {
2745	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2746		let temporary_channel_id: ChannelId = Readable::read(r)?;
2747		let funding_satoshis: u64 = Readable::read(r)?;
2748		let dust_limit_satoshis: u64 = Readable::read(r)?;
2749		let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2750		let htlc_minimum_msat: u64 = Readable::read(r)?;
2751		let minimum_depth: u32 = Readable::read(r)?;
2752		let to_self_delay: u16 = Readable::read(r)?;
2753		let max_accepted_htlcs: u16 = Readable::read(r)?;
2754		let funding_pubkey: PublicKey = Readable::read(r)?;
2755		let revocation_basepoint: PublicKey = Readable::read(r)?;
2756		let payment_basepoint: PublicKey = Readable::read(r)?;
2757		let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2758		let htlc_basepoint: PublicKey = Readable::read(r)?;
2759		let first_per_commitment_point: PublicKey = Readable::read(r)?;
2760		let second_per_commitment_point: PublicKey = Readable::read(r)?;
2761
2762		let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2763		let mut channel_type: Option<ChannelTypeFeatures> = None;
2764		let mut require_confirmed_inputs: Option<()> = None;
2765		decode_tlv_stream!(r, {
2766			(0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2767			(1, channel_type, option),
2768			(2, require_confirmed_inputs, option),
2769		});
2770
2771		Ok(AcceptChannelV2 {
2772			common_fields: CommonAcceptChannelFields {
2773				temporary_channel_id,
2774				dust_limit_satoshis,
2775				max_htlc_value_in_flight_msat,
2776				htlc_minimum_msat,
2777				minimum_depth,
2778				to_self_delay,
2779				max_accepted_htlcs,
2780				funding_pubkey,
2781				revocation_basepoint,
2782				payment_basepoint,
2783				delayed_payment_basepoint,
2784				htlc_basepoint,
2785				first_per_commitment_point,
2786				shutdown_scriptpubkey,
2787				channel_type,
2788			},
2789			funding_satoshis,
2790			second_per_commitment_point,
2791			require_confirmed_inputs,
2792		})
2793	}
2794}
2795
2796impl_writeable_msg!(Stfu, {
2797	channel_id,
2798	initiator,
2799}, {});
2800
2801impl_writeable_msg!(SpliceInit, {
2802	channel_id,
2803	funding_contribution_satoshis,
2804	funding_feerate_per_kw,
2805	locktime,
2806	funding_pubkey,
2807}, {
2808	(2, require_confirmed_inputs, option), // `splice_init_tlvs`
2809});
2810
2811impl_writeable_msg!(SpliceAck, {
2812	channel_id,
2813	funding_contribution_satoshis,
2814	funding_pubkey,
2815}, {
2816	(2, require_confirmed_inputs, option), // `splice_ack_tlvs`
2817});
2818
2819impl_writeable_msg!(SpliceLocked, {
2820	channel_id,
2821	splice_txid,
2822}, {});
2823
2824impl Writeable for TxAddInput {
2825	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2826		self.channel_id.write(w)?;
2827		self.serial_id.write(w)?;
2828
2829		match &self.prevtx {
2830			Some(tx) => {
2831				(tx.serialized_length() as u16).write(w)?;
2832				tx.write(w)?;
2833			},
2834			None => 0u16.write(w)?,
2835		}
2836
2837		self.prevtx_out.write(w)?;
2838		self.sequence.write(w)?;
2839
2840		encode_tlv_stream!(w, {
2841			(0, self.shared_input_txid, option),
2842		});
2843		Ok(())
2844	}
2845}
2846
2847impl LengthReadable for TxAddInput {
2848	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2849		let channel_id: ChannelId = Readable::read(r)?;
2850		let serial_id: SerialId = Readable::read(r)?;
2851
2852		let prevtx_len: u16 = Readable::read(r)?;
2853		let prevtx = if prevtx_len > 0 {
2854			let mut tx_reader = FixedLengthReader::new(r, prevtx_len as u64);
2855			let tx: Transaction = Readable::read(&mut tx_reader)?;
2856			if tx_reader.bytes_remain() {
2857				return Err(DecodeError::BadLengthDescriptor);
2858			}
2859
2860			Some(tx)
2861		} else {
2862			None
2863		};
2864
2865		let prevtx_out: u32 = Readable::read(r)?;
2866		let sequence: u32 = Readable::read(r)?;
2867
2868		let mut shared_input_txid: Option<Txid> = None;
2869		decode_tlv_stream!(r, {
2870			(0, shared_input_txid, option),
2871		});
2872
2873		Ok(TxAddInput { channel_id, serial_id, prevtx, prevtx_out, sequence, shared_input_txid })
2874	}
2875}
2876impl_writeable_msg!(TxAddOutput, {
2877	channel_id,
2878	serial_id,
2879	sats,
2880	script,
2881}, {});
2882
2883impl_writeable_msg!(TxRemoveInput, {
2884	channel_id,
2885	serial_id,
2886}, {});
2887
2888impl_writeable_msg!(TxRemoveOutput, {
2889	channel_id,
2890	serial_id,
2891}, {});
2892
2893impl_writeable_msg!(TxComplete, {
2894	channel_id,
2895}, {});
2896
2897impl_writeable_msg!(TxSignatures, {
2898	channel_id,
2899	tx_hash,
2900	witnesses,
2901}, {
2902	(0, shared_input_signature, option), // `signature`
2903});
2904
2905impl_writeable_msg!(TxInitRbf, {
2906	channel_id,
2907	locktime,
2908	feerate_sat_per_1000_weight,
2909}, {
2910	(0, funding_output_contribution, option),
2911});
2912
2913impl_writeable_msg!(TxAckRbf, {
2914	channel_id,
2915}, {
2916	(0, funding_output_contribution, option),
2917});
2918
2919impl_writeable_msg!(TxAbort, {
2920	channel_id,
2921	data,
2922}, {});
2923
2924impl_writeable_msg!(AnnouncementSignatures, {
2925	channel_id,
2926	short_channel_id,
2927	node_signature,
2928	bitcoin_signature
2929}, {});
2930
2931impl_writeable_msg!(ChannelReestablish, {
2932	channel_id,
2933	next_local_commitment_number,
2934	next_remote_commitment_number,
2935	your_last_per_commitment_secret,
2936	my_current_per_commitment_point,
2937}, {
2938	(1, next_funding, option),
2939	(5, my_current_funding_locked, option),
2940});
2941
2942impl_writeable!(NextFunding, {
2943	txid,
2944	retransmit_flags
2945});
2946
2947impl_writeable!(FundingLocked, {
2948	txid,
2949	retransmit_flags
2950});
2951
2952impl_writeable_msg!(ClosingSigned,
2953	{ channel_id, fee_satoshis, signature },
2954	{ (1, fee_range, option) }
2955);
2956
2957impl_writeable_msg!(ClosingComplete,
2958	{ channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
2959	{
2960		(1, closer_output_only, option),
2961		(2, closee_output_only, option),
2962		(3, closer_and_closee_outputs, option)
2963	}
2964);
2965
2966impl_writeable_msg!(ClosingSig,
2967	{ channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
2968	{
2969		(1, closer_output_only, option),
2970		(2, closee_output_only, option),
2971		(3, closer_and_closee_outputs, option)
2972	}
2973);
2974
2975impl_writeable!(ClosingSignedFeeRange, {
2976	min_fee_satoshis,
2977	max_fee_satoshis
2978});
2979
2980#[cfg(not(taproot))]
2981impl_writeable_msg!(CommitmentSigned, {
2982	channel_id,
2983	signature,
2984	htlc_signatures
2985}, {
2986	(1, funding_txid, option),
2987});
2988
2989#[cfg(taproot)]
2990impl_writeable_msg!(CommitmentSigned, {
2991	channel_id,
2992	signature,
2993	htlc_signatures
2994}, {
2995	(1, funding_txid, option),
2996	(2, partial_signature_with_nonce, option),
2997});
2998
2999impl_writeable!(DecodedOnionErrorPacket, {
3000	hmac,
3001	failuremsg,
3002	pad
3003});
3004
3005#[cfg(not(taproot))]
3006impl_writeable_msg!(FundingCreated, {
3007	temporary_channel_id,
3008	funding_txid,
3009	funding_output_index,
3010	signature
3011}, {});
3012#[cfg(taproot)]
3013impl_writeable_msg!(FundingCreated, {
3014	temporary_channel_id,
3015	funding_txid,
3016	funding_output_index,
3017	signature
3018}, {
3019	(2, partial_signature_with_nonce, option),
3020	(4, next_local_nonce, option)
3021});
3022
3023#[cfg(not(taproot))]
3024impl_writeable_msg!(FundingSigned, {
3025	channel_id,
3026	signature
3027}, {});
3028
3029#[cfg(taproot)]
3030impl_writeable_msg!(FundingSigned, {
3031	channel_id,
3032	signature
3033}, {
3034	(2, partial_signature_with_nonce, option)
3035});
3036
3037impl_writeable_msg!(ChannelReady, {
3038	channel_id,
3039	next_per_commitment_point,
3040}, {
3041	(1, short_channel_id_alias, option),
3042});
3043
3044pub(crate) fn write_features_up_to_13<W: Writer>(
3045	w: &mut W, le_flags: &[u8],
3046) -> Result<(), io::Error> {
3047	let len = core::cmp::min(2, le_flags.len());
3048	(len as u16).write(w)?;
3049	for i in (0..len).rev() {
3050		if i == 0 {
3051			le_flags[i].write(w)?;
3052		} else {
3053			// On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
3054			// up-to-and-including-bit-5, 0-indexed, on this byte:
3055			(le_flags[i] & 0b00_11_11_11).write(w)?;
3056		}
3057	}
3058	Ok(())
3059}
3060
3061impl Writeable for Init {
3062	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3063		// global_features gets the bottom 13 bits of our features, and local_features gets all of
3064		// our relevant feature bits. This keeps us compatible with old nodes.
3065		write_features_up_to_13(w, self.features.le_flags())?;
3066		self.features.write(w)?;
3067		encode_tlv_stream!(w, {
3068			(1, self.networks.as_ref().map(|n| WithoutLength(n)), option),
3069			(3, self.remote_network_address, option),
3070		});
3071		Ok(())
3072	}
3073}
3074
3075impl LengthReadable for Init {
3076	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3077		let global_features: InitFeatures = Readable::read(r)?;
3078		let features: InitFeatures = Readable::read(r)?;
3079		let mut remote_network_address: Option<SocketAddress> = None;
3080		let mut networks: Option<WithoutLength<Vec<ChainHash>>> = None;
3081		decode_tlv_stream!(r, {
3082			(1, networks, option),
3083			(3, remote_network_address, option)
3084		});
3085		Ok(Init {
3086			features: features | global_features,
3087			networks: networks.map(|n| n.0),
3088			remote_network_address,
3089		})
3090	}
3091}
3092
3093impl Writeable for OpenChannel {
3094	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3095		self.common_fields.chain_hash.write(w)?;
3096		self.common_fields.temporary_channel_id.write(w)?;
3097		self.common_fields.funding_satoshis.write(w)?;
3098		self.push_msat.write(w)?;
3099		self.common_fields.dust_limit_satoshis.write(w)?;
3100		self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3101		self.channel_reserve_satoshis.write(w)?;
3102		self.common_fields.htlc_minimum_msat.write(w)?;
3103		self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3104		self.common_fields.to_self_delay.write(w)?;
3105		self.common_fields.max_accepted_htlcs.write(w)?;
3106		self.common_fields.funding_pubkey.write(w)?;
3107		self.common_fields.revocation_basepoint.write(w)?;
3108		self.common_fields.payment_basepoint.write(w)?;
3109		self.common_fields.delayed_payment_basepoint.write(w)?;
3110		self.common_fields.htlc_basepoint.write(w)?;
3111		self.common_fields.first_per_commitment_point.write(w)?;
3112		self.common_fields.channel_flags.write(w)?;
3113		encode_tlv_stream!(w, {
3114			(0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), // Don't encode length twice.
3115			(1, self.common_fields.channel_type, option),
3116		});
3117		Ok(())
3118	}
3119}
3120
3121impl LengthReadable for OpenChannel {
3122	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3123		let chain_hash: ChainHash = Readable::read(r)?;
3124		let temporary_channel_id: ChannelId = Readable::read(r)?;
3125		let funding_satoshis: u64 = Readable::read(r)?;
3126		let push_msat: u64 = Readable::read(r)?;
3127		let dust_limit_satoshis: u64 = Readable::read(r)?;
3128		let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3129		let channel_reserve_satoshis: u64 = Readable::read(r)?;
3130		let htlc_minimum_msat: u64 = Readable::read(r)?;
3131		let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3132		let to_self_delay: u16 = Readable::read(r)?;
3133		let max_accepted_htlcs: u16 = Readable::read(r)?;
3134		let funding_pubkey: PublicKey = Readable::read(r)?;
3135		let revocation_basepoint: PublicKey = Readable::read(r)?;
3136		let payment_basepoint: PublicKey = Readable::read(r)?;
3137		let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3138		let htlc_basepoint: PublicKey = Readable::read(r)?;
3139		let first_per_commitment_point: PublicKey = Readable::read(r)?;
3140		let channel_flags: u8 = Readable::read(r)?;
3141
3142		let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3143		let mut channel_type: Option<ChannelTypeFeatures> = None;
3144		decode_tlv_stream!(r, {
3145			(0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3146			(1, channel_type, option),
3147		});
3148		Ok(OpenChannel {
3149			common_fields: CommonOpenChannelFields {
3150				chain_hash,
3151				temporary_channel_id,
3152				funding_satoshis,
3153				dust_limit_satoshis,
3154				max_htlc_value_in_flight_msat,
3155				htlc_minimum_msat,
3156				commitment_feerate_sat_per_1000_weight,
3157				to_self_delay,
3158				max_accepted_htlcs,
3159				funding_pubkey,
3160				revocation_basepoint,
3161				payment_basepoint,
3162				delayed_payment_basepoint,
3163				htlc_basepoint,
3164				first_per_commitment_point,
3165				channel_flags,
3166				shutdown_scriptpubkey,
3167				channel_type,
3168			},
3169			push_msat,
3170			channel_reserve_satoshis,
3171		})
3172	}
3173}
3174
3175impl Writeable for OpenChannelV2 {
3176	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3177		self.common_fields.chain_hash.write(w)?;
3178		self.common_fields.temporary_channel_id.write(w)?;
3179		self.funding_feerate_sat_per_1000_weight.write(w)?;
3180		self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3181		self.common_fields.funding_satoshis.write(w)?;
3182		self.common_fields.dust_limit_satoshis.write(w)?;
3183		self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3184		self.common_fields.htlc_minimum_msat.write(w)?;
3185		self.common_fields.to_self_delay.write(w)?;
3186		self.common_fields.max_accepted_htlcs.write(w)?;
3187		self.locktime.write(w)?;
3188		self.common_fields.funding_pubkey.write(w)?;
3189		self.common_fields.revocation_basepoint.write(w)?;
3190		self.common_fields.payment_basepoint.write(w)?;
3191		self.common_fields.delayed_payment_basepoint.write(w)?;
3192		self.common_fields.htlc_basepoint.write(w)?;
3193		self.common_fields.first_per_commitment_point.write(w)?;
3194		self.second_per_commitment_point.write(w)?;
3195		self.common_fields.channel_flags.write(w)?;
3196		encode_tlv_stream!(w, {
3197			(0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), // Don't encode length twice.
3198			(1, self.common_fields.channel_type, option),
3199			(2, self.require_confirmed_inputs, option),
3200		});
3201		Ok(())
3202	}
3203}
3204
3205impl LengthReadable for OpenChannelV2 {
3206	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3207		let chain_hash: ChainHash = Readable::read(r)?;
3208		let temporary_channel_id: ChannelId = Readable::read(r)?;
3209		let funding_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3210		let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3211		let funding_satoshis: u64 = Readable::read(r)?;
3212		let dust_limit_satoshis: u64 = Readable::read(r)?;
3213		let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3214		let htlc_minimum_msat: u64 = Readable::read(r)?;
3215		let to_self_delay: u16 = Readable::read(r)?;
3216		let max_accepted_htlcs: u16 = Readable::read(r)?;
3217		let locktime: u32 = Readable::read(r)?;
3218		let funding_pubkey: PublicKey = Readable::read(r)?;
3219		let revocation_basepoint: PublicKey = Readable::read(r)?;
3220		let payment_basepoint: PublicKey = Readable::read(r)?;
3221		let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3222		let htlc_basepoint: PublicKey = Readable::read(r)?;
3223		let first_per_commitment_point: PublicKey = Readable::read(r)?;
3224		let second_per_commitment_point: PublicKey = Readable::read(r)?;
3225		let channel_flags: u8 = Readable::read(r)?;
3226
3227		let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3228		let mut channel_type: Option<ChannelTypeFeatures> = None;
3229		let mut require_confirmed_inputs: Option<()> = None;
3230		decode_tlv_stream!(r, {
3231			(0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3232			(1, channel_type, option),
3233			(2, require_confirmed_inputs, option),
3234		});
3235		Ok(OpenChannelV2 {
3236			common_fields: CommonOpenChannelFields {
3237				chain_hash,
3238				temporary_channel_id,
3239				funding_satoshis,
3240				dust_limit_satoshis,
3241				max_htlc_value_in_flight_msat,
3242				htlc_minimum_msat,
3243				commitment_feerate_sat_per_1000_weight,
3244				to_self_delay,
3245				max_accepted_htlcs,
3246				funding_pubkey,
3247				revocation_basepoint,
3248				payment_basepoint,
3249				delayed_payment_basepoint,
3250				htlc_basepoint,
3251				first_per_commitment_point,
3252				channel_flags,
3253				shutdown_scriptpubkey,
3254				channel_type,
3255			},
3256			funding_feerate_sat_per_1000_weight,
3257			locktime,
3258			second_per_commitment_point,
3259			require_confirmed_inputs,
3260		})
3261	}
3262}
3263
3264#[cfg(not(taproot))]
3265impl_writeable_msg!(RevokeAndACK, {
3266	channel_id,
3267	per_commitment_secret,
3268	next_per_commitment_point
3269}, {
3270	(75537, release_htlc_message_paths, optional_vec)
3271});
3272
3273#[cfg(taproot)]
3274impl_writeable_msg!(RevokeAndACK, {
3275	channel_id,
3276	per_commitment_secret,
3277	next_per_commitment_point
3278}, {
3279	(4, next_local_nonce, option),
3280	(75537, release_htlc_message_paths, optional_vec)
3281});
3282
3283impl_writeable_msg!(Shutdown, {
3284	channel_id,
3285	scriptpubkey
3286}, {});
3287
3288impl_writeable_msg!(UpdateFailHTLC, {
3289	channel_id,
3290	htlc_id,
3291	reason
3292}, {
3293	(1, attribution_data, option)
3294});
3295
3296impl_writeable_msg!(UpdateFailMalformedHTLC, {
3297	channel_id,
3298	htlc_id,
3299	sha256_of_onion,
3300	failure_code
3301}, {});
3302
3303impl_writeable_msg!(UpdateFee, {
3304	channel_id,
3305	feerate_per_kw
3306}, {});
3307
3308impl_writeable_msg!(UpdateFulfillHTLC, {
3309	channel_id,
3310	htlc_id,
3311	payment_preimage
3312}, {
3313	(1, attribution_data, option)
3314});
3315
3316impl_writeable_msg!(PeerStorage, { data }, {});
3317
3318impl_writeable_msg!(PeerStorageRetrieval, { data }, {});
3319
3320impl_writeable_msg!(StartBatch, {
3321	channel_id,
3322	batch_size
3323}, {
3324	(1, message_type, option)
3325});
3326
3327// Note that this is written as a part of ChannelManager objects, and thus cannot change its
3328// serialization format in a way which assumes we know the total serialized length/message end
3329// position.
3330impl Writeable for OnionPacket {
3331	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3332		self.version.write(w)?;
3333		match self.public_key {
3334			Ok(pubkey) => pubkey.write(w)?,
3335			Err(_) => [0u8; 33].write(w)?,
3336		}
3337		w.write_all(&self.hop_data)?;
3338		self.hmac.write(w)?;
3339		Ok(())
3340	}
3341}
3342
3343impl Readable for OnionPacket {
3344	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3345		Ok(OnionPacket {
3346			version: Readable::read(r)?,
3347			public_key: {
3348				let mut buf = [0u8; 33];
3349				r.read_exact(&mut buf)?;
3350				PublicKey::from_slice(&buf)
3351			},
3352			hop_data: Readable::read(r)?,
3353			hmac: Readable::read(r)?,
3354		})
3355	}
3356}
3357
3358impl_writeable_msg!(UpdateAddHTLC, {
3359	channel_id,
3360	htlc_id,
3361	amount_msat,
3362	payment_hash,
3363	cltv_expiry,
3364	onion_routing_packet,
3365}, {
3366	(0, blinding_point, option),
3367	(65537, skimmed_fee_msat, option),
3368	// TODO: currently we may fail to read the `ChannelManager` if we write a new even TLV in this message
3369	// and then downgrade. Once this is fixed, update the type here to match BOLTs PR 989.
3370	(75537, hold_htlc, option),
3371});
3372
3373impl LengthReadable for OnionMessage {
3374	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3375		let blinding_point: PublicKey = Readable::read(r)?;
3376		let len: u16 = Readable::read(r)?;
3377		let mut packet_reader = FixedLengthReader::new(r, len as u64);
3378		let onion_routing_packet: onion_message::packet::Packet =
3379			<onion_message::packet::Packet as LengthReadable>::read_from_fixed_length_buffer(
3380				&mut packet_reader,
3381			)?;
3382		Ok(Self { blinding_point, onion_routing_packet })
3383	}
3384}
3385
3386impl Writeable for OnionMessage {
3387	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3388		self.blinding_point.write(w)?;
3389		let onion_packet_len = self.onion_routing_packet.serialized_length();
3390		(onion_packet_len as u16).write(w)?;
3391		self.onion_routing_packet.write(w)?;
3392		Ok(())
3393	}
3394}
3395
3396impl Writeable for FinalOnionHopData {
3397	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3398		self.payment_secret.0.write(w)?;
3399		HighZeroBytesDroppedBigSize(self.total_msat).write(w)
3400	}
3401}
3402
3403impl Readable for FinalOnionHopData {
3404	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3405		let secret: [u8; 32] = Readable::read(r)?;
3406		let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
3407		Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
3408	}
3409}
3410
3411impl<'a> Writeable for OutboundOnionPayload<'a> {
3412	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3413		match self {
3414			Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } => {
3415				_encode_varint_length_prefixed_tlv!(w, {
3416					(2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3417					(4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3418					(6, short_channel_id, required)
3419				});
3420			},
3421			Self::TrampolineEntrypoint {
3422				amt_to_forward,
3423				outgoing_cltv_value,
3424				ref multipath_trampoline_data,
3425				ref trampoline_packet,
3426			} => {
3427				_encode_varint_length_prefixed_tlv!(w, {
3428					(2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3429					(4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3430					(8, multipath_trampoline_data, option),
3431					(20, trampoline_packet, required)
3432				});
3433			},
3434			Self::BlindedTrampolineEntrypoint {
3435				amt_to_forward,
3436				outgoing_cltv_value,
3437				current_path_key,
3438				ref multipath_trampoline_data,
3439				ref trampoline_packet,
3440			} => {
3441				_encode_varint_length_prefixed_tlv!(w, {
3442					(2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3443					(4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3444					(8, multipath_trampoline_data, option),
3445					(12, current_path_key, required),
3446					(20, trampoline_packet, required)
3447				});
3448			},
3449			Self::Receive {
3450				ref payment_data,
3451				ref payment_metadata,
3452				ref keysend_preimage,
3453				sender_intended_htlc_amt_msat,
3454				cltv_expiry_height,
3455				ref custom_tlvs,
3456			} => {
3457				// We need to update [`ln::outbound_payment::RecipientOnionFields::with_custom_tlvs`]
3458				// to reject any reserved types in the experimental range if new ones are ever
3459				// standardized.
3460				let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3461				let mut custom_tlvs: Vec<&(u64, Vec<u8>)> =
3462					custom_tlvs.iter().chain(keysend_tlv.iter()).collect();
3463				custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3464				_encode_varint_length_prefixed_tlv!(w, {
3465					(2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3466					(4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3467					(8, payment_data, option),
3468					(16, payment_metadata.map(|m| WithoutLength(m)), option)
3469				}, custom_tlvs.iter());
3470			},
3471			Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3472				_encode_varint_length_prefixed_tlv!(w, {
3473					(10, *encrypted_tlvs, required_vec),
3474					(12, intro_node_blinding_point, option)
3475				});
3476			},
3477			Self::BlindedReceive {
3478				sender_intended_htlc_amt_msat,
3479				total_msat,
3480				cltv_expiry_height,
3481				encrypted_tlvs,
3482				intro_node_blinding_point,
3483				keysend_preimage,
3484				ref invoice_request,
3485				ref custom_tlvs,
3486			} => {
3487				// We need to update [`ln::outbound_payment::RecipientOnionFields::with_custom_tlvs`]
3488				// to reject any reserved types in the experimental range if new ones are ever
3489				// standardized.
3490				let invoice_request_tlv = invoice_request.map(|invreq| (77_777, invreq.encode())); // TODO: update TLV type once the async payments spec is merged
3491				let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3492				let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs
3493					.iter()
3494					.chain(invoice_request_tlv.iter())
3495					.chain(keysend_tlv.iter())
3496					.collect();
3497				custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3498				_encode_varint_length_prefixed_tlv!(w, {
3499					(2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3500					(4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3501					(10, *encrypted_tlvs, required_vec),
3502					(12, intro_node_blinding_point, option),
3503					(18, HighZeroBytesDroppedBigSize(*total_msat), required)
3504				}, custom_tlvs.iter());
3505			},
3506		}
3507		Ok(())
3508	}
3509}
3510
3511impl<'a> Writeable for OutboundTrampolinePayload<'a> {
3512	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3513		match self {
3514			Self::Forward { amt_to_forward, outgoing_cltv_value, outgoing_node_id } => {
3515				_encode_varint_length_prefixed_tlv!(w, {
3516					(2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3517					(4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3518					(14, outgoing_node_id, required)
3519				});
3520			},
3521			#[cfg(test)]
3522			Self::Receive {
3523				ref payment_data,
3524				sender_intended_htlc_amt_msat,
3525				cltv_expiry_height,
3526			} => {
3527				_encode_varint_length_prefixed_tlv!(w, {
3528					(2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3529					(4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3530					(8, payment_data, option)
3531				});
3532			},
3533			Self::LegacyBlindedPathEntry {
3534				amt_to_forward,
3535				outgoing_cltv_value,
3536				payment_paths,
3537				invoice_features,
3538			} => {
3539				let mut blinded_path_serialization = [0u8; 2048]; // Fixed-length buffer on the stack
3540				let serialization_length = {
3541					let buffer_size = blinded_path_serialization.len();
3542					let mut blinded_path_slice = &mut blinded_path_serialization[..];
3543					for current_payment_path in payment_paths {
3544						current_payment_path.inner_blinded_path().write(&mut blinded_path_slice)?;
3545						current_payment_path.payinfo.write(&mut blinded_path_slice)?;
3546					}
3547					buffer_size - blinded_path_slice.len()
3548				};
3549				let blinded_path_serialization =
3550					&blinded_path_serialization[..serialization_length];
3551				_encode_varint_length_prefixed_tlv!(w, {
3552					(2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3553					(4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3554					(21, invoice_features.as_ref().map(|m| WithoutLength(m)), option),
3555					(22, WithoutLength(blinded_path_serialization), required)
3556				});
3557			},
3558			Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3559				_encode_varint_length_prefixed_tlv!(w, {
3560					(10, *encrypted_tlvs, required_vec),
3561					(12, intro_node_blinding_point, option)
3562				});
3563			},
3564			Self::BlindedReceive {
3565				sender_intended_htlc_amt_msat,
3566				total_msat,
3567				cltv_expiry_height,
3568				encrypted_tlvs,
3569				intro_node_blinding_point,
3570				keysend_preimage,
3571				custom_tlvs,
3572			} => {
3573				_encode_varint_length_prefixed_tlv!(w, {
3574					(2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3575					(4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3576					(10, *encrypted_tlvs, required_vec),
3577					(12, intro_node_blinding_point, option),
3578					(18, HighZeroBytesDroppedBigSize(*total_msat), required),
3579					(20, keysend_preimage, option)
3580				}, custom_tlvs.iter());
3581			},
3582		}
3583		Ok(())
3584	}
3585}
3586
3587impl<NS: Deref> ReadableArgs<(Option<PublicKey>, NS)> for InboundOnionPayload
3588where
3589	NS::Target: NodeSigner,
3590{
3591	fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3592		let (update_add_blinding_point, node_signer) = args;
3593
3594		let mut amt = None;
3595		let mut cltv_value = None;
3596		let mut short_id: Option<u64> = None;
3597		let mut payment_data: Option<FinalOnionHopData> = None;
3598		let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3599		let mut intro_node_blinding_point = None;
3600		let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3601		let mut total_msat = None;
3602		let mut keysend_preimage: Option<PaymentPreimage> = None;
3603		let mut trampoline_onion_packet: Option<TrampolineOnionPacket> = None;
3604		let mut invoice_request: Option<InvoiceRequest> = None;
3605		let mut custom_tlvs = Vec::new();
3606
3607		let tlv_len = BigSize::read(r)?;
3608		let mut rd = FixedLengthReader::new(r, tlv_len.0);
3609
3610		decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3611			(2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3612			(4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3613			(6, short_id, option),
3614			(8, payment_data, option),
3615			(10, encrypted_tlvs_opt, option),
3616			(12, intro_node_blinding_point, option),
3617			(16, payment_metadata, option),
3618			(18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3619			(20, trampoline_onion_packet, option),
3620			(77_777, invoice_request, option),
3621			// See https://github.com/lightning/blips/blob/master/blip-0003.md
3622			(5482373484, keysend_preimage, option)
3623		}, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
3624			if msg_type < 1 << 16 { return Ok(false) }
3625			let mut value = Vec::new();
3626			msg_reader.read_to_limit(&mut value, u64::MAX)?;
3627			custom_tlvs.push((msg_type, value));
3628			Ok(true)
3629		});
3630
3631		if amt.unwrap_or(0) > MAX_VALUE_MSAT {
3632			return Err(DecodeError::InvalidValue);
3633		}
3634		if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
3635			return Err(DecodeError::InvalidValue);
3636		}
3637
3638		if let Some(trampoline_onion_packet) = trampoline_onion_packet {
3639			if payment_metadata.is_some() || encrypted_tlvs_opt.is_some() || total_msat.is_some() {
3640				return Err(DecodeError::InvalidValue);
3641			}
3642			return Ok(Self::TrampolineEntrypoint(InboundTrampolineEntrypointPayload {
3643				amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3644				outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3645				multipath_trampoline_data: payment_data,
3646				trampoline_packet: trampoline_onion_packet,
3647				current_path_key: intro_node_blinding_point,
3648			}));
3649		}
3650
3651		if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
3652			if short_id.is_some() || payment_data.is_some() || payment_metadata.is_some() {
3653				return Err(DecodeError::InvalidValue);
3654			}
3655			let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
3656			let enc_tlvs_ss = node_signer
3657				.ecdh(Recipient::Node, &blinding_point, None)
3658				.map_err(|_| DecodeError::InvalidValue)?;
3659			let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
3660			let mut s = Cursor::new(&enc_tlvs);
3661			let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
3662			match ChaChaPolyReadAdapter::read(&mut reader, rho)? {
3663				ChaChaPolyReadAdapter {
3664					readable:
3665						BlindedPaymentTlvs::Forward(ForwardTlvs {
3666							short_channel_id,
3667							payment_relay,
3668							payment_constraints,
3669							features,
3670							next_blinding_override,
3671						}),
3672				} => {
3673					if amt.is_some()
3674						|| cltv_value.is_some() || total_msat.is_some()
3675						|| keysend_preimage.is_some()
3676						|| invoice_request.is_some()
3677					{
3678						return Err(DecodeError::InvalidValue);
3679					}
3680					Ok(Self::BlindedForward(InboundOnionBlindedForwardPayload {
3681						short_channel_id,
3682						payment_relay,
3683						payment_constraints,
3684						features,
3685						intro_node_blinding_point,
3686						next_blinding_override,
3687					}))
3688				},
3689				ChaChaPolyReadAdapter { readable: BlindedPaymentTlvs::Receive(receive_tlvs) } => {
3690					let ReceiveTlvs { tlvs, authentication: (hmac, nonce) } = receive_tlvs;
3691					let expanded_key = node_signer.get_expanded_key();
3692					if tlvs.verify_for_offer_payment(hmac, nonce, &expanded_key).is_err() {
3693						return Err(DecodeError::InvalidValue);
3694					}
3695
3696					let UnauthenticatedReceiveTlvs {
3697						payment_secret,
3698						payment_constraints,
3699						payment_context,
3700					} = tlvs;
3701					if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
3702						return Err(DecodeError::InvalidValue);
3703					}
3704					Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
3705						sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3706						total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
3707						cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3708						payment_secret,
3709						payment_constraints,
3710						payment_context,
3711						intro_node_blinding_point,
3712						keysend_preimage,
3713						invoice_request,
3714						custom_tlvs,
3715					}))
3716				},
3717			}
3718		} else if let Some(short_channel_id) = short_id {
3719			if payment_data.is_some()
3720				|| payment_metadata.is_some()
3721				|| encrypted_tlvs_opt.is_some()
3722				|| total_msat.is_some()
3723				|| invoice_request.is_some()
3724			{
3725				return Err(DecodeError::InvalidValue);
3726			}
3727			Ok(Self::Forward(InboundOnionForwardPayload {
3728				short_channel_id,
3729				amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3730				outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3731			}))
3732		} else {
3733			if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
3734				return Err(DecodeError::InvalidValue);
3735			}
3736			if let Some(data) = &payment_data {
3737				if data.total_msat > MAX_VALUE_MSAT {
3738					return Err(DecodeError::InvalidValue);
3739				}
3740			}
3741			Ok(Self::Receive(InboundOnionReceivePayload {
3742				payment_data,
3743				payment_metadata: payment_metadata.map(|w| w.0),
3744				keysend_preimage,
3745				sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3746				cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3747				custom_tlvs,
3748			}))
3749		}
3750	}
3751}
3752
3753impl<NS: Deref> ReadableArgs<(Option<PublicKey>, NS)> for InboundTrampolinePayload
3754where
3755	NS::Target: NodeSigner,
3756{
3757	fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3758		let (update_add_blinding_point, node_signer) = args;
3759
3760		let mut amt = None;
3761		let mut cltv_value = None;
3762		let mut payment_data: Option<FinalOnionHopData> = None;
3763		let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3764		let mut intro_node_blinding_point = None;
3765		let mut next_trampoline: Option<PublicKey> = None;
3766		let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3767		let mut total_msat = None;
3768		let mut keysend_preimage: Option<PaymentPreimage> = None;
3769		let mut invoice_request: Option<InvoiceRequest> = None;
3770		let mut custom_tlvs = Vec::new();
3771
3772		let tlv_len = BigSize::read(r)?;
3773		let mut rd = FixedLengthReader::new(r, tlv_len.0);
3774		decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3775			(2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3776			(4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3777			(8, payment_data, option),
3778			(10, encrypted_tlvs_opt, option),
3779			(12, intro_node_blinding_point, option),
3780			(14, next_trampoline, option),
3781			(16, payment_metadata, option),
3782			(18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3783			(77_777, invoice_request, option),
3784			// See https://github.com/lightning/blips/blob/master/blip-0003.md
3785			(5482373484, keysend_preimage, option)
3786		}, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
3787			if msg_type < 1 << 16 { return Ok(false) }
3788			let mut value = Vec::new();
3789			msg_reader.read_to_limit(&mut value, u64::MAX)?;
3790			custom_tlvs.push((msg_type, value));
3791			Ok(true)
3792		});
3793
3794		if amt.unwrap_or(0) > MAX_VALUE_MSAT {
3795			return Err(DecodeError::InvalidValue);
3796		}
3797		if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
3798			return Err(DecodeError::InvalidValue);
3799		}
3800
3801		if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
3802			if next_trampoline.is_some() || payment_data.is_some() || payment_metadata.is_some() {
3803				return Err(DecodeError::InvalidValue);
3804			}
3805			let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
3806			let enc_tlvs_ss = node_signer
3807				.ecdh(Recipient::Node, &blinding_point, None)
3808				.map_err(|_| DecodeError::InvalidValue)?;
3809			let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
3810			let mut s = Cursor::new(&enc_tlvs);
3811			let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
3812			match ChaChaPolyReadAdapter::read(&mut reader, rho)? {
3813				ChaChaPolyReadAdapter {
3814					readable:
3815						BlindedTrampolineTlvs::Forward(TrampolineForwardTlvs {
3816							next_trampoline,
3817							payment_relay,
3818							payment_constraints,
3819							features,
3820							next_blinding_override,
3821						}),
3822				} => {
3823					if amt.is_some()
3824						|| cltv_value.is_some() || total_msat.is_some()
3825						|| keysend_preimage.is_some()
3826						|| invoice_request.is_some()
3827					{
3828						return Err(DecodeError::InvalidValue);
3829					}
3830					Ok(Self::BlindedForward(InboundTrampolineBlindedForwardPayload {
3831						next_trampoline,
3832						payment_relay,
3833						payment_constraints,
3834						features,
3835						intro_node_blinding_point,
3836						next_blinding_override,
3837					}))
3838				},
3839				ChaChaPolyReadAdapter {
3840					readable: BlindedTrampolineTlvs::Receive(receive_tlvs),
3841				} => {
3842					let ReceiveTlvs { tlvs, authentication: (hmac, nonce) } = receive_tlvs;
3843					let expanded_key = node_signer.get_expanded_key();
3844					if tlvs.verify_for_offer_payment(hmac, nonce, &expanded_key).is_err() {
3845						return Err(DecodeError::InvalidValue);
3846					}
3847
3848					let UnauthenticatedReceiveTlvs {
3849						payment_secret,
3850						payment_constraints,
3851						payment_context,
3852					} = tlvs;
3853					if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
3854						return Err(DecodeError::InvalidValue);
3855					}
3856					Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
3857						sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3858						total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
3859						cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3860						payment_secret,
3861						payment_constraints,
3862						payment_context,
3863						intro_node_blinding_point,
3864						keysend_preimage,
3865						invoice_request,
3866						custom_tlvs,
3867					}))
3868				},
3869			}
3870		} else if let Some(next_trampoline) = next_trampoline {
3871			if payment_data.is_some()
3872				|| payment_metadata.is_some()
3873				|| encrypted_tlvs_opt.is_some()
3874				|| total_msat.is_some()
3875				|| invoice_request.is_some()
3876			{
3877				return Err(DecodeError::InvalidValue);
3878			}
3879			Ok(Self::Forward(InboundTrampolineForwardPayload {
3880				next_trampoline,
3881				amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3882				outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3883			}))
3884		} else {
3885			if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
3886				return Err(DecodeError::InvalidValue);
3887			}
3888			if let Some(data) = &payment_data {
3889				if data.total_msat > MAX_VALUE_MSAT {
3890					return Err(DecodeError::InvalidValue);
3891				}
3892			}
3893			Ok(Self::Receive(InboundOnionReceivePayload {
3894				payment_data,
3895				payment_metadata: payment_metadata.map(|w| w.0),
3896				keysend_preimage,
3897				sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3898				cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3899				custom_tlvs,
3900			}))
3901		}
3902	}
3903}
3904
3905impl Writeable for Ping {
3906	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3907		self.ponglen.write(w)?;
3908		vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
3909		Ok(())
3910	}
3911}
3912
3913impl LengthReadable for Ping {
3914	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3915		Ok(Ping {
3916			ponglen: Readable::read(r)?,
3917			byteslen: {
3918				let byteslen = Readable::read(r)?;
3919				r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
3920				byteslen
3921			},
3922		})
3923	}
3924}
3925
3926impl Writeable for Pong {
3927	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3928		vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
3929		Ok(())
3930	}
3931}
3932
3933impl LengthReadable for Pong {
3934	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3935		Ok(Pong {
3936			byteslen: {
3937				let byteslen = Readable::read(r)?;
3938				r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
3939				byteslen
3940			},
3941		})
3942	}
3943}
3944
3945impl Writeable for UnsignedChannelAnnouncement {
3946	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3947		self.features.write(w)?;
3948		self.chain_hash.write(w)?;
3949		self.short_channel_id.write(w)?;
3950		self.node_id_1.write(w)?;
3951		self.node_id_2.write(w)?;
3952		self.bitcoin_key_1.write(w)?;
3953		self.bitcoin_key_2.write(w)?;
3954		w.write_all(&self.excess_data[..])?;
3955		Ok(())
3956	}
3957}
3958
3959impl LengthReadable for UnsignedChannelAnnouncement {
3960	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3961		Ok(Self {
3962			features: Readable::read(r)?,
3963			chain_hash: Readable::read(r)?,
3964			short_channel_id: Readable::read(r)?,
3965			node_id_1: Readable::read(r)?,
3966			node_id_2: Readable::read(r)?,
3967			bitcoin_key_1: Readable::read(r)?,
3968			bitcoin_key_2: Readable::read(r)?,
3969			excess_data: read_to_end(r)?,
3970		})
3971	}
3972}
3973
3974impl Writeable for ChannelAnnouncement {
3975	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3976		self.node_signature_1.write(w)?;
3977		self.node_signature_2.write(w)?;
3978		self.bitcoin_signature_1.write(w)?;
3979		self.bitcoin_signature_2.write(w)?;
3980		self.contents.write(w)?;
3981		Ok(())
3982	}
3983}
3984
3985impl LengthReadable for ChannelAnnouncement {
3986	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3987		Ok(Self {
3988			node_signature_1: Readable::read(r)?,
3989			node_signature_2: Readable::read(r)?,
3990			bitcoin_signature_1: Readable::read(r)?,
3991			bitcoin_signature_2: Readable::read(r)?,
3992			contents: LengthReadable::read_from_fixed_length_buffer(r)?,
3993		})
3994	}
3995}
3996
3997impl Writeable for UnsignedChannelUpdate {
3998	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3999		self.chain_hash.write(w)?;
4000		self.short_channel_id.write(w)?;
4001		self.timestamp.write(w)?;
4002		// The low bit of message_flags used to indicate the presence of `htlc_maximum_msat`, and
4003		// now must be set
4004		(self.message_flags | 1).write(w)?;
4005		self.channel_flags.write(w)?;
4006		self.cltv_expiry_delta.write(w)?;
4007		self.htlc_minimum_msat.write(w)?;
4008		self.fee_base_msat.write(w)?;
4009		self.fee_proportional_millionths.write(w)?;
4010		self.htlc_maximum_msat.write(w)?;
4011		w.write_all(&self.excess_data[..])?;
4012		Ok(())
4013	}
4014}
4015
4016impl LengthReadable for UnsignedChannelUpdate {
4017	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4018		let res = Self {
4019			chain_hash: Readable::read(r)?,
4020			short_channel_id: Readable::read(r)?,
4021			timestamp: Readable::read(r)?,
4022			message_flags: Readable::read(r)?,
4023			channel_flags: Readable::read(r)?,
4024			cltv_expiry_delta: Readable::read(r)?,
4025			htlc_minimum_msat: Readable::read(r)?,
4026			fee_base_msat: Readable::read(r)?,
4027			fee_proportional_millionths: Readable::read(r)?,
4028			htlc_maximum_msat: Readable::read(r)?,
4029			excess_data: read_to_end(r)?,
4030		};
4031		if res.message_flags & 1 != 1 {
4032			// The `must_be_one` flag should be set (historically it indicated the presence of the
4033			// `htlc_maximum_msat` field, which is now required).
4034			Err(DecodeError::InvalidValue)
4035		} else {
4036			Ok(res)
4037		}
4038	}
4039}
4040
4041impl Writeable for ChannelUpdate {
4042	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4043		self.signature.write(w)?;
4044		self.contents.write(w)?;
4045		Ok(())
4046	}
4047}
4048
4049impl LengthReadable for ChannelUpdate {
4050	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4051		Ok(Self {
4052			signature: Readable::read(r)?,
4053			contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4054		})
4055	}
4056}
4057
4058impl Writeable for ErrorMessage {
4059	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4060		self.channel_id.write(w)?;
4061		(self.data.len() as u16).write(w)?;
4062		w.write_all(self.data.as_bytes())?;
4063		Ok(())
4064	}
4065}
4066
4067impl LengthReadable for ErrorMessage {
4068	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4069		Ok(Self {
4070			channel_id: Readable::read(r)?,
4071			data: {
4072				let sz: usize = <u16 as Readable>::read(r)? as usize;
4073				let mut data = Vec::with_capacity(sz);
4074				data.resize(sz, 0);
4075				r.read_exact(&mut data)?;
4076				match String::from_utf8(data) {
4077					Ok(s) => s,
4078					Err(_) => return Err(DecodeError::InvalidValue),
4079				}
4080			},
4081		})
4082	}
4083}
4084
4085impl Writeable for WarningMessage {
4086	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4087		self.channel_id.write(w)?;
4088		(self.data.len() as u16).write(w)?;
4089		w.write_all(self.data.as_bytes())?;
4090		Ok(())
4091	}
4092}
4093
4094impl LengthReadable for WarningMessage {
4095	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4096		Ok(Self {
4097			channel_id: Readable::read(r)?,
4098			data: {
4099				let sz: usize = <u16 as Readable>::read(r)? as usize;
4100				let mut data = Vec::with_capacity(sz);
4101				data.resize(sz, 0);
4102				r.read_exact(&mut data)?;
4103				match String::from_utf8(data) {
4104					Ok(s) => s,
4105					Err(_) => return Err(DecodeError::InvalidValue),
4106				}
4107			},
4108		})
4109	}
4110}
4111
4112impl Writeable for UnsignedNodeAnnouncement {
4113	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4114		self.features.write(w)?;
4115		self.timestamp.write(w)?;
4116		self.node_id.write(w)?;
4117		w.write_all(&self.rgb)?;
4118		self.alias.write(w)?;
4119
4120		let mut addr_len = 0;
4121		for addr in self.addresses.iter() {
4122			addr_len += 1 + addr.len();
4123		}
4124		(addr_len + self.excess_address_data.len() as u16).write(w)?;
4125		for addr in self.addresses.iter() {
4126			addr.write(w)?;
4127		}
4128		w.write_all(&self.excess_address_data[..])?;
4129		w.write_all(&self.excess_data[..])?;
4130		Ok(())
4131	}
4132}
4133
4134impl LengthReadable for UnsignedNodeAnnouncement {
4135	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4136		let features: NodeFeatures = Readable::read(r)?;
4137		let timestamp: u32 = Readable::read(r)?;
4138		let node_id: NodeId = Readable::read(r)?;
4139		let mut rgb = [0; 3];
4140		r.read_exact(&mut rgb)?;
4141		let alias: NodeAlias = Readable::read(r)?;
4142
4143		let addr_len: u16 = Readable::read(r)?;
4144		let mut addresses: Vec<SocketAddress> = Vec::new();
4145		let mut addr_readpos = 0;
4146		let mut excess = false;
4147		let mut excess_byte = 0;
4148		loop {
4149			if addr_len <= addr_readpos {
4150				break;
4151			}
4152			match Readable::read(r) {
4153				Ok(Ok(addr)) => {
4154					if addr_len < addr_readpos + 1 + addr.len() {
4155						return Err(DecodeError::BadLengthDescriptor);
4156					}
4157					addr_readpos += (1 + addr.len()) as u16;
4158					addresses.push(addr);
4159				},
4160				Ok(Err(unknown_descriptor)) => {
4161					excess = true;
4162					excess_byte = unknown_descriptor;
4163					break;
4164				},
4165				Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
4166				Err(e) => return Err(e),
4167			}
4168		}
4169
4170		let mut excess_data = vec![];
4171		let excess_address_data = if addr_readpos < addr_len {
4172			let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
4173			r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
4174			if excess {
4175				excess_address_data[0] = excess_byte;
4176			}
4177			excess_address_data
4178		} else {
4179			if excess {
4180				excess_data.push(excess_byte);
4181			}
4182			Vec::new()
4183		};
4184		excess_data.extend(read_to_end(r)?.iter());
4185		Ok(UnsignedNodeAnnouncement {
4186			features,
4187			timestamp,
4188			node_id,
4189			rgb,
4190			alias,
4191			addresses,
4192			excess_address_data,
4193			excess_data,
4194		})
4195	}
4196}
4197
4198impl Writeable for NodeAnnouncement {
4199	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4200		self.signature.write(w)?;
4201		self.contents.write(w)?;
4202		Ok(())
4203	}
4204}
4205
4206impl LengthReadable for NodeAnnouncement {
4207	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4208		Ok(Self {
4209			signature: Readable::read(r)?,
4210			contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4211		})
4212	}
4213}
4214
4215impl LengthReadable for QueryShortChannelIds {
4216	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4217		let chain_hash: ChainHash = Readable::read(r)?;
4218
4219		let encoding_len: u16 = Readable::read(r)?;
4220		let encoding_type: u8 = Readable::read(r)?;
4221
4222		// Must be encoding_type=0 uncompressed serialization. We do not
4223		// support encoding_type=1 zlib serialization.
4224		if encoding_type != EncodingType::Uncompressed as u8 {
4225			return Err(DecodeError::UnsupportedCompression);
4226		}
4227
4228		// We expect the encoding_len to always includes the 1-byte
4229		// encoding_type and that short_channel_ids are 8-bytes each
4230		if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4231			return Err(DecodeError::InvalidValue);
4232		}
4233
4234		// Read short_channel_ids (8-bytes each), for the u16 encoding_len
4235		// less the 1-byte encoding_type
4236		let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4237		let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4238		for _ in 0..short_channel_id_count {
4239			short_channel_ids.push(Readable::read(r)?);
4240		}
4241
4242		Ok(QueryShortChannelIds { chain_hash, short_channel_ids })
4243	}
4244}
4245
4246impl Writeable for QueryShortChannelIds {
4247	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4248		// Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
4249		let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4250
4251		self.chain_hash.write(w)?;
4252		encoding_len.write(w)?;
4253
4254		// We only support type=0 uncompressed serialization
4255		(EncodingType::Uncompressed as u8).write(w)?;
4256
4257		for scid in self.short_channel_ids.iter() {
4258			scid.write(w)?;
4259		}
4260
4261		Ok(())
4262	}
4263}
4264
4265impl_writeable_msg!(ReplyShortChannelIdsEnd, {
4266	chain_hash,
4267	full_information,
4268}, {});
4269
4270impl QueryChannelRange {
4271	/// Calculates the overflow safe ending block height for the query.
4272	///
4273	/// Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`.
4274	pub fn end_blocknum(&self) -> u32 {
4275		match self.first_blocknum.checked_add(self.number_of_blocks) {
4276			Some(block) => block,
4277			None => u32::max_value(),
4278		}
4279	}
4280}
4281
4282impl_writeable_msg!(QueryChannelRange, {
4283	chain_hash,
4284	first_blocknum,
4285	number_of_blocks
4286}, {});
4287
4288impl LengthReadable for ReplyChannelRange {
4289	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4290		let chain_hash: ChainHash = Readable::read(r)?;
4291		let first_blocknum: u32 = Readable::read(r)?;
4292		let number_of_blocks: u32 = Readable::read(r)?;
4293		let sync_complete: bool = Readable::read(r)?;
4294
4295		let encoding_len: u16 = Readable::read(r)?;
4296		let encoding_type: u8 = Readable::read(r)?;
4297
4298		// Must be encoding_type=0 uncompressed serialization. We do not
4299		// support encoding_type=1 zlib serialization.
4300		if encoding_type != EncodingType::Uncompressed as u8 {
4301			return Err(DecodeError::UnsupportedCompression);
4302		}
4303
4304		// We expect the encoding_len to always includes the 1-byte
4305		// encoding_type and that short_channel_ids are 8-bytes each
4306		if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4307			return Err(DecodeError::InvalidValue);
4308		}
4309
4310		// Read short_channel_ids (8-bytes each), for the u16 encoding_len
4311		// less the 1-byte encoding_type
4312		let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4313		let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4314		for _ in 0..short_channel_id_count {
4315			short_channel_ids.push(Readable::read(r)?);
4316		}
4317
4318		Ok(ReplyChannelRange {
4319			chain_hash,
4320			first_blocknum,
4321			number_of_blocks,
4322			sync_complete,
4323			short_channel_ids,
4324		})
4325	}
4326}
4327
4328impl Writeable for ReplyChannelRange {
4329	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4330		let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4331		self.chain_hash.write(w)?;
4332		self.first_blocknum.write(w)?;
4333		self.number_of_blocks.write(w)?;
4334		self.sync_complete.write(w)?;
4335
4336		encoding_len.write(w)?;
4337		(EncodingType::Uncompressed as u8).write(w)?;
4338		for scid in self.short_channel_ids.iter() {
4339			scid.write(w)?;
4340		}
4341
4342		Ok(())
4343	}
4344}
4345
4346impl_writeable_msg!(GossipTimestampFilter, {
4347	chain_hash,
4348	first_timestamp,
4349	timestamp_range,
4350}, {});
4351
4352#[cfg(test)]
4353mod tests {
4354	use crate::ln::msgs::SocketAddress;
4355	use crate::ln::msgs::{
4356		self, CommonAcceptChannelFields, CommonOpenChannelFields, FinalOnionHopData,
4357		InboundOnionForwardPayload, InboundOnionReceivePayload, OutboundTrampolinePayload,
4358		TrampolineOnionPacket,
4359	};
4360	use crate::ln::onion_utils::{AttributionData, HMAC_COUNT, HMAC_LEN, HOLD_TIME_LEN, MAX_HOPS};
4361	use crate::ln::types::ChannelId;
4362	use crate::routing::gossip::{NodeAlias, NodeId};
4363	use crate::types::features::{
4364		ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures,
4365	};
4366	use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
4367	use crate::util::ser::{BigSize, Hostname, LengthReadable, Readable, ReadableArgs, Writeable};
4368	use crate::util::test_utils;
4369	use bitcoin::hex::DisplayHex;
4370	use bitcoin::{Amount, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};
4371
4372	use bitcoin::address::Address;
4373	use bitcoin::constants::ChainHash;
4374	use bitcoin::hash_types::Txid;
4375	use bitcoin::hex::FromHex;
4376	use bitcoin::locktime::absolute::LockTime;
4377	use bitcoin::network::Network;
4378	use bitcoin::opcodes;
4379	use bitcoin::script::Builder;
4380	use bitcoin::transaction::Version;
4381
4382	use bitcoin::secp256k1::{Message, Secp256k1};
4383	use bitcoin::secp256k1::{PublicKey, SecretKey};
4384
4385	use crate::chain::transaction::OutPoint;
4386	use crate::io::{self, Cursor};
4387	use crate::prelude::*;
4388	use core::str::FromStr;
4389
4390	use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
4391	#[cfg(feature = "std")]
4392	use crate::ln::msgs::SocketAddressParseError;
4393	#[cfg(feature = "std")]
4394	use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
4395	use types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
4396
4397	#[test]
4398	fn encoding_channel_reestablish() {
4399		let public_key = {
4400			let secp_ctx = Secp256k1::new();
4401			PublicKey::from_secret_key(
4402				&secp_ctx,
4403				&SecretKey::from_slice(
4404					&<Vec<u8>>::from_hex(
4405						"0101010101010101010101010101010101010101010101010101010101010101",
4406					)
4407					.unwrap()[..],
4408				)
4409				.unwrap(),
4410			)
4411		};
4412
4413		let cr = msgs::ChannelReestablish {
4414			channel_id: ChannelId::from_bytes([
4415				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,
4416				0, 0, 0, 0,
4417			]),
4418			next_local_commitment_number: 3,
4419			next_remote_commitment_number: 4,
4420			your_last_per_commitment_secret: [9; 32],
4421			my_current_per_commitment_point: public_key,
4422			next_funding: None,
4423			my_current_funding_locked: None,
4424		};
4425
4426		let encoded_value = cr.encode();
4427		assert_eq!(
4428			encoded_value,
4429			vec![
4430				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,
4431				0, 0, 0, 0, // channel_id
4432				0, 0, 0, 0, 0, 0, 0, 3, // next_local_commitment_number
4433				0, 0, 0, 0, 0, 0, 0, 4, // next_remote_commitment_number
4434				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,
4435				9, 9, 9, 9, // your_last_per_commitment_secret
4436				3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4437				24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4438				143, // my_current_per_commitment_point
4439			]
4440		);
4441	}
4442
4443	#[test]
4444	fn encoding_channel_reestablish_with_next_funding_txid() {
4445		let public_key = {
4446			let secp_ctx = Secp256k1::new();
4447			PublicKey::from_secret_key(
4448				&secp_ctx,
4449				&SecretKey::from_slice(
4450					&<Vec<u8>>::from_hex(
4451						"0101010101010101010101010101010101010101010101010101010101010101",
4452					)
4453					.unwrap()[..],
4454				)
4455				.unwrap(),
4456			)
4457		};
4458
4459		let cr = msgs::ChannelReestablish {
4460			channel_id: ChannelId::from_bytes([
4461				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,
4462				0, 0, 0, 0,
4463			]),
4464			next_local_commitment_number: 3,
4465			next_remote_commitment_number: 4,
4466			your_last_per_commitment_secret: [9; 32],
4467			my_current_per_commitment_point: public_key,
4468			next_funding: Some(msgs::NextFunding {
4469				txid: Txid::from_raw_hash(
4470					bitcoin::hashes::Hash::from_slice(&[
4471						48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4472						80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4473					])
4474					.unwrap(),
4475				),
4476				retransmit_flags: 1,
4477			}),
4478			my_current_funding_locked: None,
4479		};
4480
4481		let encoded_value = cr.encode();
4482		assert_eq!(
4483			encoded_value,
4484			vec![
4485				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,
4486				0, 0, 0, 0, // channel_id
4487				0, 0, 0, 0, 0, 0, 0, 3, // next_local_commitment_number
4488				0, 0, 0, 0, 0, 0, 0, 4, // next_remote_commitment_number
4489				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,
4490				9, 9, 9, 9, // your_last_per_commitment_secret
4491				3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4492				24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4493				143, // my_current_per_commitment_point
4494				1,   // Type (next_funding)
4495				33,  // Length
4496				48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4497				12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, // Value
4498			]
4499		);
4500	}
4501
4502	#[test]
4503	fn encoding_channel_reestablish_with_funding_locked_txid() {
4504		let public_key = {
4505			let secp_ctx = Secp256k1::new();
4506			PublicKey::from_secret_key(
4507				&secp_ctx,
4508				&SecretKey::from_slice(
4509					&<Vec<u8>>::from_hex(
4510						"0101010101010101010101010101010101010101010101010101010101010101",
4511					)
4512					.unwrap()[..],
4513				)
4514				.unwrap(),
4515			)
4516		};
4517
4518		let cr = msgs::ChannelReestablish {
4519			channel_id: ChannelId::from_bytes([
4520				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,
4521				0, 0, 0, 0,
4522			]),
4523			next_local_commitment_number: 3,
4524			next_remote_commitment_number: 4,
4525			your_last_per_commitment_secret: [9; 32],
4526			my_current_per_commitment_point: public_key,
4527			next_funding: None,
4528			my_current_funding_locked: Some(msgs::FundingLocked {
4529				txid: Txid::from_raw_hash(
4530					bitcoin::hashes::Hash::from_slice(&[
4531						21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4532						80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4533					])
4534					.unwrap(),
4535				),
4536				retransmit_flags: 1,
4537			}),
4538		};
4539
4540		let encoded_value = cr.encode();
4541		assert_eq!(
4542			encoded_value,
4543			vec![
4544				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,
4545				0, 0, 0, 0, // channel_id
4546				0, 0, 0, 0, 0, 0, 0, 3, // next_local_commitment_number
4547				0, 0, 0, 0, 0, 0, 0, 4, // next_remote_commitment_number
4548				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,
4549				9, 9, 9, 9, // your_last_per_commitment_secret
4550				3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4551				24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4552				143, // my_current_per_commitment_point
4553				5,   // Type (my_current_funding_locked)
4554				33,  // Length
4555				21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4556				12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, // Value
4557			]
4558		);
4559	}
4560
4561	macro_rules! get_keys_from {
4562		($slice: expr, $secp_ctx: expr) => {{
4563			let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex($slice).unwrap()[..]).unwrap();
4564			let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
4565			(privkey, pubkey)
4566		}};
4567	}
4568
4569	macro_rules! get_sig_on {
4570		($privkey: expr, $ctx: expr, $string: expr) => {{
4571			let sighash = Message::from_digest_slice(&$string.into_bytes()[..]).unwrap();
4572			$ctx.sign_ecdsa(&sighash, &$privkey)
4573		}};
4574	}
4575
4576	#[test]
4577	fn encoding_announcement_signatures() {
4578		let secp_ctx = Secp256k1::new();
4579		let (privkey, _) = get_keys_from!(
4580			"0101010101010101010101010101010101010101010101010101010101010101",
4581			secp_ctx
4582		);
4583		let sig_1 =
4584			get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
4585		let sig_2 =
4586			get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
4587		let announcement_signatures = msgs::AnnouncementSignatures {
4588			channel_id: ChannelId::from_bytes([
4589				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,
4590				0, 0, 0, 0,
4591			]),
4592			short_channel_id: 2316138423780173,
4593			node_signature: sig_1,
4594			bitcoin_signature: sig_2,
4595		};
4596
4597		let encoded_value = announcement_signatures.encode();
4598		assert_eq!(encoded_value, <Vec<u8>>::from_hex("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
4599	}
4600
4601	fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
4602		let secp_ctx = Secp256k1::new();
4603		let (privkey_1, pubkey_1) = get_keys_from!(
4604			"0101010101010101010101010101010101010101010101010101010101010101",
4605			secp_ctx
4606		);
4607		let (privkey_2, pubkey_2) = get_keys_from!(
4608			"0202020202020202020202020202020202020202020202020202020202020202",
4609			secp_ctx
4610		);
4611		let (privkey_3, pubkey_3) = get_keys_from!(
4612			"0303030303030303030303030303030303030303030303030303030303030303",
4613			secp_ctx
4614		);
4615		let (privkey_4, pubkey_4) = get_keys_from!(
4616			"0404040404040404040404040404040404040404040404040404040404040404",
4617			secp_ctx
4618		);
4619		let sig_1 =
4620			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4621		let sig_2 =
4622			get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
4623		let sig_3 =
4624			get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
4625		let sig_4 =
4626			get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
4627		let mut features = ChannelFeatures::empty();
4628		if unknown_features_bits {
4629			features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
4630		}
4631		let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
4632			features,
4633			chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4634			short_channel_id: 2316138423780173,
4635			node_id_1: NodeId::from_pubkey(&pubkey_1),
4636			node_id_2: NodeId::from_pubkey(&pubkey_2),
4637			bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
4638			bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
4639			excess_data: if excess_data {
4640				vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40]
4641			} else {
4642				Vec::new()
4643			},
4644		};
4645		let channel_announcement = msgs::ChannelAnnouncement {
4646			node_signature_1: sig_1,
4647			node_signature_2: sig_2,
4648			bitcoin_signature_1: sig_3,
4649			bitcoin_signature_2: sig_4,
4650			contents: unsigned_channel_announcement,
4651		};
4652		let encoded_value = channel_announcement.encode();
4653		let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
4654		if unknown_features_bits {
4655			target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4656		} else {
4657			target_value.append(&mut <Vec<u8>>::from_hex("0000").unwrap());
4658		}
4659		target_value.append(
4660			&mut <Vec<u8>>::from_hex(
4661				"6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4662			)
4663			.unwrap(),
4664		);
4665		target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
4666		if excess_data {
4667			target_value.append(&mut <Vec<u8>>::from_hex("0a00001400001e000028").unwrap());
4668		}
4669		assert_eq!(encoded_value, target_value);
4670	}
4671
4672	#[test]
4673	fn encoding_channel_announcement() {
4674		do_encoding_channel_announcement(true, false);
4675		do_encoding_channel_announcement(false, true);
4676		do_encoding_channel_announcement(false, false);
4677		do_encoding_channel_announcement(true, true);
4678	}
4679
4680	fn do_encoding_node_announcement(
4681		unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool,
4682		hostname: bool, excess_address_data: bool, excess_data: bool,
4683	) {
4684		let secp_ctx = Secp256k1::new();
4685		let (privkey_1, pubkey_1) = get_keys_from!(
4686			"0101010101010101010101010101010101010101010101010101010101010101",
4687			secp_ctx
4688		);
4689		let sig_1 =
4690			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4691		let features = if unknown_features_bits {
4692			NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
4693		} else {
4694			// Set to some features we may support
4695			NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
4696		};
4697		let mut addresses = Vec::new();
4698		if ipv4 {
4699			addresses.push(SocketAddress::TcpIpV4 { addr: [255, 254, 253, 252], port: 9735 });
4700		}
4701		if ipv6 {
4702			addresses.push(SocketAddress::TcpIpV6 {
4703				addr: [
4704					255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4705				],
4706				port: 9735,
4707			});
4708		}
4709		if onionv2 {
4710			addresses.push(msgs::SocketAddress::OnionV2([
4711				255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7,
4712			]));
4713		}
4714		if onionv3 {
4715			addresses.push(msgs::SocketAddress::OnionV3 {
4716				ed25519_pubkey: [
4717					255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4718					239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224,
4719				],
4720				checksum: 32,
4721				version: 16,
4722				port: 9735,
4723			});
4724		}
4725		if hostname {
4726			addresses.push(SocketAddress::Hostname {
4727				hostname: Hostname::try_from(String::from("host")).unwrap(),
4728				port: 9735,
4729			});
4730		}
4731		let mut addr_len = 0;
4732		for addr in &addresses {
4733			addr_len += addr.len() + 1;
4734		}
4735		let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
4736			features,
4737			timestamp: 20190119,
4738			node_id: NodeId::from_pubkey(&pubkey_1),
4739			rgb: [32; 3],
4740			alias: NodeAlias([16; 32]),
4741			addresses,
4742			excess_address_data: if excess_address_data {
4743				vec![
4744					33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34,
4745					241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84,
4746					174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42,
4747					160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105,
4748				]
4749			} else {
4750				Vec::new()
4751			},
4752			excess_data: if excess_data {
4753				vec![
4754					59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160,
4755					127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8,
4756					85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17,
4757					200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253,
4758				]
4759			} else {
4760				Vec::new()
4761			},
4762		};
4763		addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
4764		let node_announcement =
4765			msgs::NodeAnnouncement { signature: sig_1, contents: unsigned_node_announcement };
4766		let encoded_value = node_announcement.encode();
4767		let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4768		if unknown_features_bits {
4769			target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4770		} else {
4771			target_value.append(&mut <Vec<u8>>::from_hex("000122").unwrap());
4772		}
4773		target_value.append(&mut <Vec<u8>>::from_hex("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
4774		target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
4775		if ipv4 {
4776			target_value.append(&mut <Vec<u8>>::from_hex("01fffefdfc2607").unwrap());
4777		}
4778		if ipv6 {
4779			target_value.append(
4780				&mut <Vec<u8>>::from_hex("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap(),
4781			);
4782		}
4783		if onionv2 {
4784			target_value.append(&mut <Vec<u8>>::from_hex("03fffefdfcfbfaf9f8f7f62607").unwrap());
4785		}
4786		if onionv3 {
4787			target_value.append(
4788				&mut <Vec<u8>>::from_hex(
4789					"04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607",
4790				)
4791				.unwrap(),
4792			);
4793		}
4794		if hostname {
4795			target_value.append(&mut <Vec<u8>>::from_hex("0504686f73742607").unwrap());
4796		}
4797		if excess_address_data {
4798			target_value.append(&mut <Vec<u8>>::from_hex("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
4799		}
4800		if excess_data {
4801			target_value.append(&mut <Vec<u8>>::from_hex("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
4802		}
4803		assert_eq!(encoded_value, target_value);
4804	}
4805
4806	#[test]
4807	fn encoding_node_announcement() {
4808		do_encoding_node_announcement(true, true, true, true, true, true, true, true);
4809		do_encoding_node_announcement(false, false, false, false, false, false, false, false);
4810		do_encoding_node_announcement(false, true, false, false, false, false, false, false);
4811		do_encoding_node_announcement(false, false, true, false, false, false, false, false);
4812		do_encoding_node_announcement(false, false, false, true, false, false, false, false);
4813		do_encoding_node_announcement(false, false, false, false, true, false, false, false);
4814		do_encoding_node_announcement(false, false, false, false, false, true, false, false);
4815		do_encoding_node_announcement(false, false, false, false, false, false, true, false);
4816		do_encoding_node_announcement(false, true, false, true, false, false, true, false);
4817		do_encoding_node_announcement(false, false, true, false, true, false, false, false);
4818	}
4819
4820	fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
4821		let secp_ctx = Secp256k1::new();
4822		let (privkey_1, _) = get_keys_from!(
4823			"0101010101010101010101010101010101010101010101010101010101010101",
4824			secp_ctx
4825		);
4826		let sig_1 =
4827			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4828		let unsigned_channel_update = msgs::UnsignedChannelUpdate {
4829			chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4830			short_channel_id: 2316138423780173,
4831			timestamp: 20190119,
4832			message_flags: 1, // Only must_be_one
4833			channel_flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
4834			cltv_expiry_delta: 144,
4835			htlc_minimum_msat: 1000000,
4836			htlc_maximum_msat: 131355275467161,
4837			fee_base_msat: 10000,
4838			fee_proportional_millionths: 20,
4839			excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() },
4840		};
4841		let channel_update =
4842			msgs::ChannelUpdate { signature: sig_1, contents: unsigned_channel_update };
4843		let encoded_value = channel_update.encode();
4844		let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4845		target_value.append(
4846			&mut <Vec<u8>>::from_hex(
4847				"6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4848			)
4849			.unwrap(),
4850		);
4851		target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d013413a7").unwrap());
4852		target_value.append(&mut <Vec<u8>>::from_hex("01").unwrap());
4853		target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
4854		if direction {
4855			let flag = target_value.last_mut().unwrap();
4856			*flag = 1;
4857		}
4858		if disable {
4859			let flag = target_value.last_mut().unwrap();
4860			*flag |= 1 << 1;
4861		}
4862		target_value
4863			.append(&mut <Vec<u8>>::from_hex("009000000000000f42400000271000000014").unwrap());
4864		target_value.append(&mut <Vec<u8>>::from_hex("0000777788889999").unwrap());
4865		if excess_data {
4866			target_value.append(&mut <Vec<u8>>::from_hex("000000003b9aca00").unwrap());
4867		}
4868		assert_eq!(encoded_value, target_value);
4869	}
4870
4871	#[test]
4872	fn encoding_channel_update() {
4873		do_encoding_channel_update(false, false, false);
4874		do_encoding_channel_update(false, false, true);
4875		do_encoding_channel_update(true, false, false);
4876		do_encoding_channel_update(true, false, true);
4877		do_encoding_channel_update(false, true, false);
4878		do_encoding_channel_update(false, true, true);
4879		do_encoding_channel_update(true, true, false);
4880		do_encoding_channel_update(true, true, true);
4881	}
4882
4883	fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
4884		let secp_ctx = Secp256k1::new();
4885		let (_, pubkey_1) = get_keys_from!(
4886			"0101010101010101010101010101010101010101010101010101010101010101",
4887			secp_ctx
4888		);
4889		let (_, pubkey_2) = get_keys_from!(
4890			"0202020202020202020202020202020202020202020202020202020202020202",
4891			secp_ctx
4892		);
4893		let (_, pubkey_3) = get_keys_from!(
4894			"0303030303030303030303030303030303030303030303030303030303030303",
4895			secp_ctx
4896		);
4897		let (_, pubkey_4) = get_keys_from!(
4898			"0404040404040404040404040404040404040404040404040404040404040404",
4899			secp_ctx
4900		);
4901		let (_, pubkey_5) = get_keys_from!(
4902			"0505050505050505050505050505050505050505050505050505050505050505",
4903			secp_ctx
4904		);
4905		let (_, pubkey_6) = get_keys_from!(
4906			"0606060606060606060606060606060606060606060606060606060606060606",
4907			secp_ctx
4908		);
4909		let open_channel = msgs::OpenChannel {
4910			common_fields: CommonOpenChannelFields {
4911				chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4912				temporary_channel_id: ChannelId::from_bytes([2; 32]),
4913				funding_satoshis: 1311768467284833366,
4914				dust_limit_satoshis: 3608586615801332854,
4915				max_htlc_value_in_flight_msat: 8517154655701053848,
4916				htlc_minimum_msat: 2316138423780173,
4917				commitment_feerate_sat_per_1000_weight: 821716,
4918				to_self_delay: 49340,
4919				max_accepted_htlcs: 49340,
4920				funding_pubkey: pubkey_1,
4921				revocation_basepoint: pubkey_2,
4922				payment_basepoint: pubkey_3,
4923				delayed_payment_basepoint: pubkey_4,
4924				htlc_basepoint: pubkey_5,
4925				first_per_commitment_point: pubkey_6,
4926				channel_flags: if random_bit { 1 << 5 } else { 0 },
4927				shutdown_scriptpubkey: if shutdown {
4928					Some(
4929						Address::p2pkh(
4930							&::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
4931							Network::Testnet,
4932						)
4933						.script_pubkey(),
4934					)
4935				} else {
4936					None
4937				},
4938				channel_type: if incl_chan_type {
4939					Some(ChannelTypeFeatures::empty())
4940				} else {
4941					None
4942				},
4943			},
4944			push_msat: 2536655962884945560,
4945			channel_reserve_satoshis: 8665828695742877976,
4946		};
4947		let encoded_value = open_channel.encode();
4948		let mut target_value = Vec::new();
4949		target_value.append(
4950			&mut <Vec<u8>>::from_hex(
4951				"6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4952			)
4953			.unwrap(),
4954		);
4955		target_value.append(&mut <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
4956		if random_bit {
4957			target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
4958		} else {
4959			target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
4960		}
4961		if shutdown {
4962			target_value.append(
4963				&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
4964					.unwrap(),
4965			);
4966		}
4967		if incl_chan_type {
4968			target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
4969		}
4970		assert_eq!(encoded_value, target_value);
4971	}
4972
4973	#[test]
4974	fn encoding_open_channel() {
4975		do_encoding_open_channel(false, false, false);
4976		do_encoding_open_channel(false, false, true);
4977		do_encoding_open_channel(false, true, false);
4978		do_encoding_open_channel(false, true, true);
4979		do_encoding_open_channel(true, false, false);
4980		do_encoding_open_channel(true, false, true);
4981		do_encoding_open_channel(true, true, false);
4982		do_encoding_open_channel(true, true, true);
4983	}
4984
4985	fn do_encoding_open_channelv2(
4986		random_bit: bool, shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool,
4987	) {
4988		let secp_ctx = Secp256k1::new();
4989		let (_, pubkey_1) = get_keys_from!(
4990			"0101010101010101010101010101010101010101010101010101010101010101",
4991			secp_ctx
4992		);
4993		let (_, pubkey_2) = get_keys_from!(
4994			"0202020202020202020202020202020202020202020202020202020202020202",
4995			secp_ctx
4996		);
4997		let (_, pubkey_3) = get_keys_from!(
4998			"0303030303030303030303030303030303030303030303030303030303030303",
4999			secp_ctx
5000		);
5001		let (_, pubkey_4) = get_keys_from!(
5002			"0404040404040404040404040404040404040404040404040404040404040404",
5003			secp_ctx
5004		);
5005		let (_, pubkey_5) = get_keys_from!(
5006			"0505050505050505050505050505050505050505050505050505050505050505",
5007			secp_ctx
5008		);
5009		let (_, pubkey_6) = get_keys_from!(
5010			"0606060606060606060606060606060606060606060606060606060606060606",
5011			secp_ctx
5012		);
5013		let (_, pubkey_7) = get_keys_from!(
5014			"0707070707070707070707070707070707070707070707070707070707070707",
5015			secp_ctx
5016		);
5017		let open_channelv2 = msgs::OpenChannelV2 {
5018			common_fields: CommonOpenChannelFields {
5019				chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
5020				temporary_channel_id: ChannelId::from_bytes([2; 32]),
5021				commitment_feerate_sat_per_1000_weight: 821716,
5022				funding_satoshis: 1311768467284833366,
5023				dust_limit_satoshis: 3608586615801332854,
5024				max_htlc_value_in_flight_msat: 8517154655701053848,
5025				htlc_minimum_msat: 2316138423780173,
5026				to_self_delay: 49340,
5027				max_accepted_htlcs: 49340,
5028				funding_pubkey: pubkey_1,
5029				revocation_basepoint: pubkey_2,
5030				payment_basepoint: pubkey_3,
5031				delayed_payment_basepoint: pubkey_4,
5032				htlc_basepoint: pubkey_5,
5033				first_per_commitment_point: pubkey_6,
5034				channel_flags: if random_bit { 1 << 5 } else { 0 },
5035				shutdown_scriptpubkey: if shutdown {
5036					Some(
5037						Address::p2pkh(
5038							&::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5039							Network::Testnet,
5040						)
5041						.script_pubkey(),
5042					)
5043				} else {
5044					None
5045				},
5046				channel_type: if incl_chan_type {
5047					Some(ChannelTypeFeatures::empty())
5048				} else {
5049					None
5050				},
5051			},
5052			funding_feerate_sat_per_1000_weight: 821716,
5053			locktime: 305419896,
5054			second_per_commitment_point: pubkey_7,
5055			require_confirmed_inputs: if require_confirmed_inputs { Some(()) } else { None },
5056		};
5057		let encoded_value = open_channelv2.encode();
5058		let mut target_value = Vec::new();
5059		target_value.append(
5060			&mut <Vec<u8>>::from_hex(
5061				"6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
5062			)
5063			.unwrap(),
5064		);
5065		target_value.append(
5066			&mut <Vec<u8>>::from_hex(
5067				"0202020202020202020202020202020202020202020202020202020202020202",
5068			)
5069			.unwrap(),
5070		);
5071		target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5072		target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5073		target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap());
5074		target_value.append(&mut <Vec<u8>>::from_hex("3214466870114476").unwrap());
5075		target_value.append(&mut <Vec<u8>>::from_hex("7633030896203198").unwrap());
5076		target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap());
5077		target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5078		target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5079		target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap());
5080		target_value.append(
5081			&mut <Vec<u8>>::from_hex(
5082				"031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5083			)
5084			.unwrap(),
5085		);
5086		target_value.append(
5087			&mut <Vec<u8>>::from_hex(
5088				"024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5089			)
5090			.unwrap(),
5091		);
5092		target_value.append(
5093			&mut <Vec<u8>>::from_hex(
5094				"02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5095			)
5096			.unwrap(),
5097		);
5098		target_value.append(
5099			&mut <Vec<u8>>::from_hex(
5100				"03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5101			)
5102			.unwrap(),
5103		);
5104		target_value.append(
5105			&mut <Vec<u8>>::from_hex(
5106				"0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5107			)
5108			.unwrap(),
5109		);
5110		target_value.append(
5111			&mut <Vec<u8>>::from_hex(
5112				"03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5113			)
5114			.unwrap(),
5115		);
5116		target_value.append(
5117			&mut <Vec<u8>>::from_hex(
5118				"02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5119			)
5120			.unwrap(),
5121		);
5122
5123		if random_bit {
5124			target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
5125		} else {
5126			target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
5127		}
5128		if shutdown {
5129			target_value.append(
5130				&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5131					.unwrap(),
5132			);
5133		}
5134		if incl_chan_type {
5135			target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
5136		}
5137		if require_confirmed_inputs {
5138			target_value.append(&mut <Vec<u8>>::from_hex("0200").unwrap());
5139		}
5140		assert_eq!(encoded_value, target_value);
5141	}
5142
5143	#[test]
5144	fn encoding_open_channelv2() {
5145		do_encoding_open_channelv2(false, false, false, false);
5146		do_encoding_open_channelv2(false, false, false, true);
5147		do_encoding_open_channelv2(false, false, true, false);
5148		do_encoding_open_channelv2(false, false, true, true);
5149		do_encoding_open_channelv2(false, true, false, false);
5150		do_encoding_open_channelv2(false, true, false, true);
5151		do_encoding_open_channelv2(false, true, true, false);
5152		do_encoding_open_channelv2(false, true, true, true);
5153		do_encoding_open_channelv2(true, false, false, false);
5154		do_encoding_open_channelv2(true, false, false, true);
5155		do_encoding_open_channelv2(true, false, true, false);
5156		do_encoding_open_channelv2(true, false, true, true);
5157		do_encoding_open_channelv2(true, true, false, false);
5158		do_encoding_open_channelv2(true, true, false, true);
5159		do_encoding_open_channelv2(true, true, true, false);
5160		do_encoding_open_channelv2(true, true, true, true);
5161	}
5162
5163	fn do_encoding_accept_channel(shutdown: bool) {
5164		let secp_ctx = Secp256k1::new();
5165		let (_, pubkey_1) = get_keys_from!(
5166			"0101010101010101010101010101010101010101010101010101010101010101",
5167			secp_ctx
5168		);
5169		let (_, pubkey_2) = get_keys_from!(
5170			"0202020202020202020202020202020202020202020202020202020202020202",
5171			secp_ctx
5172		);
5173		let (_, pubkey_3) = get_keys_from!(
5174			"0303030303030303030303030303030303030303030303030303030303030303",
5175			secp_ctx
5176		);
5177		let (_, pubkey_4) = get_keys_from!(
5178			"0404040404040404040404040404040404040404040404040404040404040404",
5179			secp_ctx
5180		);
5181		let (_, pubkey_5) = get_keys_from!(
5182			"0505050505050505050505050505050505050505050505050505050505050505",
5183			secp_ctx
5184		);
5185		let (_, pubkey_6) = get_keys_from!(
5186			"0606060606060606060606060606060606060606060606060606060606060606",
5187			secp_ctx
5188		);
5189		let accept_channel = msgs::AcceptChannel {
5190			common_fields: CommonAcceptChannelFields {
5191				temporary_channel_id: ChannelId::from_bytes([2; 32]),
5192				dust_limit_satoshis: 1311768467284833366,
5193				max_htlc_value_in_flight_msat: 2536655962884945560,
5194				htlc_minimum_msat: 2316138423780173,
5195				minimum_depth: 821716,
5196				to_self_delay: 49340,
5197				max_accepted_htlcs: 49340,
5198				funding_pubkey: pubkey_1,
5199				revocation_basepoint: pubkey_2,
5200				payment_basepoint: pubkey_3,
5201				delayed_payment_basepoint: pubkey_4,
5202				htlc_basepoint: pubkey_5,
5203				first_per_commitment_point: pubkey_6,
5204				shutdown_scriptpubkey: if shutdown {
5205					Some(
5206						Address::p2pkh(
5207							&::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5208							Network::Testnet,
5209						)
5210						.script_pubkey(),
5211					)
5212				} else {
5213					None
5214				},
5215				channel_type: None,
5216			},
5217			channel_reserve_satoshis: 3608586615801332854,
5218			#[cfg(taproot)]
5219			next_local_nonce: None,
5220		};
5221		let encoded_value = accept_channel.encode();
5222		let mut target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
5223		if shutdown {
5224			target_value.append(
5225				&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5226					.unwrap(),
5227			);
5228		}
5229		assert_eq!(encoded_value, target_value);
5230	}
5231
5232	#[test]
5233	fn encoding_accept_channel() {
5234		do_encoding_accept_channel(false);
5235		do_encoding_accept_channel(true);
5236	}
5237
5238	fn do_encoding_accept_channelv2(shutdown: bool) {
5239		let secp_ctx = Secp256k1::new();
5240		let (_, pubkey_1) = get_keys_from!(
5241			"0101010101010101010101010101010101010101010101010101010101010101",
5242			secp_ctx
5243		);
5244		let (_, pubkey_2) = get_keys_from!(
5245			"0202020202020202020202020202020202020202020202020202020202020202",
5246			secp_ctx
5247		);
5248		let (_, pubkey_3) = get_keys_from!(
5249			"0303030303030303030303030303030303030303030303030303030303030303",
5250			secp_ctx
5251		);
5252		let (_, pubkey_4) = get_keys_from!(
5253			"0404040404040404040404040404040404040404040404040404040404040404",
5254			secp_ctx
5255		);
5256		let (_, pubkey_5) = get_keys_from!(
5257			"0505050505050505050505050505050505050505050505050505050505050505",
5258			secp_ctx
5259		);
5260		let (_, pubkey_6) = get_keys_from!(
5261			"0606060606060606060606060606060606060606060606060606060606060606",
5262			secp_ctx
5263		);
5264		let (_, pubkey_7) = get_keys_from!(
5265			"0707070707070707070707070707070707070707070707070707070707070707",
5266			secp_ctx
5267		);
5268		let accept_channelv2 = msgs::AcceptChannelV2 {
5269			common_fields: CommonAcceptChannelFields {
5270				temporary_channel_id: ChannelId::from_bytes([2; 32]),
5271				dust_limit_satoshis: 1311768467284833366,
5272				max_htlc_value_in_flight_msat: 2536655962884945560,
5273				htlc_minimum_msat: 2316138423780173,
5274				minimum_depth: 821716,
5275				to_self_delay: 49340,
5276				max_accepted_htlcs: 49340,
5277				funding_pubkey: pubkey_1,
5278				revocation_basepoint: pubkey_2,
5279				payment_basepoint: pubkey_3,
5280				delayed_payment_basepoint: pubkey_4,
5281				htlc_basepoint: pubkey_5,
5282				first_per_commitment_point: pubkey_6,
5283				shutdown_scriptpubkey: if shutdown {
5284					Some(
5285						Address::p2pkh(
5286							&::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5287							Network::Testnet,
5288						)
5289						.script_pubkey(),
5290					)
5291				} else {
5292					None
5293				},
5294				channel_type: None,
5295			},
5296			funding_satoshis: 1311768467284833366,
5297			second_per_commitment_point: pubkey_7,
5298			require_confirmed_inputs: None,
5299		};
5300		let encoded_value = accept_channelv2.encode();
5301		let mut target_value =
5302			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5303				.unwrap(); // temporary_channel_id
5304		target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap()); // funding_satoshis
5305		target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap()); // dust_limit_satoshis
5306		target_value.append(&mut <Vec<u8>>::from_hex("2334032891223698").unwrap()); // max_htlc_value_in_flight_msat
5307		target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap()); // htlc_minimum_msat
5308		target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap()); //  minimum_depth
5309		target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap()); // to_self_delay
5310		target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap()); // max_accepted_htlcs
5311		target_value.append(
5312			&mut <Vec<u8>>::from_hex(
5313				"031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5314			)
5315			.unwrap(),
5316		); // funding_pubkey
5317		target_value.append(
5318			&mut <Vec<u8>>::from_hex(
5319				"024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5320			)
5321			.unwrap(),
5322		); // revocation_basepoint
5323		target_value.append(
5324			&mut <Vec<u8>>::from_hex(
5325				"02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5326			)
5327			.unwrap(),
5328		); // payment_basepoint
5329		target_value.append(
5330			&mut <Vec<u8>>::from_hex(
5331				"03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5332			)
5333			.unwrap(),
5334		); // delayed_payment_basepoint
5335		target_value.append(
5336			&mut <Vec<u8>>::from_hex(
5337				"0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5338			)
5339			.unwrap(),
5340		); // htlc_basepoint
5341		target_value.append(
5342			&mut <Vec<u8>>::from_hex(
5343				"03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5344			)
5345			.unwrap(),
5346		); // first_per_commitment_point
5347		target_value.append(
5348			&mut <Vec<u8>>::from_hex(
5349				"02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5350			)
5351			.unwrap(),
5352		); // second_per_commitment_point
5353		if shutdown {
5354			target_value.append(
5355				&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5356					.unwrap(),
5357			);
5358		}
5359		assert_eq!(encoded_value, target_value);
5360	}
5361
5362	#[test]
5363	fn encoding_accept_channelv2() {
5364		do_encoding_accept_channelv2(false);
5365		do_encoding_accept_channelv2(true);
5366	}
5367
5368	#[test]
5369	fn encoding_funding_created() {
5370		let secp_ctx = Secp256k1::new();
5371		let (privkey_1, _) = get_keys_from!(
5372			"0101010101010101010101010101010101010101010101010101010101010101",
5373			secp_ctx
5374		);
5375		let sig_1 =
5376			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5377		let funding_created = msgs::FundingCreated {
5378			temporary_channel_id: ChannelId::from_bytes([2; 32]),
5379			funding_txid: Txid::from_str(
5380				"c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5381			)
5382			.unwrap(),
5383			funding_output_index: 255,
5384			signature: sig_1,
5385			#[cfg(taproot)]
5386			partial_signature_with_nonce: None,
5387			#[cfg(taproot)]
5388			next_local_nonce: None,
5389		};
5390		let encoded_value = funding_created.encode();
5391		let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5392		assert_eq!(encoded_value, target_value);
5393	}
5394
5395	#[test]
5396	fn encoding_funding_signed() {
5397		let secp_ctx = Secp256k1::new();
5398		let (privkey_1, _) = get_keys_from!(
5399			"0101010101010101010101010101010101010101010101010101010101010101",
5400			secp_ctx
5401		);
5402		let sig_1 =
5403			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5404		let funding_signed = msgs::FundingSigned {
5405			channel_id: ChannelId::from_bytes([2; 32]),
5406			signature: sig_1,
5407			#[cfg(taproot)]
5408			partial_signature_with_nonce: None,
5409		};
5410		let encoded_value = funding_signed.encode();
5411		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5412		assert_eq!(encoded_value, target_value);
5413	}
5414
5415	#[test]
5416	fn encoding_channel_ready() {
5417		let secp_ctx = Secp256k1::new();
5418		let (_, pubkey_1) = get_keys_from!(
5419			"0101010101010101010101010101010101010101010101010101010101010101",
5420			secp_ctx
5421		);
5422		let channel_ready = msgs::ChannelReady {
5423			channel_id: ChannelId::from_bytes([2; 32]),
5424			next_per_commitment_point: pubkey_1,
5425			short_channel_id_alias: None,
5426		};
5427		let encoded_value = channel_ready.encode();
5428		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
5429		assert_eq!(encoded_value, target_value);
5430	}
5431
5432	#[test]
5433	fn encoding_splice_init() {
5434		let secp_ctx = Secp256k1::new();
5435		let (_, pubkey_1) = get_keys_from!(
5436			"0101010101010101010101010101010101010101010101010101010101010101",
5437			secp_ctx
5438		);
5439		let splice_init = msgs::SpliceInit {
5440			channel_id: ChannelId::from_bytes([2; 32]),
5441			funding_contribution_satoshis: -123456,
5442			funding_feerate_per_kw: 2000,
5443			locktime: 0,
5444			funding_pubkey: pubkey_1,
5445			require_confirmed_inputs: Some(()),
5446		};
5447		let encoded_value = splice_init.encode();
5448		assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5449	}
5450
5451	#[test]
5452	fn encoding_stfu() {
5453		let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([2; 32]), initiator: true };
5454		let encoded_value = stfu.encode();
5455		assert_eq!(
5456			encoded_value.as_hex().to_string(),
5457			"020202020202020202020202020202020202020202020202020202020202020201"
5458		);
5459
5460		let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([3; 32]), initiator: false };
5461		let encoded_value = stfu.encode();
5462		assert_eq!(
5463			encoded_value.as_hex().to_string(),
5464			"030303030303030303030303030303030303030303030303030303030303030300"
5465		);
5466	}
5467
5468	#[test]
5469	fn encoding_splice_ack() {
5470		let secp_ctx = Secp256k1::new();
5471		let (_, pubkey_1) = get_keys_from!(
5472			"0101010101010101010101010101010101010101010101010101010101010101",
5473			secp_ctx
5474		);
5475		let splice_ack = msgs::SpliceAck {
5476			channel_id: ChannelId::from_bytes([2; 32]),
5477			funding_contribution_satoshis: -123456,
5478			funding_pubkey: pubkey_1,
5479			require_confirmed_inputs: Some(()),
5480		};
5481		let encoded_value = splice_ack.encode();
5482		assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5483	}
5484
5485	#[test]
5486	fn encoding_splice_locked() {
5487		let splice_locked = msgs::SpliceLocked {
5488			channel_id: ChannelId::from_bytes([2; 32]),
5489			splice_txid: Txid::from_str(
5490				"c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5491			)
5492			.unwrap(),
5493		};
5494		let encoded_value = splice_locked.encode();
5495		assert_eq!(encoded_value.as_hex().to_string(), "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2");
5496	}
5497
5498	#[test]
5499	fn encoding_tx_add_input() {
5500		let tx_add_input = msgs::TxAddInput {
5501			channel_id: ChannelId::from_bytes([2; 32]),
5502			serial_id: 4886718345,
5503			prevtx: Some(Transaction {
5504				version: Version::TWO,
5505				lock_time: LockTime::ZERO,
5506				input: vec![TxIn {
5507					previous_output: OutPoint { txid: Txid::from_str("305bab643ee297b8b6b76b320792c8223d55082122cb606bf89382146ced9c77").unwrap(), index: 2 }.into_bitcoin_outpoint(),
5508					script_sig: ScriptBuf::new(),
5509					sequence: Sequence(0xfffffffd),
5510					witness: Witness::from_slice(&[
5511						<Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5512						<Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5513				}],
5514				output: vec![
5515					TxOut {
5516						value: Amount::from_sat(12704566),
5517						script_pubkey: Address::from_str("bc1qzlffunw52jav8vwdu5x3jfk6sr8u22rmq3xzw2").unwrap().assume_checked().script_pubkey(),
5518					},
5519					TxOut {
5520						value: Amount::from_sat(245148),
5521						script_pubkey: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().assume_checked().script_pubkey(),
5522					},
5523				],
5524			}),
5525			prevtx_out: 305419896,
5526			sequence: 305419896,
5527			shared_input_txid: None,
5528		};
5529		let encoded_value = tx_add_input.encode();
5530		let target_value = "0202020202020202020202020202020202020202020202020202020202020202000000012345678900de02000000000101779ced6c148293f86b60cb222108553d22c89207326bb7b6b897e23e64ab5b300200000000fdffffff0236dbc1000000000016001417d29e4dd454bac3b1cde50d1926da80cfc5287b9cbd03000000000016001436ec78d514df462da95e6a00c24daa8915362d420247304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701210301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944000000001234567812345678";
5531		assert_eq!(encoded_value.as_hex().to_string(), target_value);
5532	}
5533
5534	#[test]
5535	fn encoding_tx_add_input_shared() {
5536		let tx_add_input = msgs::TxAddInput {
5537			channel_id: ChannelId::from_bytes([2; 32]),
5538			serial_id: 4886718345,
5539			prevtx: None,
5540			prevtx_out: 305419896,
5541			sequence: 305419896,
5542			shared_input_txid: Some(
5543				Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
5544					.unwrap(),
5545			),
5546		};
5547		let encoded_value = tx_add_input.encode();
5548		let target_value = "020202020202020202020202020202020202020202020202020202020202020200000001234567890000123456781234567800206e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2";
5549		assert_eq!(encoded_value.as_hex().to_string(), target_value);
5550	}
5551
5552	#[test]
5553	fn encoding_tx_add_output() {
5554		let tx_add_output = msgs::TxAddOutput {
5555			channel_id: ChannelId::from_bytes([2; 32]),
5556			serial_id: 4886718345,
5557			sats: 4886718345,
5558			script: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z")
5559				.unwrap()
5560				.assume_checked()
5561				.script_pubkey(),
5562		};
5563		let encoded_value = tx_add_output.encode();
5564		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000000012345678900000001234567890016001436ec78d514df462da95e6a00c24daa8915362d42").unwrap();
5565		assert_eq!(encoded_value, target_value);
5566	}
5567
5568	#[test]
5569	fn encoding_tx_remove_input() {
5570		let tx_remove_input = msgs::TxRemoveInput {
5571			channel_id: ChannelId::from_bytes([2; 32]),
5572			serial_id: 4886718345,
5573		};
5574		let encoded_value = tx_remove_input.encode();
5575		let target_value = <Vec<u8>>::from_hex(
5576			"02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5577		)
5578		.unwrap();
5579		assert_eq!(encoded_value, target_value);
5580	}
5581
5582	#[test]
5583	fn encoding_tx_remove_output() {
5584		let tx_remove_output = msgs::TxRemoveOutput {
5585			channel_id: ChannelId::from_bytes([2; 32]),
5586			serial_id: 4886718345,
5587		};
5588		let encoded_value = tx_remove_output.encode();
5589		let target_value = <Vec<u8>>::from_hex(
5590			"02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5591		)
5592		.unwrap();
5593		assert_eq!(encoded_value, target_value);
5594	}
5595
5596	#[test]
5597	fn encoding_tx_complete() {
5598		let tx_complete = msgs::TxComplete { channel_id: ChannelId::from_bytes([2; 32]) };
5599		let encoded_value = tx_complete.encode();
5600		let target_value =
5601			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5602				.unwrap();
5603		assert_eq!(encoded_value, target_value);
5604	}
5605
5606	#[test]
5607	fn encoding_tx_signatures() {
5608		let secp_ctx = Secp256k1::new();
5609		let (privkey_1, _) = get_keys_from!(
5610			"0101010101010101010101010101010101010101010101010101010101010101",
5611			secp_ctx
5612		);
5613		let sig_1 =
5614			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5615
5616		let tx_signatures = msgs::TxSignatures {
5617			channel_id: ChannelId::from_bytes([2; 32]),
5618			tx_hash: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
5619			witnesses: vec![
5620				Witness::from_slice(&[
5621					<Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5622					<Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5623				Witness::from_slice(&[
5624					<Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap(),
5625					<Vec<u8>>::from_hex("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap()]),
5626			],
5627			shared_input_signature: Some(sig_1),
5628		};
5629		let encoded_value = tx_signatures.encode();
5630		let mut target_value =
5631			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5632				.unwrap(); // channel_id
5633		target_value.append(
5634			&mut <Vec<u8>>::from_hex(
5635				"6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2",
5636			)
5637			.unwrap(),
5638		); // tx_hash (sha256) (big endian byte order)
5639		target_value.append(&mut <Vec<u8>>::from_hex("0002").unwrap()); // num_witnesses (u16)
5640
5641		// Witness 1
5642		target_value.append(&mut <Vec<u8>>::from_hex("006b").unwrap()); // len of witness_data
5643		target_value.append(&mut <Vec<u8>>::from_hex("02").unwrap()); // num_witness_elements (VarInt)
5644		target_value.append(&mut <Vec<u8>>::from_hex("47").unwrap()); // len of witness element data (VarInt)
5645		target_value.append(&mut <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap());
5646		target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); // len of witness element data (VarInt)
5647		target_value.append(
5648			&mut <Vec<u8>>::from_hex(
5649				"0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944",
5650			)
5651			.unwrap(),
5652		);
5653		// Witness 2
5654		target_value.append(&mut <Vec<u8>>::from_hex("006c").unwrap()); // len of witness_data
5655		target_value.append(&mut <Vec<u8>>::from_hex("02").unwrap()); // num_witness_elements (VarInt)
5656		target_value.append(&mut <Vec<u8>>::from_hex("48").unwrap()); // len of witness element data (VarInt)
5657		target_value.append(&mut <Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap());
5658		target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); // len of witness element data (VarInt)
5659		target_value.append(
5660			&mut <Vec<u8>>::from_hex(
5661				"028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5",
5662			)
5663			.unwrap(),
5664		);
5665		target_value.append(&mut <Vec<u8>>::from_hex("0040").unwrap()); // type and len (64)
5666		target_value.append(&mut <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap());
5667		assert_eq!(encoded_value, target_value);
5668	}
5669
5670	fn do_encoding_tx_init_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5671		let tx_init_rbf = msgs::TxInitRbf {
5672			channel_id: ChannelId::from_bytes([2; 32]),
5673			locktime: 305419896,
5674			feerate_sat_per_1000_weight: 20190119,
5675			funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5676				Some(value)
5677			} else {
5678				None
5679			},
5680		};
5681		let encoded_value = tx_init_rbf.encode();
5682		let mut target_value =
5683			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5684				.unwrap(); // channel_id
5685		target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap()); // locktime
5686		target_value.append(&mut <Vec<u8>>::from_hex("013413a7").unwrap()); // feerate_sat_per_1000_weight
5687		if let Some((_, target)) = funding_value_with_hex_target {
5688			target_value.push(0x00); // Type
5689			target_value.push(target.len() as u8 / 2); // Length
5690			target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); // Value (i64)
5691		}
5692		assert_eq!(encoded_value, target_value);
5693	}
5694
5695	#[test]
5696	fn encoding_tx_init_rbf() {
5697		do_encoding_tx_init_rbf(Some((1311768467284833366, "1234567890123456")));
5698		do_encoding_tx_init_rbf(Some((13117684672, "000000030DDFFBC0")));
5699		do_encoding_tx_init_rbf(None);
5700	}
5701
5702	fn do_encoding_tx_ack_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5703		let tx_ack_rbf = msgs::TxAckRbf {
5704			channel_id: ChannelId::from_bytes([2; 32]),
5705			funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5706				Some(value)
5707			} else {
5708				None
5709			},
5710		};
5711		let encoded_value = tx_ack_rbf.encode();
5712		let mut target_value =
5713			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5714				.unwrap();
5715		if let Some((_, target)) = funding_value_with_hex_target {
5716			target_value.push(0x00); // Type
5717			target_value.push(target.len() as u8 / 2); // Length
5718			target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); // Value (i64)
5719		}
5720		assert_eq!(encoded_value, target_value);
5721	}
5722
5723	#[test]
5724	fn encoding_tx_ack_rbf() {
5725		do_encoding_tx_ack_rbf(Some((1311768467284833366, "1234567890123456")));
5726		do_encoding_tx_ack_rbf(Some((13117684672, "000000030DDFFBC0")));
5727		do_encoding_tx_ack_rbf(None);
5728	}
5729
5730	#[test]
5731	fn encoding_tx_abort() {
5732		let tx_abort = msgs::TxAbort {
5733			channel_id: ChannelId::from_bytes([2; 32]),
5734			data: <Vec<u8>>::from_hex("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(),
5735		};
5736		let encoded_value = tx_abort.encode();
5737		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap();
5738		assert_eq!(encoded_value, target_value);
5739	}
5740
5741	fn do_encoding_shutdown(script_type: u8) {
5742		let secp_ctx = Secp256k1::new();
5743		let (_, pubkey_1) = get_keys_from!(
5744			"0101010101010101010101010101010101010101010101010101010101010101",
5745			secp_ctx
5746		);
5747		let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
5748		let shutdown = msgs::Shutdown {
5749			channel_id: ChannelId::from_bytes([2; 32]),
5750			scriptpubkey: if script_type == 1 {
5751				Address::p2pkh(
5752					&::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5753					Network::Testnet,
5754				)
5755				.script_pubkey()
5756			} else if script_type == 2 {
5757				Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey()
5758			} else if script_type == 3 {
5759				Address::p2wpkh(&::bitcoin::CompressedPublicKey(pubkey_1), Network::Testnet)
5760					.script_pubkey()
5761			} else {
5762				Address::p2wsh(&script, Network::Testnet).script_pubkey()
5763			},
5764		};
5765		let encoded_value = shutdown.encode();
5766		let mut target_value =
5767			<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5768				.unwrap();
5769		if script_type == 1 {
5770			target_value.append(
5771				&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5772					.unwrap(),
5773			);
5774		} else if script_type == 2 {
5775			target_value.append(
5776				&mut <Vec<u8>>::from_hex("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87")
5777					.unwrap(),
5778			);
5779		} else if script_type == 3 {
5780			target_value.append(
5781				&mut <Vec<u8>>::from_hex("0016001479b000887626b294a914501a4cd226b58b235983")
5782					.unwrap(),
5783			);
5784		} else if script_type == 4 {
5785			target_value.append(
5786				&mut <Vec<u8>>::from_hex(
5787					"002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260",
5788				)
5789				.unwrap(),
5790			);
5791		}
5792		assert_eq!(encoded_value, target_value);
5793	}
5794
5795	#[test]
5796	fn encoding_shutdown() {
5797		do_encoding_shutdown(1);
5798		do_encoding_shutdown(2);
5799		do_encoding_shutdown(3);
5800		do_encoding_shutdown(4);
5801	}
5802
5803	#[test]
5804	fn encoding_closing_signed() {
5805		let secp_ctx = Secp256k1::new();
5806		let (privkey_1, _) = get_keys_from!(
5807			"0101010101010101010101010101010101010101010101010101010101010101",
5808			secp_ctx
5809		);
5810		let sig_1 =
5811			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5812		let closing_signed = msgs::ClosingSigned {
5813			channel_id: ChannelId::from_bytes([2; 32]),
5814			fee_satoshis: 2316138423780173,
5815			signature: sig_1,
5816			fee_range: None,
5817		};
5818		let encoded_value = closing_signed.encode();
5819		let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5820		assert_eq!(encoded_value, target_value);
5821		assert_eq!(
5822			msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
5823			closing_signed
5824		);
5825
5826		let closing_signed_with_range = msgs::ClosingSigned {
5827			channel_id: ChannelId::from_bytes([2; 32]),
5828			fee_satoshis: 2316138423780173,
5829			signature: sig_1,
5830			fee_range: Some(msgs::ClosingSignedFeeRange {
5831				min_fee_satoshis: 0xdeadbeef,
5832				max_fee_satoshis: 0x1badcafe01234567,
5833			}),
5834		};
5835		let encoded_value_with_range = closing_signed_with_range.encode();
5836		let target_value_with_range = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
5837		assert_eq!(encoded_value_with_range, target_value_with_range);
5838		assert_eq!(
5839			msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value_with_range[..])
5840				.unwrap(),
5841			closing_signed_with_range
5842		);
5843	}
5844
5845	#[test]
5846	fn encoding_update_add_htlc() {
5847		let secp_ctx = Secp256k1::new();
5848		let (_, pubkey_1) = get_keys_from!(
5849			"0101010101010101010101010101010101010101010101010101010101010101",
5850			secp_ctx
5851		);
5852		let onion_routing_packet = msgs::OnionPacket {
5853			version: 255,
5854			public_key: Ok(pubkey_1),
5855			hop_data: [1; 20 * 65],
5856			hmac: [2; 32],
5857		};
5858		let update_add_htlc = msgs::UpdateAddHTLC {
5859			channel_id: ChannelId::from_bytes([2; 32]),
5860			htlc_id: 2316138423780173,
5861			amount_msat: 3608586615801332854,
5862			payment_hash: PaymentHash([1; 32]),
5863			cltv_expiry: 821716,
5864			onion_routing_packet,
5865			skimmed_fee_msat: None,
5866			blinding_point: None,
5867			hold_htlc: None,
5868		};
5869		let encoded_value = update_add_htlc.encode();
5870		let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
5871		assert_eq!(encoded_value, target_value);
5872	}
5873
5874	#[test]
5875	fn encoding_update_fulfill_htlc() {
5876		let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
5877			channel_id: ChannelId::from_bytes([2; 32]),
5878			htlc_id: 2316138423780173,
5879			payment_preimage: PaymentPreimage([1; 32]),
5880			attribution_data: None,
5881		};
5882		let encoded_value = update_fulfill_htlc.encode();
5883		let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
5884		assert_eq!(encoded_value, target_value);
5885	}
5886
5887	#[test]
5888	fn encoding_update_fail_htlc() {
5889		let update_fail_htlc = msgs::UpdateFailHTLC {
5890			channel_id: ChannelId::from_bytes([2; 32]),
5891			htlc_id: 2316138423780173,
5892			reason: [1; 32].to_vec(),
5893			attribution_data: Some(AttributionData {
5894				hold_times: [3; MAX_HOPS * HOLD_TIME_LEN],
5895				hmacs: [3; HMAC_LEN * HMAC_COUNT],
5896			}),
5897		};
5898		let encoded_value = update_fail_htlc.encode();
5899		let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0020010101010101010101010101010101010101010101010101010101010101010101fd03980303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303").unwrap();
5900		assert_eq!(encoded_value, target_value);
5901	}
5902
5903	#[test]
5904	fn encoding_update_fail_malformed_htlc() {
5905		let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
5906			channel_id: ChannelId::from_bytes([2; 32]),
5907			htlc_id: 2316138423780173,
5908			sha256_of_onion: [1; 32],
5909			failure_code: 255,
5910		};
5911		let encoded_value = update_fail_malformed_htlc.encode();
5912		let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
5913		assert_eq!(encoded_value, target_value);
5914	}
5915
5916	fn do_encoding_commitment_signed(htlcs: bool) {
5917		let secp_ctx = Secp256k1::new();
5918		let (privkey_1, _) = get_keys_from!(
5919			"0101010101010101010101010101010101010101010101010101010101010101",
5920			secp_ctx
5921		);
5922		let (privkey_2, _) = get_keys_from!(
5923			"0202020202020202020202020202020202020202020202020202020202020202",
5924			secp_ctx
5925		);
5926		let (privkey_3, _) = get_keys_from!(
5927			"0303030303030303030303030303030303030303030303030303030303030303",
5928			secp_ctx
5929		);
5930		let (privkey_4, _) = get_keys_from!(
5931			"0404040404040404040404040404040404040404040404040404040404040404",
5932			secp_ctx
5933		);
5934		let sig_1 =
5935			get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5936		let sig_2 =
5937			get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
5938		let sig_3 =
5939			get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
5940		let sig_4 =
5941			get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
5942		let commitment_signed = msgs::CommitmentSigned {
5943			channel_id: ChannelId::from_bytes([2; 32]),
5944			signature: sig_1,
5945			htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
5946			funding_txid: Some(
5947				Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
5948					.unwrap(),
5949			),
5950			#[cfg(taproot)]
5951			partial_signature_with_nonce: None,
5952		};
5953		let encoded_value = commitment_signed.encode();
5954		let mut target_value = "0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a".to_string();
5955		if htlcs {
5956			target_value += "00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd";
5957		} else {
5958			target_value += "0000";
5959		}
5960		target_value += "01"; // Type (funding_txid)
5961		target_value += "20"; // Length (funding_txid)
5962		target_value += "6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2"; // Value
5963		assert_eq!(encoded_value.as_hex().to_string(), target_value);
5964	}
5965
5966	#[test]
5967	fn encoding_commitment_signed() {
5968		do_encoding_commitment_signed(true);
5969		do_encoding_commitment_signed(false);
5970	}
5971
5972	#[test]
5973	fn encoding_revoke_and_ack() {
5974		let secp_ctx = Secp256k1::new();
5975		let (_, pubkey_1) = get_keys_from!(
5976			"0101010101010101010101010101010101010101010101010101010101010101",
5977			secp_ctx
5978		);
5979		let raa = msgs::RevokeAndACK {
5980			channel_id: ChannelId::from_bytes([2; 32]),
5981			per_commitment_secret: [
5982				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,
5983				1, 1, 1, 1,
5984			],
5985			next_per_commitment_point: pubkey_1,
5986			#[cfg(taproot)]
5987			next_local_nonce: None,
5988			release_htlc_message_paths: Vec::new(),
5989		};
5990		let encoded_value = raa.encode();
5991		let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
5992		assert_eq!(encoded_value, target_value);
5993	}
5994
5995	#[test]
5996	fn encoding_update_fee() {
5997		let update_fee = msgs::UpdateFee {
5998			channel_id: ChannelId::from_bytes([2; 32]),
5999			feerate_per_kw: 20190119,
6000		};
6001		let encoded_value = update_fee.encode();
6002		let target_value = <Vec<u8>>::from_hex(
6003			"0202020202020202020202020202020202020202020202020202020202020202013413a7",
6004		)
6005		.unwrap();
6006		assert_eq!(encoded_value, target_value);
6007	}
6008
6009	#[test]
6010	fn encoding_init() {
6011		let mainnet_hash = ChainHash::using_genesis_block(Network::Bitcoin);
6012		assert_eq!(msgs::Init {
6013			features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
6014			networks: Some(vec![mainnet_hash]),
6015			remote_network_address: None,
6016		}.encode(), <Vec<u8>>::from_hex("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
6017		assert_eq!(
6018			msgs::Init {
6019				features: InitFeatures::from_le_bytes(vec![0xFF]),
6020				networks: None,
6021				remote_network_address: None,
6022			}
6023			.encode(),
6024			<Vec<u8>>::from_hex("0001ff0001ff").unwrap()
6025		);
6026		assert_eq!(
6027			msgs::Init {
6028				features: InitFeatures::from_le_bytes(vec![]),
6029				networks: Some(vec![mainnet_hash]),
6030				remote_network_address: None,
6031			}
6032			.encode(),
6033			<Vec<u8>>::from_hex(
6034				"0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"
6035			)
6036			.unwrap()
6037		);
6038		assert_eq!(msgs::Init {
6039			features: InitFeatures::from_le_bytes(vec![]),
6040			networks: Some(vec![ChainHash::from(&[1; 32]), ChainHash::from(&[2; 32])]),
6041			remote_network_address: None,
6042		}.encode(), <Vec<u8>>::from_hex("00000000014001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap());
6043		let init_msg = msgs::Init {
6044			features: InitFeatures::from_le_bytes(vec![]),
6045			networks: Some(vec![mainnet_hash]),
6046			remote_network_address: Some(SocketAddress::TcpIpV4 {
6047				addr: [127, 0, 0, 1],
6048				port: 1000,
6049			}),
6050		};
6051		let encoded_value = init_msg.encode();
6052		let target_value = <Vec<u8>>::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap();
6053		assert_eq!(encoded_value, target_value);
6054		assert_eq!(
6055			msgs::Init::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
6056			init_msg
6057		);
6058	}
6059
6060	#[test]
6061	fn encoding_error() {
6062		let error = msgs::ErrorMessage {
6063			channel_id: ChannelId::from_bytes([2; 32]),
6064			data: String::from("rust-lightning"),
6065		};
6066		let encoded_value = error.encode();
6067		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6068		assert_eq!(encoded_value, target_value);
6069	}
6070
6071	#[test]
6072	fn encoding_warning() {
6073		let error = msgs::WarningMessage {
6074			channel_id: ChannelId::from_bytes([2; 32]),
6075			data: String::from("rust-lightning"),
6076		};
6077		let encoded_value = error.encode();
6078		let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6079		assert_eq!(encoded_value, target_value);
6080	}
6081
6082	#[test]
6083	fn encoding_ping() {
6084		let ping = msgs::Ping { ponglen: 64, byteslen: 64 };
6085		let encoded_value = ping.encode();
6086		let target_value = <Vec<u8>>::from_hex("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6087		assert_eq!(encoded_value, target_value);
6088	}
6089
6090	#[test]
6091	fn encoding_peer_storage() {
6092		let peer_storage =
6093			msgs::PeerStorage { data: <Vec<u8>>::from_hex("01020304050607080910").unwrap() };
6094		let encoded_value = peer_storage.encode();
6095		let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6096		assert_eq!(encoded_value, target_value);
6097	}
6098
6099	#[test]
6100	fn encoding_peer_storage_retrieval() {
6101		let peer_storage_retrieval = msgs::PeerStorageRetrieval {
6102			data: <Vec<u8>>::from_hex("01020304050607080910").unwrap(),
6103		};
6104		let encoded_value = peer_storage_retrieval.encode();
6105		let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6106		assert_eq!(encoded_value, target_value);
6107	}
6108
6109	#[test]
6110	fn encoding_pong() {
6111		let pong = msgs::Pong { byteslen: 64 };
6112		let encoded_value = pong.encode();
6113		let target_value = <Vec<u8>>::from_hex("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6114		assert_eq!(encoded_value, target_value);
6115	}
6116
6117	#[test]
6118	fn encoding_nonfinal_onion_hop_data() {
6119		let outbound_msg = msgs::OutboundOnionPayload::Forward {
6120			short_channel_id: 0xdeadbeef1bad1dea,
6121			amt_to_forward: 0x0badf00d01020304,
6122			outgoing_cltv_value: 0xffffffff,
6123		};
6124		let encoded_value = outbound_msg.encode();
6125		let target_value =
6126			<Vec<u8>>::from_hex("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
6127		assert_eq!(encoded_value, target_value);
6128
6129		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6130		let inbound_msg =
6131			ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6132		if let msgs::InboundOnionPayload::Forward(InboundOnionForwardPayload {
6133			short_channel_id,
6134			amt_to_forward,
6135			outgoing_cltv_value,
6136		}) = inbound_msg
6137		{
6138			assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
6139			assert_eq!(amt_to_forward, 0x0badf00d01020304);
6140			assert_eq!(outgoing_cltv_value, 0xffffffff);
6141		} else {
6142			panic!();
6143		}
6144	}
6145
6146	#[test]
6147	fn encoding_final_onion_hop_data() {
6148		let outbound_msg = msgs::OutboundOnionPayload::Receive {
6149			payment_data: None,
6150			payment_metadata: None,
6151			keysend_preimage: None,
6152			sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6153			cltv_expiry_height: 0xffffffff,
6154			custom_tlvs: &vec![],
6155		};
6156		let encoded_value = outbound_msg.encode();
6157		let target_value = <Vec<u8>>::from_hex("1002080badf00d010203040404ffffffff").unwrap();
6158		assert_eq!(encoded_value, target_value);
6159
6160		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6161		let inbound_msg =
6162			ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6163		if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6164			payment_data: None,
6165			sender_intended_htlc_amt_msat,
6166			cltv_expiry_height,
6167			..
6168		}) = inbound_msg
6169		{
6170			assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6171			assert_eq!(cltv_expiry_height, 0xffffffff);
6172		} else {
6173			panic!();
6174		}
6175	}
6176
6177	#[test]
6178	fn encoding_final_onion_hop_data_with_secret() {
6179		let expected_payment_secret = PaymentSecret([0x42u8; 32]);
6180		let outbound_msg = msgs::OutboundOnionPayload::Receive {
6181			payment_data: Some(FinalOnionHopData {
6182				payment_secret: expected_payment_secret,
6183				total_msat: 0x1badca1f,
6184			}),
6185			payment_metadata: None,
6186			keysend_preimage: None,
6187			sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6188			cltv_expiry_height: 0xffffffff,
6189			custom_tlvs: &vec![],
6190		};
6191		let encoded_value = outbound_msg.encode();
6192		let target_value = <Vec<u8>>::from_hex("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
6193		assert_eq!(encoded_value, target_value);
6194
6195		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6196		let inbound_msg =
6197			ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6198		if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6199			payment_data: Some(FinalOnionHopData { payment_secret, total_msat: 0x1badca1f }),
6200			sender_intended_htlc_amt_msat,
6201			cltv_expiry_height,
6202			payment_metadata: None,
6203			keysend_preimage: None,
6204			custom_tlvs,
6205		}) = inbound_msg
6206		{
6207			assert_eq!(payment_secret, expected_payment_secret);
6208			assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6209			assert_eq!(cltv_expiry_height, 0xffffffff);
6210			assert_eq!(custom_tlvs, vec![]);
6211		} else {
6212			panic!();
6213		}
6214	}
6215
6216	#[test]
6217	fn encoding_final_onion_hop_data_with_bad_custom_tlvs() {
6218		// If custom TLVs have type number within the range reserved for protocol, treat them as if
6219		// they're unknown
6220		let bad_type_range_tlvs = vec![((1 << 16) - 4, vec![42]), ((1 << 16) - 2, vec![42; 32])];
6221		let mut msg = msgs::OutboundOnionPayload::Receive {
6222			payment_data: None,
6223			payment_metadata: None,
6224			keysend_preimage: None,
6225			custom_tlvs: &bad_type_range_tlvs,
6226			sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6227			cltv_expiry_height: 0xffffffff,
6228		};
6229		let encoded_value = msg.encode();
6230		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6231		assert!(msgs::InboundOnionPayload::read(
6232			&mut Cursor::new(&encoded_value[..]),
6233			(None, &node_signer)
6234		)
6235		.is_err());
6236		let good_type_range_tlvs = vec![((1 << 16) - 3, vec![42]), ((1 << 16) - 1, vec![42; 32])];
6237		if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg {
6238			*custom_tlvs = &good_type_range_tlvs;
6239		}
6240		let encoded_value = msg.encode();
6241		let inbound_msg =
6242			ReadableArgs::read(&mut Cursor::new(&encoded_value[..]), (None, &node_signer)).unwrap();
6243		match inbound_msg {
6244			msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6245				custom_tlvs, ..
6246			}) => assert!(custom_tlvs.is_empty()),
6247			_ => panic!(),
6248		}
6249	}
6250
6251	#[test]
6252	fn encoding_final_onion_hop_data_with_custom_tlvs() {
6253		let expected_custom_tlvs =
6254			vec![(5482373483, vec![0x12, 0x34]), (5482373487, vec![0x42u8; 8])];
6255		let msg = msgs::OutboundOnionPayload::Receive {
6256			payment_data: None,
6257			payment_metadata: None,
6258			keysend_preimage: None,
6259			custom_tlvs: &expected_custom_tlvs,
6260			sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6261			cltv_expiry_height: 0xffffffff,
6262		};
6263		let encoded_value = msg.encode();
6264		let target_value = <Vec<u8>>::from_hex("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap();
6265		assert_eq!(encoded_value, target_value);
6266		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6267		let inbound_msg: msgs::InboundOnionPayload =
6268			ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6269		if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6270			payment_data: None,
6271			payment_metadata: None,
6272			keysend_preimage: None,
6273			custom_tlvs,
6274			sender_intended_htlc_amt_msat,
6275			cltv_expiry_height: outgoing_cltv_value,
6276			..
6277		}) = inbound_msg
6278		{
6279			assert_eq!(custom_tlvs, expected_custom_tlvs);
6280			assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6281			assert_eq!(outgoing_cltv_value, 0xffffffff);
6282		} else {
6283			panic!();
6284		}
6285	}
6286
6287	#[test]
6288	fn encoding_final_onion_hop_data_with_trampoline_packet() {
6289		let secp_ctx = Secp256k1::new();
6290		let (_private_key, public_key) = get_keys_from!(
6291			"0101010101010101010101010101010101010101010101010101010101010101",
6292			secp_ctx
6293		);
6294
6295		let compressed_public_key = public_key.serialize();
6296		assert_eq!(compressed_public_key.len(), 33);
6297
6298		let trampoline_packet = TrampolineOnionPacket {
6299			version: 0,
6300			public_key,
6301			hop_data: vec![1; 650], // this should be the standard encoded length
6302			hmac: [2; 32],
6303		};
6304		let encoded_trampoline_packet = trampoline_packet.encode();
6305		assert_eq!(encoded_trampoline_packet.len(), 716);
6306
6307		{
6308			// verify that a codec round trip works
6309			let decoded_trampoline_packet: TrampolineOnionPacket =
6310				<TrampolineOnionPacket as LengthReadable>::read_from_fixed_length_buffer(
6311					&mut &encoded_trampoline_packet[..],
6312				)
6313				.unwrap();
6314			assert_eq!(decoded_trampoline_packet.encode(), encoded_trampoline_packet);
6315		}
6316
6317		let msg = msgs::OutboundOnionPayload::TrampolineEntrypoint {
6318			multipath_trampoline_data: None,
6319			amt_to_forward: 0x0badf00d01020304,
6320			outgoing_cltv_value: 0xffffffff,
6321			trampoline_packet,
6322		};
6323		let encoded_payload = msg.encode();
6324
6325		let trampoline_type_bytes = &encoded_payload[19..=19];
6326		let mut trampoline_type_cursor = Cursor::new(trampoline_type_bytes);
6327		let trampoline_type_big_size: BigSize =
6328			Readable::read(&mut trampoline_type_cursor).unwrap();
6329		assert_eq!(trampoline_type_big_size.0, 20);
6330
6331		let trampoline_length_bytes = &encoded_payload[20..=22];
6332		let mut trampoline_length_cursor = Cursor::new(trampoline_length_bytes);
6333		let trampoline_length_big_size: BigSize =
6334			Readable::read(&mut trampoline_length_cursor).unwrap();
6335		assert_eq!(trampoline_length_big_size.0, encoded_trampoline_packet.len() as u64);
6336	}
6337
6338	#[test]
6339	fn encoding_final_onion_hop_data_with_eclair_trampoline_packet() {
6340		let public_key = PublicKey::from_slice(
6341			&<Vec<u8>>::from_hex(
6342				"02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6343			)
6344			.unwrap(),
6345		)
6346		.unwrap();
6347		let hop_data = <Vec<u8>>::from_hex("cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4c").unwrap();
6348		let hmac_vector =
6349			<Vec<u8>>::from_hex("bb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c")
6350				.unwrap();
6351		let mut hmac = [0; 32];
6352		hmac.copy_from_slice(&hmac_vector);
6353
6354		let compressed_public_key = public_key.serialize();
6355		assert_eq!(compressed_public_key.len(), 33);
6356
6357		let trampoline_packet = TrampolineOnionPacket { version: 0, public_key, hop_data, hmac };
6358		let encoded_trampoline_packet = trampoline_packet.encode();
6359		let expected_eclair_trampoline_packet = <Vec<u8>>::from_hex("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4cbb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c").unwrap();
6360		assert_eq!(encoded_trampoline_packet, expected_eclair_trampoline_packet);
6361	}
6362
6363	#[test]
6364	fn encoding_outbound_trampoline_payload() {
6365		let mut trampoline_features = Bolt12InvoiceFeatures::empty();
6366		trampoline_features.set_basic_mpp_optional();
6367		let introduction_node = PublicKey::from_slice(
6368			&<Vec<u8>>::from_hex(
6369				"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",
6370			)
6371			.unwrap(),
6372		)
6373		.unwrap();
6374		let blinding_point = PublicKey::from_slice(
6375			&<Vec<u8>>::from_hex(
6376				"02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6377			)
6378			.unwrap(),
6379		)
6380		.unwrap();
6381		let trampoline_payload = OutboundTrampolinePayload::LegacyBlindedPathEntry {
6382			amt_to_forward: 150_000_000,
6383			outgoing_cltv_value: 800_000,
6384			payment_paths: vec![BlindedPaymentPath::from_blinded_path_and_payinfo(
6385				introduction_node,
6386				blinding_point,
6387				vec![],
6388				BlindedPayInfo {
6389					fee_base_msat: 500,
6390					fee_proportional_millionths: 1_000,
6391					cltv_expiry_delta: 36,
6392					htlc_minimum_msat: 1,
6393					htlc_maximum_msat: 500_000_000,
6394					features: BlindedHopFeatures::empty(),
6395				},
6396			)],
6397			invoice_features: Some(trampoline_features),
6398		};
6399		let serialized_payload = trampoline_payload.encode().to_lower_hex_string();
6400		assert_eq!(serialized_payload, "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000");
6401	}
6402
6403	#[test]
6404	fn encode_trampoline_blinded_path_payload() {
6405		let trampoline_payload_eve = OutboundTrampolinePayload::BlindedReceive {
6406			sender_intended_htlc_amt_msat: 150_000_000,
6407			total_msat: 150_000_000,
6408			cltv_expiry_height: 800_000,
6409			encrypted_tlvs: &<Vec<u8>>::from_hex("bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c").unwrap(),
6410			intro_node_blinding_point: None,
6411			keysend_preimage: None,
6412			custom_tlvs: &vec![],
6413		};
6414		let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string();
6415		assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180");
6416
6417		let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward {
6418			encrypted_tlvs: &<Vec<u8>>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(),
6419			intro_node_blinding_point: Some(PublicKey::from_slice(&<Vec<u8>>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap()),
6420		};
6421		let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string();
6422		assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e")
6423	}
6424
6425	#[test]
6426	fn query_channel_range_end_blocknum() {
6427		let tests: Vec<(u32, u32, u32)> =
6428			vec![(10000, 1500, 11500), (0, 0xffffffff, 0xffffffff), (1, 0xffffffff, 0xffffffff)];
6429
6430		for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
6431			let sut = msgs::QueryChannelRange {
6432				chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6433				first_blocknum,
6434				number_of_blocks,
6435			};
6436			assert_eq!(sut.end_blocknum(), expected);
6437		}
6438	}
6439
6440	#[test]
6441	fn encoding_query_channel_range() {
6442		let mut query_channel_range = msgs::QueryChannelRange {
6443			chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6444			first_blocknum: 100000,
6445			number_of_blocks: 1500,
6446		};
6447		let encoded_value = query_channel_range.encode();
6448		let target_value = <Vec<u8>>::from_hex(
6449			"06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000186a0000005dc",
6450		)
6451		.unwrap();
6452		assert_eq!(encoded_value, target_value);
6453
6454		query_channel_range =
6455			LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6456		assert_eq!(query_channel_range.first_blocknum, 100000);
6457		assert_eq!(query_channel_range.number_of_blocks, 1500);
6458	}
6459
6460	#[test]
6461	fn encoding_reply_channel_range() {
6462		do_encoding_reply_channel_range(0);
6463		do_encoding_reply_channel_range(1);
6464	}
6465
6466	fn do_encoding_reply_channel_range(encoding_type: u8) {
6467		let mut target_value = <Vec<u8>>::from_hex(
6468			"06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000b8a06000005dc01",
6469		)
6470		.unwrap();
6471		let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6472		let mut reply_channel_range = msgs::ReplyChannelRange {
6473			chain_hash: expected_chain_hash,
6474			first_blocknum: 756230,
6475			number_of_blocks: 1500,
6476			sync_complete: true,
6477			short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6478		};
6479
6480		if encoding_type == 0 {
6481			target_value.append(
6482				&mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6483					.unwrap(),
6484			);
6485			let encoded_value = reply_channel_range.encode();
6486			assert_eq!(encoded_value, target_value);
6487
6488			reply_channel_range =
6489				LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6490			assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
6491			assert_eq!(reply_channel_range.first_blocknum, 756230);
6492			assert_eq!(reply_channel_range.number_of_blocks, 1500);
6493			assert_eq!(reply_channel_range.sync_complete, true);
6494			assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
6495			assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
6496			assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
6497		} else {
6498			target_value.append(
6499				&mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6500					.unwrap(),
6501			);
6502			let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> =
6503				LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6504			assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6505		}
6506	}
6507
6508	#[test]
6509	fn encoding_query_short_channel_ids() {
6510		do_encoding_query_short_channel_ids(0);
6511		do_encoding_query_short_channel_ids(1);
6512	}
6513
6514	fn do_encoding_query_short_channel_ids(encoding_type: u8) {
6515		let mut target_value =
6516			<Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f")
6517				.unwrap();
6518		let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6519		let mut query_short_channel_ids = msgs::QueryShortChannelIds {
6520			chain_hash: expected_chain_hash,
6521			short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6522		};
6523
6524		if encoding_type == 0 {
6525			target_value.append(
6526				&mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6527					.unwrap(),
6528			);
6529			let encoded_value = query_short_channel_ids.encode();
6530			assert_eq!(encoded_value, target_value);
6531
6532			query_short_channel_ids =
6533				LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6534			assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
6535			assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
6536			assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
6537			assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
6538		} else {
6539			target_value.append(
6540				&mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6541					.unwrap(),
6542			);
6543			let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> =
6544				LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6545			assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6546		}
6547	}
6548
6549	#[test]
6550	fn encoding_reply_short_channel_ids_end() {
6551		let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6552		let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
6553			chain_hash: expected_chain_hash,
6554			full_information: true,
6555		};
6556		let encoded_value = reply_short_channel_ids_end.encode();
6557		let target_value = <Vec<u8>>::from_hex(
6558			"06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f01",
6559		)
6560		.unwrap();
6561		assert_eq!(encoded_value, target_value);
6562
6563		reply_short_channel_ids_end =
6564			LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6565		assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
6566		assert_eq!(reply_short_channel_ids_end.full_information, true);
6567	}
6568
6569	#[test]
6570	fn encoding_gossip_timestamp_filter() {
6571		let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6572		let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
6573			chain_hash: expected_chain_hash,
6574			first_timestamp: 1590000000,
6575			timestamp_range: 0xffff_ffff,
6576		};
6577		let encoded_value = gossip_timestamp_filter.encode();
6578		let target_value = <Vec<u8>>::from_hex(
6579			"06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f5ec57980ffffffff",
6580		)
6581		.unwrap();
6582		assert_eq!(encoded_value, target_value);
6583
6584		gossip_timestamp_filter =
6585			LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6586		assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
6587		assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
6588		assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
6589	}
6590
6591	#[test]
6592	fn decode_onion_hop_data_len_as_bigsize() {
6593		// Tests that we can decode an onion payload that is >253 bytes.
6594		// Previously, receiving a payload of this size could've caused us to fail to decode a valid
6595		// payload, because we were decoding the length (a BigSize, big-endian) as a VarInt
6596		// (little-endian).
6597
6598		// Encode a test onion payload with a big custom TLV such that it's >253 bytes, forcing the
6599		// payload length to be encoded over multiple bytes rather than a single u8.
6600		let big_payload = encode_big_payload().unwrap();
6601		let mut rd = Cursor::new(&big_payload[..]);
6602
6603		let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6604		<msgs::InboundOnionPayload as ReadableArgs<(
6605			Option<PublicKey>,
6606			&test_utils::TestKeysInterface,
6607		)>>::read(&mut rd, (None, &&node_signer))
6608		.unwrap();
6609	}
6610	// see above test, needs to be a separate method for use of the serialization macros.
6611	fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
6612		use crate::util::ser::HighZeroBytesDroppedBigSize;
6613		let payload = msgs::OutboundOnionPayload::Forward {
6614			short_channel_id: 0xdeadbeef1bad1dea,
6615			amt_to_forward: 1000,
6616			outgoing_cltv_value: 0xffffffff,
6617		};
6618		let mut encoded_payload = Vec::new();
6619		let test_bytes = vec![42u8; 1000];
6620		if let msgs::OutboundOnionPayload::Forward {
6621			short_channel_id,
6622			amt_to_forward,
6623			outgoing_cltv_value,
6624		} = payload
6625		{
6626			_encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
6627				(1, &test_bytes, required_vec),
6628				(2, HighZeroBytesDroppedBigSize(amt_to_forward), required),
6629				(4, HighZeroBytesDroppedBigSize(outgoing_cltv_value), required),
6630				(6, short_channel_id, required)
6631			});
6632		}
6633		Ok(encoded_payload)
6634	}
6635
6636	#[test]
6637	#[cfg(feature = "std")]
6638	fn test_socket_address_from_str() {
6639		let tcpip_v4 =
6640			SocketAddress::TcpIpV4 { addr: Ipv4Addr::new(127, 0, 0, 1).octets(), port: 1234 };
6641		assert_eq!(tcpip_v4, SocketAddress::from_str("127.0.0.1:1234").unwrap());
6642		assert_eq!(tcpip_v4, SocketAddress::from_str(&tcpip_v4.to_string()).unwrap());
6643
6644		let tcpip_v6 = SocketAddress::TcpIpV6 {
6645			addr: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).octets(),
6646			port: 1234,
6647		};
6648		assert_eq!(tcpip_v6, SocketAddress::from_str("[0:0:0:0:0:0:0:1]:1234").unwrap());
6649		assert_eq!(tcpip_v6, SocketAddress::from_str(&tcpip_v6.to_string()).unwrap());
6650
6651		let hostname = SocketAddress::Hostname {
6652			hostname: Hostname::try_from("lightning-node.mydomain.com".to_string()).unwrap(),
6653			port: 1234,
6654		};
6655		assert_eq!(hostname, SocketAddress::from_str("lightning-node.mydomain.com:1234").unwrap());
6656		assert_eq!(hostname, SocketAddress::from_str(&hostname.to_string()).unwrap());
6657
6658		let onion_v2 = SocketAddress::OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7]);
6659		assert_eq!(
6660			"OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7])",
6661			&onion_v2.to_string()
6662		);
6663		assert_eq!(
6664			Err(SocketAddressParseError::InvalidOnionV3),
6665			SocketAddress::from_str("FACEBOOKCOREWWWI.onion:9735")
6666		);
6667
6668		let onion_v3 = SocketAddress::OnionV3 {
6669			ed25519_pubkey: [
6670				121, 188, 198, 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247,
6671				246, 85, 111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31,
6672			],
6673			checksum: 8519,
6674			version: 3,
6675			port: 1234,
6676		};
6677		let onion_v3_str = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:1234";
6678		let parsed = SocketAddress::from_str(onion_v3_str).unwrap();
6679		assert_eq!(onion_v3, parsed);
6680		assert_eq!(onion_v3_str, parsed.to_string());
6681		match parsed {
6682			SocketAddress::OnionV3 { version, .. } => assert_eq!(version, 3),
6683			_ => panic!("expected OnionV3"),
6684		}
6685
6686		assert_eq!(
6687			Err(SocketAddressParseError::InvalidOnionV3),
6688			SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6.onion:1234")
6689		);
6690		assert_eq!(
6691			Err(SocketAddressParseError::InvalidInput),
6692			SocketAddress::from_str("127.0.0.1@1234")
6693		);
6694		assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::<SocketAddress>());
6695		assert!(SocketAddress::from_str(
6696			"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94"
6697		)
6698		.is_err());
6699		assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err());
6700		assert_eq!(
6701			Err(SocketAddressParseError::InvalidPort),
6702			SocketAddress::from_str("example.com:wrong")
6703		);
6704		assert!("localhost".parse::<SocketAddress>().is_err());
6705		assert!("localhost:invalid-port".parse::<SocketAddress>().is_err());
6706		assert!("invalid-onion-v3-hostname.onion:8080".parse::<SocketAddress>().is_err());
6707		assert!("b32.example.onion:invalid-port".parse::<SocketAddress>().is_err());
6708		assert!("invalid-address".parse::<SocketAddress>().is_err());
6709		assert!(SocketAddress::from_str(
6710			"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234"
6711		)
6712		.is_err());
6713	}
6714
6715	#[test]
6716	#[cfg(feature = "std")]
6717	fn test_socket_address_to_socket_addrs() {
6718		assert_eq!(
6719			SocketAddress::TcpIpV4 { addr: [0u8; 4], port: 1337 }
6720				.to_socket_addrs()
6721				.unwrap()
6722				.next()
6723				.unwrap(),
6724			SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 1337))
6725		);
6726		assert_eq!(
6727			SocketAddress::TcpIpV6 { addr: [0u8; 16], port: 1337 }
6728				.to_socket_addrs()
6729				.unwrap()
6730				.next()
6731				.unwrap(),
6732			SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from([0u8; 16]), 1337, 0, 0))
6733		);
6734		assert_eq!(
6735			SocketAddress::Hostname {
6736				hostname: Hostname::try_from("0.0.0.0".to_string()).unwrap(),
6737				port: 0,
6738			}
6739			.to_socket_addrs()
6740			.unwrap()
6741			.next()
6742			.unwrap(),
6743			SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from([0u8; 4]), 0))
6744		);
6745		assert!(SocketAddress::OnionV2([0u8; 12]).to_socket_addrs().is_err());
6746		assert!(SocketAddress::OnionV3 {
6747			ed25519_pubkey: [
6748				37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85, 111,
6749				177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3
6750			],
6751			checksum: 48326,
6752			version: 121,
6753			port: 1234
6754		}
6755		.to_socket_addrs()
6756		.is_err());
6757	}
6758}