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