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