4a0b58937ea46cf7624f15b4eaba6fb564d5accb
[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::secp256k1::PublicKey;
28 use bitcoin::secp256k1::ecdsa::Signature;
29 use bitcoin::secp256k1;
30 use bitcoin::blockdata::script::Script;
31 use bitcoin::hash_types::{Txid, BlockHash};
32
33 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
34 use crate::ln::onion_utils;
35 use crate::onion_message;
36
37 use crate::prelude::*;
38 use core::fmt;
39 use core::fmt::Debug;
40 use crate::io::{self, Read};
41 use crate::io_extras::read_to_end;
42
43 use crate::util::events::{MessageSendEventsProvider, OnionMessageProvider};
44 use crate::util::logger;
45 use crate::util::ser::{LengthReadable, Readable, ReadableArgs, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname};
46
47 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
48
49 /// 21 million * 10^8 * 1000
50 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
51
52 /// An error in decoding a message or struct.
53 #[derive(Clone, Debug, PartialEq, Eq)]
54 pub enum DecodeError {
55         /// A version byte specified something we don't know how to handle.
56         /// Includes unknown realm byte in an OnionHopData packet
57         UnknownVersion,
58         /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type)
59         UnknownRequiredFeature,
60         /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
61         /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was
62         /// syntactically incorrect, etc
63         InvalidValue,
64         /// Buffer too short
65         ShortRead,
66         /// A length descriptor in the packet didn't describe the later data correctly
67         BadLengthDescriptor,
68         /// Error from std::io
69         Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping
70         io::ErrorKind),
71         /// The message included zlib-compressed values, which we don't support.
72         UnsupportedCompression,
73 }
74
75 /// An init message to be sent or received from a peer
76 #[derive(Clone, Debug, PartialEq, Eq)]
77 pub struct Init {
78         /// The relevant features which the sender supports
79         pub features: InitFeatures,
80         /// The receipient's network address. This adds the option to report a remote IP address
81         /// back to a connecting peer using the init message. A node can decide to use that information
82         /// to discover a potential update to its public IPv4 address (NAT) and use
83         /// that for a node_announcement update message containing the new address.
84         pub remote_network_address: Option<NetAddress>,
85 }
86
87 /// An error message to be sent or received from a peer
88 #[derive(Clone, Debug, PartialEq, Eq)]
89 pub struct ErrorMessage {
90         /// The channel ID involved in the error.
91         ///
92         /// All-0s indicates a general error unrelated to a specific channel, after which all channels
93         /// with the sending peer should be closed.
94         pub channel_id: [u8; 32],
95         /// A possibly human-readable error description.
96         /// The string should be sanitized before it is used (e.g. emitted to logs or printed to
97         /// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in
98         /// the terminal emulator or the logging subsystem.
99         pub data: String,
100 }
101
102 /// A warning message to be sent or received from a peer
103 #[derive(Clone, Debug, PartialEq, Eq)]
104 pub struct WarningMessage {
105         /// The channel ID involved in the warning.
106         ///
107         /// All-0s indicates a warning unrelated to a specific channel.
108         pub channel_id: [u8; 32],
109         /// A possibly human-readable warning description.
110         /// The string should be sanitized before it is used (e.g. emitted to logs or printed to
111         /// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in
112         /// the terminal emulator or the logging subsystem.
113         pub data: String,
114 }
115
116 /// A ping message to be sent or received from a peer
117 #[derive(Clone, Debug, PartialEq, Eq)]
118 pub struct Ping {
119         /// The desired response length
120         pub ponglen: u16,
121         /// The ping packet size.
122         /// This field is not sent on the wire. byteslen zeros are sent.
123         pub byteslen: u16,
124 }
125
126 /// A pong message to be sent or received from a peer
127 #[derive(Clone, Debug, PartialEq, Eq)]
128 pub struct Pong {
129         /// The pong packet size.
130         /// This field is not sent on the wire. byteslen zeros are sent.
131         pub byteslen: u16,
132 }
133
134 /// An open_channel message to be sent or received from a peer
135 #[derive(Clone, Debug, PartialEq, Eq)]
136 pub struct OpenChannel {
137         /// The genesis hash of the blockchain where the channel is to be opened
138         pub chain_hash: BlockHash,
139         /// A temporary channel ID, until the funding outpoint is announced
140         pub temporary_channel_id: [u8; 32],
141         /// The channel value
142         pub funding_satoshis: u64,
143         /// The amount to push to the counterparty as part of the open, in milli-satoshi
144         pub push_msat: u64,
145         /// The threshold below which outputs on transactions broadcast by sender will be omitted
146         pub dust_limit_satoshis: u64,
147         /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
148         pub max_htlc_value_in_flight_msat: u64,
149         /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
150         pub channel_reserve_satoshis: u64,
151         /// The minimum HTLC size incoming to sender, in milli-satoshi
152         pub htlc_minimum_msat: u64,
153         /// The feerate per 1000-weight of sender generated transactions, until updated by update_fee
154         pub feerate_per_kw: u32,
155         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
156         pub to_self_delay: u16,
157         /// The maximum number of inbound HTLCs towards sender
158         pub max_accepted_htlcs: u16,
159         /// The sender's key controlling the funding transaction
160         pub funding_pubkey: PublicKey,
161         /// Used to derive a revocation key for transactions broadcast by counterparty
162         pub revocation_basepoint: PublicKey,
163         /// A payment key to sender for transactions broadcast by counterparty
164         pub payment_point: PublicKey,
165         /// Used to derive a payment key to sender for transactions broadcast by sender
166         pub delayed_payment_basepoint: PublicKey,
167         /// Used to derive an HTLC payment key to sender
168         pub htlc_basepoint: PublicKey,
169         /// The first to-be-broadcast-by-sender transaction's per commitment point
170         pub first_per_commitment_point: PublicKey,
171         /// Channel flags
172         pub channel_flags: u8,
173         /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
174         pub shutdown_scriptpubkey: OptionalField<Script>,
175         /// The channel type that this channel will represent. If none is set, we derive the channel
176         /// type from the intersection of our feature bits with our counterparty's feature bits from
177         /// the Init message.
178         pub channel_type: Option<ChannelTypeFeatures>,
179 }
180
181 /// An accept_channel message to be sent or received from a peer
182 #[derive(Clone, Debug, PartialEq, Eq)]
183 pub struct AcceptChannel {
184         /// A temporary channel ID, until the funding outpoint is announced
185         pub temporary_channel_id: [u8; 32],
186         /// The threshold below which outputs on transactions broadcast by sender will be omitted
187         pub dust_limit_satoshis: u64,
188         /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
189         pub max_htlc_value_in_flight_msat: u64,
190         /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
191         pub channel_reserve_satoshis: u64,
192         /// The minimum HTLC size incoming to sender, in milli-satoshi
193         pub htlc_minimum_msat: u64,
194         /// Minimum depth of the funding transaction before the channel is considered open
195         pub minimum_depth: u32,
196         /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
197         pub to_self_delay: u16,
198         /// The maximum number of inbound HTLCs towards sender
199         pub max_accepted_htlcs: u16,
200         /// The sender's key controlling the funding transaction
201         pub funding_pubkey: PublicKey,
202         /// Used to derive a revocation key for transactions broadcast by counterparty
203         pub revocation_basepoint: PublicKey,
204         /// A payment key to sender for transactions broadcast by counterparty
205         pub payment_point: PublicKey,
206         /// Used to derive a payment key to sender for transactions broadcast by sender
207         pub delayed_payment_basepoint: PublicKey,
208         /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
209         pub htlc_basepoint: PublicKey,
210         /// The first to-be-broadcast-by-sender transaction's per commitment point
211         pub first_per_commitment_point: PublicKey,
212         /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
213         pub shutdown_scriptpubkey: OptionalField<Script>,
214         /// The channel type that this channel will represent. If none is set, we derive the channel
215         /// type from the intersection of our feature bits with our counterparty's feature bits from
216         /// the Init message.
217         ///
218         /// This is required to match the equivalent field in [`OpenChannel::channel_type`].
219         pub channel_type: Option<ChannelTypeFeatures>,
220 }
221
222 /// A funding_created message to be sent or received from a peer
223 #[derive(Clone, Debug, PartialEq, Eq)]
224 pub struct FundingCreated {
225         /// A temporary channel ID, until the funding is established
226         pub temporary_channel_id: [u8; 32],
227         /// The funding transaction ID
228         pub funding_txid: Txid,
229         /// The specific output index funding this channel
230         pub funding_output_index: u16,
231         /// The signature of the channel initiator (funder) on the initial commitment transaction
232         pub signature: Signature,
233 }
234
235 /// A funding_signed message to be sent or received from a peer
236 #[derive(Clone, Debug, PartialEq, Eq)]
237 pub struct FundingSigned {
238         /// The channel ID
239         pub channel_id: [u8; 32],
240         /// The signature of the channel acceptor (fundee) on the initial commitment transaction
241         pub signature: Signature,
242 }
243
244 /// A channel_ready message to be sent or received from a peer
245 #[derive(Clone, Debug, PartialEq, Eq)]
246 pub struct ChannelReady {
247         /// The channel ID
248         pub channel_id: [u8; 32],
249         /// The per-commitment point of the second commitment transaction
250         pub next_per_commitment_point: PublicKey,
251         /// If set, provides a short_channel_id alias for this channel. The sender will accept payments
252         /// to be forwarded over this SCID and forward them to this messages' recipient.
253         pub short_channel_id_alias: Option<u64>,
254 }
255
256 /// A shutdown message to be sent or received from a peer
257 #[derive(Clone, Debug, PartialEq, Eq)]
258 pub struct Shutdown {
259         /// The channel ID
260         pub channel_id: [u8; 32],
261         /// The destination of this peer's funds on closing.
262         /// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh.
263         pub scriptpubkey: Script,
264 }
265
266 /// The minimum and maximum fees which the sender is willing to place on the closing transaction.
267 /// This is provided in [`ClosingSigned`] by both sides to indicate the fee range they are willing
268 /// to use.
269 #[derive(Clone, Debug, PartialEq, Eq)]
270 pub struct ClosingSignedFeeRange {
271         /// The minimum absolute fee, in satoshis, which the sender is willing to place on the closing
272         /// transaction.
273         pub min_fee_satoshis: u64,
274         /// The maximum absolute fee, in satoshis, which the sender is willing to place on the closing
275         /// transaction.
276         pub max_fee_satoshis: u64,
277 }
278
279 /// A closing_signed message to be sent or received from a peer
280 #[derive(Clone, Debug, PartialEq, Eq)]
281 pub struct ClosingSigned {
282         /// The channel ID
283         pub channel_id: [u8; 32],
284         /// The proposed total fee for the closing transaction
285         pub fee_satoshis: u64,
286         /// A signature on the closing transaction
287         pub signature: Signature,
288         /// The minimum and maximum fees which the sender is willing to accept, provided only by new
289         /// nodes.
290         pub fee_range: Option<ClosingSignedFeeRange>,
291 }
292
293 /// An update_add_htlc message to be sent or received from a peer
294 #[derive(Clone, Debug, PartialEq, Eq)]
295 pub struct UpdateAddHTLC {
296         /// The channel ID
297         pub channel_id: [u8; 32],
298         /// The HTLC ID
299         pub htlc_id: u64,
300         /// The HTLC value in milli-satoshi
301         pub amount_msat: u64,
302         /// The payment hash, the pre-image of which controls HTLC redemption
303         pub payment_hash: PaymentHash,
304         /// The expiry height of the HTLC
305         pub cltv_expiry: u32,
306         pub(crate) onion_routing_packet: OnionPacket,
307 }
308
309  /// An onion message to be sent or received from a peer
310 #[derive(Clone, Debug, PartialEq, Eq)]
311 pub struct OnionMessage {
312         /// Used in decrypting the onion packet's payload.
313         pub blinding_point: PublicKey,
314         pub(crate) onion_routing_packet: onion_message::Packet,
315 }
316
317 /// An update_fulfill_htlc message to be sent or received from a peer
318 #[derive(Clone, Debug, PartialEq, Eq)]
319 pub struct UpdateFulfillHTLC {
320         /// The channel ID
321         pub channel_id: [u8; 32],
322         /// The HTLC ID
323         pub htlc_id: u64,
324         /// The pre-image of the payment hash, allowing HTLC redemption
325         pub payment_preimage: PaymentPreimage,
326 }
327
328 /// An update_fail_htlc message to be sent or received from a peer
329 #[derive(Clone, Debug, PartialEq, Eq)]
330 pub struct UpdateFailHTLC {
331         /// The channel ID
332         pub channel_id: [u8; 32],
333         /// The HTLC ID
334         pub htlc_id: u64,
335         pub(crate) reason: OnionErrorPacket,
336 }
337
338 /// An update_fail_malformed_htlc message to be sent or received from a peer
339 #[derive(Clone, Debug, PartialEq, Eq)]
340 pub struct UpdateFailMalformedHTLC {
341         /// The channel ID
342         pub channel_id: [u8; 32],
343         /// The HTLC ID
344         pub htlc_id: u64,
345         pub(crate) sha256_of_onion: [u8; 32],
346         /// The failure code
347         pub failure_code: u16,
348 }
349
350 /// A commitment_signed message to be sent or received from a peer
351 #[derive(Clone, Debug, PartialEq, Eq)]
352 pub struct CommitmentSigned {
353         /// The channel ID
354         pub channel_id: [u8; 32],
355         /// A signature on the commitment transaction
356         pub signature: Signature,
357         /// Signatures on the HTLC transactions
358         pub htlc_signatures: Vec<Signature>,
359 }
360
361 /// A revoke_and_ack message to be sent or received from a peer
362 #[derive(Clone, Debug, PartialEq, Eq)]
363 pub struct RevokeAndACK {
364         /// The channel ID
365         pub channel_id: [u8; 32],
366         /// The secret corresponding to the per-commitment point
367         pub per_commitment_secret: [u8; 32],
368         /// The next sender-broadcast commitment transaction's per-commitment point
369         pub next_per_commitment_point: PublicKey,
370 }
371
372 /// An update_fee message to be sent or received from a peer
373 #[derive(Clone, Debug, PartialEq, Eq)]
374 pub struct UpdateFee {
375         /// The channel ID
376         pub channel_id: [u8; 32],
377         /// Fee rate per 1000-weight of the transaction
378         pub feerate_per_kw: u32,
379 }
380
381 #[derive(Clone, Debug, PartialEq, Eq)]
382 /// Proof that the sender knows the per-commitment secret of the previous commitment transaction.
383 /// This is used to convince the recipient that the channel is at a certain commitment
384 /// number even if they lost that data due to a local failure.  Of course, the peer may lie
385 /// and even later commitments may have been revoked.
386 pub struct DataLossProtect {
387         /// Proof that the sender knows the per-commitment secret of a specific commitment transaction
388         /// belonging to the recipient
389         pub your_last_per_commitment_secret: [u8; 32],
390         /// The sender's per-commitment point for their current commitment transaction
391         pub my_current_per_commitment_point: PublicKey,
392 }
393
394 /// A channel_reestablish message to be sent or received from a peer
395 #[derive(Clone, Debug, PartialEq, Eq)]
396 pub struct ChannelReestablish {
397         /// The channel ID
398         pub channel_id: [u8; 32],
399         /// The next commitment number for the sender
400         pub next_local_commitment_number: u64,
401         /// The next commitment number for the recipient
402         pub next_remote_commitment_number: u64,
403         /// Optionally, a field proving that next_remote_commitment_number-1 has been revoked
404         pub data_loss_protect: OptionalField<DataLossProtect>,
405 }
406
407 /// An announcement_signatures message to be sent or received from a peer
408 #[derive(Clone, Debug, PartialEq, Eq)]
409 pub struct AnnouncementSignatures {
410         /// The channel ID
411         pub channel_id: [u8; 32],
412         /// The short channel ID
413         pub short_channel_id: u64,
414         /// A signature by the node key
415         pub node_signature: Signature,
416         /// A signature by the funding key
417         pub bitcoin_signature: Signature,
418 }
419
420 /// An address which can be used to connect to a remote peer
421 #[derive(Clone, Debug, PartialEq, Eq)]
422 pub enum NetAddress {
423         /// An IPv4 address/port on which the peer is listening.
424         IPv4 {
425                 /// The 4-byte IPv4 address
426                 addr: [u8; 4],
427                 /// The port on which the node is listening
428                 port: u16,
429         },
430         /// An IPv6 address/port on which the peer is listening.
431         IPv6 {
432                 /// The 16-byte IPv6 address
433                 addr: [u8; 16],
434                 /// The port on which the node is listening
435                 port: u16,
436         },
437         /// An old-style Tor onion address/port on which the peer is listening.
438         ///
439         /// This field is deprecated and the Tor network generally no longer supports V2 Onion
440         /// addresses. Thus, the details are not parsed here.
441         OnionV2([u8; 12]),
442         /// A new-style Tor onion address/port on which the peer is listening.
443         /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
444         /// wrap as base32 and append ".onion".
445         OnionV3 {
446                 /// The ed25519 long-term public key of the peer
447                 ed25519_pubkey: [u8; 32],
448                 /// The checksum of the pubkey and version, as included in the onion address
449                 checksum: u16,
450                 /// The version byte, as defined by the Tor Onion v3 spec.
451                 version: u8,
452                 /// The port on which the node is listening
453                 port: u16,
454         },
455         /// A hostname/port on which the peer is listening.
456         Hostname {
457                 /// The hostname on which the node is listening.
458                 hostname: Hostname,
459                 /// The port on which the node is listening.
460                 port: u16,
461         },
462 }
463 impl NetAddress {
464         /// Gets the ID of this address type. Addresses in node_announcement messages should be sorted
465         /// by this.
466         pub(crate) fn get_id(&self) -> u8 {
467                 match self {
468                         &NetAddress::IPv4 {..} => { 1 },
469                         &NetAddress::IPv6 {..} => { 2 },
470                         &NetAddress::OnionV2(_) => { 3 },
471                         &NetAddress::OnionV3 {..} => { 4 },
472                         &NetAddress::Hostname {..} => { 5 },
473                 }
474         }
475
476         /// Strict byte-length of address descriptor, 1-byte type not recorded
477         fn len(&self) -> u16 {
478                 match self {
479                         &NetAddress::IPv4 { .. } => { 6 },
480                         &NetAddress::IPv6 { .. } => { 18 },
481                         &NetAddress::OnionV2(_) => { 12 },
482                         &NetAddress::OnionV3 { .. } => { 37 },
483                         // Consists of 1-byte hostname length, hostname bytes, and 2-byte port.
484                         &NetAddress::Hostname { ref hostname, .. } => { u16::from(hostname.len()) + 3 },
485                 }
486         }
487
488         /// The maximum length of any address descriptor, not including the 1-byte type.
489         /// This maximum length is reached by a hostname address descriptor:
490         /// a hostname with a maximum length of 255, its 1-byte length and a 2-byte port.
491         pub(crate) const MAX_LEN: u16 = 258;
492 }
493
494 impl Writeable for NetAddress {
495         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
496                 match self {
497                         &NetAddress::IPv4 { ref addr, ref port } => {
498                                 1u8.write(writer)?;
499                                 addr.write(writer)?;
500                                 port.write(writer)?;
501                         },
502                         &NetAddress::IPv6 { ref addr, ref port } => {
503                                 2u8.write(writer)?;
504                                 addr.write(writer)?;
505                                 port.write(writer)?;
506                         },
507                         &NetAddress::OnionV2(bytes) => {
508                                 3u8.write(writer)?;
509                                 bytes.write(writer)?;
510                         },
511                         &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
512                                 4u8.write(writer)?;
513                                 ed25519_pubkey.write(writer)?;
514                                 checksum.write(writer)?;
515                                 version.write(writer)?;
516                                 port.write(writer)?;
517                         },
518                         &NetAddress::Hostname { ref hostname, ref port } => {
519                                 5u8.write(writer)?;
520                                 hostname.write(writer)?;
521                                 port.write(writer)?;
522                         },
523                 }
524                 Ok(())
525         }
526 }
527
528 impl Readable for Result<NetAddress, u8> {
529         fn read<R: Read>(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
530                 let byte = <u8 as Readable>::read(reader)?;
531                 match byte {
532                         1 => {
533                                 Ok(Ok(NetAddress::IPv4 {
534                                         addr: Readable::read(reader)?,
535                                         port: Readable::read(reader)?,
536                                 }))
537                         },
538                         2 => {
539                                 Ok(Ok(NetAddress::IPv6 {
540                                         addr: Readable::read(reader)?,
541                                         port: Readable::read(reader)?,
542                                 }))
543                         },
544                         3 => Ok(Ok(NetAddress::OnionV2(Readable::read(reader)?))),
545                         4 => {
546                                 Ok(Ok(NetAddress::OnionV3 {
547                                         ed25519_pubkey: Readable::read(reader)?,
548                                         checksum: Readable::read(reader)?,
549                                         version: Readable::read(reader)?,
550                                         port: Readable::read(reader)?,
551                                 }))
552                         },
553                         5 => {
554                                 Ok(Ok(NetAddress::Hostname {
555                                         hostname: Readable::read(reader)?,
556                                         port: Readable::read(reader)?,
557                                 }))
558                         },
559                         _ => return Ok(Err(byte)),
560                 }
561         }
562 }
563
564 impl Readable for NetAddress {
565         fn read<R: Read>(reader: &mut R) -> Result<NetAddress, DecodeError> {
566                 match Readable::read(reader) {
567                         Ok(Ok(res)) => Ok(res),
568                         Ok(Err(_)) => Err(DecodeError::UnknownVersion),
569                         Err(e) => Err(e),
570                 }
571         }
572 }
573
574
575 /// The unsigned part of a node_announcement
576 #[derive(Clone, Debug, PartialEq, Eq)]
577 pub struct UnsignedNodeAnnouncement {
578         /// The advertised features
579         pub features: NodeFeatures,
580         /// A strictly monotonic announcement counter, with gaps allowed
581         pub timestamp: u32,
582         /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
583         /// to this node).
584         pub node_id: PublicKey,
585         /// An RGB color for UI purposes
586         pub rgb: [u8; 3],
587         /// An alias, for UI purposes.  This should be sanitized before use.  There is no guarantee
588         /// of uniqueness.
589         pub alias: [u8; 32],
590         /// List of addresses on which this node is reachable
591         pub addresses: Vec<NetAddress>,
592         pub(crate) excess_address_data: Vec<u8>,
593         pub(crate) excess_data: Vec<u8>,
594 }
595 #[derive(Clone, Debug, PartialEq, Eq)]
596 /// A node_announcement message to be sent or received from a peer
597 pub struct NodeAnnouncement {
598         /// The signature by the node key
599         pub signature: Signature,
600         /// The actual content of the announcement
601         pub contents: UnsignedNodeAnnouncement,
602 }
603
604 /// The unsigned part of a channel_announcement
605 #[derive(Clone, Debug, PartialEq, Eq)]
606 pub struct UnsignedChannelAnnouncement {
607         /// The advertised channel features
608         pub features: ChannelFeatures,
609         /// The genesis hash of the blockchain where the channel is to be opened
610         pub chain_hash: BlockHash,
611         /// The short channel ID
612         pub short_channel_id: u64,
613         /// One of the two node_ids which are endpoints of this channel
614         pub node_id_1: PublicKey,
615         /// The other of the two node_ids which are endpoints of this channel
616         pub node_id_2: PublicKey,
617         /// The funding key for the first node
618         pub bitcoin_key_1: PublicKey,
619         /// The funding key for the second node
620         pub bitcoin_key_2: PublicKey,
621         pub(crate) excess_data: Vec<u8>,
622 }
623 /// A channel_announcement message to be sent or received from a peer
624 #[derive(Clone, Debug, PartialEq, Eq)]
625 pub struct ChannelAnnouncement {
626         /// Authentication of the announcement by the first public node
627         pub node_signature_1: Signature,
628         /// Authentication of the announcement by the second public node
629         pub node_signature_2: Signature,
630         /// Proof of funding UTXO ownership by the first public node
631         pub bitcoin_signature_1: Signature,
632         /// Proof of funding UTXO ownership by the second public node
633         pub bitcoin_signature_2: Signature,
634         /// The actual announcement
635         pub contents: UnsignedChannelAnnouncement,
636 }
637
638 /// The unsigned part of a channel_update
639 #[derive(Clone, Debug, PartialEq, Eq)]
640 pub struct UnsignedChannelUpdate {
641         /// The genesis hash of the blockchain where the channel is to be opened
642         pub chain_hash: BlockHash,
643         /// The short channel ID
644         pub short_channel_id: u64,
645         /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
646         pub timestamp: u32,
647         /// Channel flags
648         pub flags: u8,
649         /// The number of blocks such that if:
650         /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta`
651         /// then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines
652         /// the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a
653         /// cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10,
654         /// then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before
655         /// forwarding. Note that the HTLC sender is the one who originally sets this value when
656         /// constructing the route.
657         pub cltv_expiry_delta: u16,
658         /// The minimum HTLC size incoming to sender, in milli-satoshi
659         pub htlc_minimum_msat: u64,
660         /// The maximum HTLC value incoming to sender, in milli-satoshi. Used to be optional.
661         pub htlc_maximum_msat: u64,
662         /// The base HTLC fee charged by sender, in milli-satoshi
663         pub fee_base_msat: u32,
664         /// The amount to fee multiplier, in micro-satoshi
665         pub fee_proportional_millionths: u32,
666         /// Excess data which was signed as a part of the message which we do not (yet) understand how
667         /// to decode. This is stored to ensure forward-compatibility as new fields are added to the
668         /// lightning gossip
669         pub excess_data: Vec<u8>,
670 }
671 /// A channel_update message to be sent or received from a peer
672 #[derive(Clone, Debug, PartialEq, Eq)]
673 pub struct ChannelUpdate {
674         /// A signature of the channel update
675         pub signature: Signature,
676         /// The actual channel update
677         pub contents: UnsignedChannelUpdate,
678 }
679
680 /// A query_channel_range message is used to query a peer for channel
681 /// UTXOs in a range of blocks. The recipient of a query makes a best
682 /// effort to reply to the query using one or more reply_channel_range
683 /// messages.
684 #[derive(Clone, Debug, PartialEq, Eq)]
685 pub struct QueryChannelRange {
686         /// The genesis hash of the blockchain being queried
687         pub chain_hash: BlockHash,
688         /// The height of the first block for the channel UTXOs being queried
689         pub first_blocknum: u32,
690         /// The number of blocks to include in the query results
691         pub number_of_blocks: u32,
692 }
693
694 /// A reply_channel_range message is a reply to a query_channel_range
695 /// message. Multiple reply_channel_range messages can be sent in reply
696 /// to a single query_channel_range message. The query recipient makes a
697 /// best effort to respond based on their local network view which may
698 /// not be a perfect view of the network. The short_channel_ids in the
699 /// reply are encoded. We only support encoding_type=0 uncompressed
700 /// serialization and do not support encoding_type=1 zlib serialization.
701 #[derive(Clone, Debug, PartialEq, Eq)]
702 pub struct ReplyChannelRange {
703         /// The genesis hash of the blockchain being queried
704         pub chain_hash: BlockHash,
705         /// The height of the first block in the range of the reply
706         pub first_blocknum: u32,
707         /// The number of blocks included in the range of the reply
708         pub number_of_blocks: u32,
709         /// True when this is the final reply for a query
710         pub sync_complete: bool,
711         /// The short_channel_ids in the channel range
712         pub short_channel_ids: Vec<u64>,
713 }
714
715 /// A query_short_channel_ids message is used to query a peer for
716 /// routing gossip messages related to one or more short_channel_ids.
717 /// The query recipient will reply with the latest, if available,
718 /// channel_announcement, channel_update and node_announcement messages
719 /// it maintains for the requested short_channel_ids followed by a
720 /// reply_short_channel_ids_end message. The short_channel_ids sent in
721 /// this query are encoded. We only support encoding_type=0 uncompressed
722 /// serialization and do not support encoding_type=1 zlib serialization.
723 #[derive(Clone, Debug, PartialEq, Eq)]
724 pub struct QueryShortChannelIds {
725         /// The genesis hash of the blockchain being queried
726         pub chain_hash: BlockHash,
727         /// The short_channel_ids that are being queried
728         pub short_channel_ids: Vec<u64>,
729 }
730
731 /// A reply_short_channel_ids_end message is sent as a reply to a
732 /// query_short_channel_ids message. The query recipient makes a best
733 /// effort to respond based on their local network view which may not be
734 /// a perfect view of the network.
735 #[derive(Clone, Debug, PartialEq, Eq)]
736 pub struct ReplyShortChannelIdsEnd {
737         /// The genesis hash of the blockchain that was queried
738         pub chain_hash: BlockHash,
739         /// Indicates if the query recipient maintains up-to-date channel
740         /// information for the chain_hash
741         pub full_information: bool,
742 }
743
744 /// A gossip_timestamp_filter message is used by a node to request
745 /// gossip relay for messages in the requested time range when the
746 /// gossip_queries feature has been negotiated.
747 #[derive(Clone, Debug, PartialEq, Eq)]
748 pub struct GossipTimestampFilter {
749         /// The genesis hash of the blockchain for channel and node information
750         pub chain_hash: BlockHash,
751         /// The starting unix timestamp
752         pub first_timestamp: u32,
753         /// The range of information in seconds
754         pub timestamp_range: u32,
755 }
756
757 /// Encoding type for data compression of collections in gossip queries.
758 /// We do not support encoding_type=1 zlib serialization defined in BOLT #7.
759 enum EncodingType {
760         Uncompressed = 0x00,
761 }
762
763 /// Used to put an error message in a LightningError
764 #[derive(Clone, Debug)]
765 pub enum ErrorAction {
766         /// The peer took some action which made us think they were useless. Disconnect them.
767         DisconnectPeer {
768                 /// An error message which we should make an effort to send before we disconnect.
769                 msg: Option<ErrorMessage>
770         },
771         /// The peer did something harmless that we weren't able to process, just log and ignore
772         // New code should *not* use this. New code must use IgnoreAndLog, below!
773         IgnoreError,
774         /// The peer did something harmless that we weren't able to meaningfully process.
775         /// If the error is logged, log it at the given level.
776         IgnoreAndLog(logger::Level),
777         /// The peer provided us with a gossip message which we'd already seen. In most cases this
778         /// should be ignored, but it may result in the message being forwarded if it is a duplicate of
779         /// our own channel announcements.
780         IgnoreDuplicateGossip,
781         /// The peer did something incorrect. Tell them.
782         SendErrorMessage {
783                 /// The message to send.
784                 msg: ErrorMessage,
785         },
786         /// The peer did something incorrect. Tell them without closing any channels.
787         SendWarningMessage {
788                 /// The message to send.
789                 msg: WarningMessage,
790                 /// The peer may have done something harmless that we weren't able to meaningfully process,
791                 /// though we should still tell them about it.
792                 /// If this event is logged, log it at the given level.
793                 log_level: logger::Level,
794         },
795 }
796
797 /// An Err type for failure to process messages.
798 #[derive(Clone, Debug)]
799 pub struct LightningError {
800         /// A human-readable message describing the error
801         pub err: String,
802         /// The action which should be taken against the offending peer.
803         pub action: ErrorAction,
804 }
805
806 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
807 /// transaction updates if they were pending.
808 #[derive(Clone, Debug, PartialEq, Eq)]
809 pub struct CommitmentUpdate {
810         /// update_add_htlc messages which should be sent
811         pub update_add_htlcs: Vec<UpdateAddHTLC>,
812         /// update_fulfill_htlc messages which should be sent
813         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
814         /// update_fail_htlc messages which should be sent
815         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
816         /// update_fail_malformed_htlc messages which should be sent
817         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
818         /// An update_fee message which should be sent
819         pub update_fee: Option<UpdateFee>,
820         /// Finally, the commitment_signed message which should be sent
821         pub commitment_signed: CommitmentSigned,
822 }
823
824 /// Messages could have optional fields to use with extended features
825 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
826 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
827 /// separate enum type for them.
828 /// (C-not exported) due to a free generic in T
829 #[derive(Clone, Debug, PartialEq, Eq)]
830 pub enum OptionalField<T> {
831         /// Optional field is included in message
832         Present(T),
833         /// Optional field is absent in message
834         Absent
835 }
836
837 /// A trait to describe an object which can receive channel messages.
838 ///
839 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
840 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
841 pub trait ChannelMessageHandler : MessageSendEventsProvider {
842         //Channel init:
843         /// Handle an incoming open_channel message from the given peer.
844         fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
845         /// Handle an incoming accept_channel message from the given peer.
846         fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
847         /// Handle an incoming funding_created message from the given peer.
848         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
849         /// Handle an incoming funding_signed message from the given peer.
850         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
851         /// Handle an incoming channel_ready message from the given peer.
852         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &ChannelReady);
853
854         // Channl close:
855         /// Handle an incoming shutdown message from the given peer.
856         fn handle_shutdown(&self, their_node_id: &PublicKey, their_features: &InitFeatures, msg: &Shutdown);
857         /// Handle an incoming closing_signed message from the given peer.
858         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
859
860         // HTLC handling:
861         /// Handle an incoming update_add_htlc message from the given peer.
862         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
863         /// Handle an incoming update_fulfill_htlc message from the given peer.
864         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
865         /// Handle an incoming update_fail_htlc message from the given peer.
866         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
867         /// Handle an incoming update_fail_malformed_htlc message from the given peer.
868         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
869         /// Handle an incoming commitment_signed message from the given peer.
870         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
871         /// Handle an incoming revoke_and_ack message from the given peer.
872         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
873
874         /// Handle an incoming update_fee message from the given peer.
875         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
876
877         // Channel-to-announce:
878         /// Handle an incoming announcement_signatures message from the given peer.
879         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
880
881         // Connection loss/reestablish:
882         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
883         /// is believed to be possible in the future (eg they're sending us messages we don't
884         /// understand or indicate they require unknown feature bits), no_connection_possible is set
885         /// and any outstanding channels should be failed.
886         ///
887         /// Note that in some rare cases this may be called without a corresponding
888         /// [`Self::peer_connected`].
889         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
890
891         /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
892         ///
893         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
894         /// with us. Implementors should be somewhat conservative about doing so, however, as other
895         /// message handlers may still wish to communicate with this peer.
896         fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init) -> Result<(), ()>;
897         /// Handle an incoming channel_reestablish message from the given peer.
898         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
899
900         /// Handle an incoming channel update from the given peer.
901         fn handle_channel_update(&self, their_node_id: &PublicKey, msg: &ChannelUpdate);
902
903         // Error:
904         /// Handle an incoming error message from the given peer.
905         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
906
907         // Handler information:
908         /// Gets the node feature flags which this handler itself supports. All available handlers are
909         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
910         /// which are broadcasted in our [`NodeAnnouncement`] message.
911         fn provided_node_features(&self) -> NodeFeatures;
912
913         /// Gets the init feature flags which should be sent to the given peer. All available handlers
914         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
915         /// which are sent in our [`Init`] message.
916         ///
917         /// Note that this method is called before [`Self::peer_connected`].
918         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
919 }
920
921 /// A trait to describe an object which can receive routing messages.
922 ///
923 /// # Implementor DoS Warnings
924 ///
925 /// For `gossip_queries` messages there are potential DoS vectors when handling
926 /// inbound queries. Implementors using an on-disk network graph should be aware of
927 /// repeated disk I/O for queries accessing different parts of the network graph.
928 pub trait RoutingMessageHandler : MessageSendEventsProvider {
929         /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
930         /// false or returning an Err otherwise.
931         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
932         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
933         /// or returning an Err otherwise.
934         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
935         /// Handle an incoming channel_update message, returning true if it should be forwarded on,
936         /// false or returning an Err otherwise.
937         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
938         /// Gets channel announcements and updates required to dump our routing table to a remote node,
939         /// starting at the short_channel_id indicated by starting_point and including announcements
940         /// for a single channel.
941         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
942         /// Gets a node announcement required to dump our routing table to a remote node, starting at
943         /// the node *after* the provided pubkey and including up to one announcement immediately
944         /// higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
945         /// If None is provided for starting_point, we start at the first node.
946         fn get_next_node_announcement(&self, starting_point: Option<&PublicKey>) -> Option<NodeAnnouncement>;
947         /// Called when a connection is established with a peer. This can be used to
948         /// perform routing table synchronization using a strategy defined by the
949         /// implementor.
950         ///
951         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
952         /// with us. Implementors should be somewhat conservative about doing so, however, as other
953         /// message handlers may still wish to communicate with this peer.
954         fn peer_connected(&self, their_node_id: &PublicKey, init: &Init) -> Result<(), ()>;
955         /// Handles the reply of a query we initiated to learn about channels
956         /// for a given range of blocks. We can expect to receive one or more
957         /// replies to a single query.
958         fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
959         /// Handles the reply of a query we initiated asking for routing gossip
960         /// messages for a list of channels. We should receive this message when
961         /// a node has completed its best effort to send us the pertaining routing
962         /// gossip messages.
963         fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
964         /// Handles when a peer asks us to send a list of short_channel_ids
965         /// for the requested range of blocks.
966         fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
967         /// Handles when a peer asks us to send routing gossip messages for a
968         /// list of short_channel_ids.
969         fn handle_query_short_channel_ids(&self, their_node_id: &PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
970
971         // Handler information:
972         /// Gets the node feature flags which this handler itself supports. All available handlers are
973         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
974         /// which are broadcasted in our [`NodeAnnouncement`] message.
975         fn provided_node_features(&self) -> NodeFeatures;
976         /// Gets the init feature flags which should be sent to the given peer. All available handlers
977         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
978         /// which are sent in our [`Init`] message.
979         ///
980         /// Note that this method is called before [`Self::peer_connected`].
981         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
982 }
983
984 /// A trait to describe an object that can receive onion messages.
985 pub trait OnionMessageHandler : OnionMessageProvider {
986         /// Handle an incoming onion_message message from the given peer.
987         fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage);
988         /// Called when a connection is established with a peer. Can be used to track which peers
989         /// advertise onion message support and are online.
990         ///
991         /// May return an `Err(())` if the features the peer supports are not sufficient to communicate
992         /// with us. Implementors should be somewhat conservative about doing so, however, as other
993         /// message handlers may still wish to communicate with this peer.
994         fn peer_connected(&self, their_node_id: &PublicKey, init: &Init) -> Result<(), ()>;
995         /// Indicates a connection to the peer failed/an existing connection was lost. Allows handlers to
996         /// drop and refuse to forward onion messages to this peer.
997         ///
998         /// Note that in some rare cases this may be called without a corresponding
999         /// [`Self::peer_connected`].
1000         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
1001
1002         // Handler information:
1003         /// Gets the node feature flags which this handler itself supports. All available handlers are
1004         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
1005         /// which are broadcasted in our [`NodeAnnouncement`] message.
1006         fn provided_node_features(&self) -> NodeFeatures;
1007
1008         /// Gets the init feature flags which should be sent to the given peer. All available handlers
1009         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
1010         /// which are sent in our [`Init`] message.
1011         ///
1012         /// Note that this method is called before [`Self::peer_connected`].
1013         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
1014 }
1015
1016 mod fuzzy_internal_msgs {
1017         use crate::prelude::*;
1018         use crate::ln::{PaymentPreimage, PaymentSecret};
1019
1020         // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
1021         // them from untrusted input):
1022         #[derive(Clone)]
1023         pub(crate) struct FinalOnionHopData {
1024                 pub(crate) payment_secret: PaymentSecret,
1025                 /// The total value, in msat, of the payment as received by the ultimate recipient.
1026                 /// Message serialization may panic if this value is more than 21 million Bitcoin.
1027                 pub(crate) total_msat: u64,
1028         }
1029
1030         pub(crate) enum OnionHopDataFormat {
1031                 NonFinalNode {
1032                         short_channel_id: u64,
1033                 },
1034                 FinalNode {
1035                         payment_data: Option<FinalOnionHopData>,
1036                         keysend_preimage: Option<PaymentPreimage>,
1037                 },
1038         }
1039
1040         pub struct OnionHopData {
1041                 pub(crate) format: OnionHopDataFormat,
1042                 /// The value, in msat, of the payment after this hop's fee is deducted.
1043                 /// Message serialization may panic if this value is more than 21 million Bitcoin.
1044                 pub(crate) amt_to_forward: u64,
1045                 pub(crate) outgoing_cltv_value: u32,
1046         }
1047
1048         pub struct DecodedOnionErrorPacket {
1049                 pub(crate) hmac: [u8; 32],
1050                 pub(crate) failuremsg: Vec<u8>,
1051                 pub(crate) pad: Vec<u8>,
1052         }
1053 }
1054 #[cfg(fuzzing)]
1055 pub use self::fuzzy_internal_msgs::*;
1056 #[cfg(not(fuzzing))]
1057 pub(crate) use self::fuzzy_internal_msgs::*;
1058
1059 #[derive(Clone)]
1060 pub(crate) struct OnionPacket {
1061         pub(crate) version: u8,
1062         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
1063         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
1064         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
1065         pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
1066         pub(crate) hop_data: [u8; 20*65],
1067         pub(crate) hmac: [u8; 32],
1068 }
1069
1070 impl onion_utils::Packet for OnionPacket {
1071         type Data = onion_utils::FixedSizeOnionPacket;
1072         fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
1073                 Self {
1074                         version: 0,
1075                         public_key: Ok(pubkey),
1076                         hop_data: hop_data.0,
1077                         hmac,
1078                 }
1079         }
1080 }
1081
1082 impl Eq for OnionPacket { }
1083 impl PartialEq for OnionPacket {
1084         fn eq(&self, other: &OnionPacket) -> bool {
1085                 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
1086                         if i != j { return false; }
1087                 }
1088                 self.version == other.version &&
1089                         self.public_key == other.public_key &&
1090                         self.hmac == other.hmac
1091         }
1092 }
1093
1094 impl fmt::Debug for OnionPacket {
1095         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1096                 f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
1097         }
1098 }
1099
1100 #[derive(Clone, Debug, PartialEq, Eq)]
1101 pub(crate) struct OnionErrorPacket {
1102         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
1103         // (TODO) We limit it in decode to much lower...
1104         pub(crate) data: Vec<u8>,
1105 }
1106
1107 impl fmt::Display for DecodeError {
1108         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1109                 match *self {
1110                         DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
1111                         DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
1112                         DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
1113                         DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
1114                         DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
1115                         DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
1116                         DecodeError::UnsupportedCompression => f.write_str("We don't support receiving messages with zlib-compressed fields"),
1117                 }
1118         }
1119 }
1120
1121 impl From<io::Error> for DecodeError {
1122         fn from(e: io::Error) -> Self {
1123                 if e.kind() == io::ErrorKind::UnexpectedEof {
1124                         DecodeError::ShortRead
1125                 } else {
1126                         DecodeError::Io(e.kind())
1127                 }
1128         }
1129 }
1130
1131 impl Writeable for OptionalField<Script> {
1132         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1133                 match *self {
1134                         OptionalField::Present(ref script) => {
1135                                 // Note that Writeable for script includes the 16-bit length tag for us
1136                                 script.write(w)?;
1137                         },
1138                         OptionalField::Absent => {}
1139                 }
1140                 Ok(())
1141         }
1142 }
1143
1144 impl Readable for OptionalField<Script> {
1145         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1146                 match <u16 as Readable>::read(r) {
1147                         Ok(len) => {
1148                                 let mut buf = vec![0; len as usize];
1149                                 r.read_exact(&mut buf)?;
1150                                 Ok(OptionalField::Present(Script::from(buf)))
1151                         },
1152                         Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
1153                         Err(e) => Err(e)
1154                 }
1155         }
1156 }
1157
1158 impl Writeable for OptionalField<u64> {
1159         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1160                 match *self {
1161                         OptionalField::Present(ref value) => {
1162                                 value.write(w)?;
1163                         },
1164                         OptionalField::Absent => {}
1165                 }
1166                 Ok(())
1167         }
1168 }
1169
1170 impl Readable for OptionalField<u64> {
1171         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1172                 let value: u64 = Readable::read(r)?;
1173                 Ok(OptionalField::Present(value))
1174         }
1175 }
1176
1177
1178 impl_writeable_msg!(AcceptChannel, {
1179         temporary_channel_id,
1180         dust_limit_satoshis,
1181         max_htlc_value_in_flight_msat,
1182         channel_reserve_satoshis,
1183         htlc_minimum_msat,
1184         minimum_depth,
1185         to_self_delay,
1186         max_accepted_htlcs,
1187         funding_pubkey,
1188         revocation_basepoint,
1189         payment_point,
1190         delayed_payment_basepoint,
1191         htlc_basepoint,
1192         first_per_commitment_point,
1193         shutdown_scriptpubkey
1194 }, {
1195         (1, channel_type, option),
1196 });
1197
1198 impl_writeable_msg!(AnnouncementSignatures, {
1199         channel_id,
1200         short_channel_id,
1201         node_signature,
1202         bitcoin_signature
1203 }, {});
1204
1205 impl Writeable for ChannelReestablish {
1206         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1207                 self.channel_id.write(w)?;
1208                 self.next_local_commitment_number.write(w)?;
1209                 self.next_remote_commitment_number.write(w)?;
1210                 match self.data_loss_protect {
1211                         OptionalField::Present(ref data_loss_protect) => {
1212                                 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
1213                                 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
1214                         },
1215                         OptionalField::Absent => {}
1216                 }
1217                 Ok(())
1218         }
1219 }
1220
1221 impl Readable for ChannelReestablish{
1222         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1223                 Ok(Self {
1224                         channel_id: Readable::read(r)?,
1225                         next_local_commitment_number: Readable::read(r)?,
1226                         next_remote_commitment_number: Readable::read(r)?,
1227                         data_loss_protect: {
1228                                 match <[u8; 32] as Readable>::read(r) {
1229                                         Ok(your_last_per_commitment_secret) =>
1230                                                 OptionalField::Present(DataLossProtect {
1231                                                         your_last_per_commitment_secret,
1232                                                         my_current_per_commitment_point: Readable::read(r)?,
1233                                                 }),
1234                                         Err(DecodeError::ShortRead) => OptionalField::Absent,
1235                                         Err(e) => return Err(e)
1236                                 }
1237                         }
1238                 })
1239         }
1240 }
1241
1242 impl_writeable_msg!(ClosingSigned,
1243         { channel_id, fee_satoshis, signature },
1244         { (1, fee_range, option) }
1245 );
1246
1247 impl_writeable!(ClosingSignedFeeRange, {
1248         min_fee_satoshis,
1249         max_fee_satoshis
1250 });
1251
1252 impl_writeable_msg!(CommitmentSigned, {
1253         channel_id,
1254         signature,
1255         htlc_signatures
1256 }, {});
1257
1258 impl_writeable!(DecodedOnionErrorPacket, {
1259         hmac,
1260         failuremsg,
1261         pad
1262 });
1263
1264 impl_writeable_msg!(FundingCreated, {
1265         temporary_channel_id,
1266         funding_txid,
1267         funding_output_index,
1268         signature
1269 }, {});
1270
1271 impl_writeable_msg!(FundingSigned, {
1272         channel_id,
1273         signature
1274 }, {});
1275
1276 impl_writeable_msg!(ChannelReady, {
1277         channel_id,
1278         next_per_commitment_point,
1279 }, {
1280         (1, short_channel_id_alias, option),
1281 });
1282
1283 impl Writeable for Init {
1284         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1285                 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1286                 // our relevant feature bits. This keeps us compatible with old nodes.
1287                 self.features.write_up_to_13(w)?;
1288                 self.features.write(w)?;
1289                 encode_tlv_stream!(w, {
1290                         (3, self.remote_network_address, option)
1291                 });
1292                 Ok(())
1293         }
1294 }
1295
1296 impl Readable for Init {
1297         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1298                 let global_features: InitFeatures = Readable::read(r)?;
1299                 let features: InitFeatures = Readable::read(r)?;
1300                 let mut remote_network_address: Option<NetAddress> = None;
1301                 decode_tlv_stream!(r, {
1302                         (3, remote_network_address, option)
1303                 });
1304                 Ok(Init {
1305                         features: features.or(global_features),
1306                         remote_network_address,
1307                 })
1308         }
1309 }
1310
1311 impl_writeable_msg!(OpenChannel, {
1312         chain_hash,
1313         temporary_channel_id,
1314         funding_satoshis,
1315         push_msat,
1316         dust_limit_satoshis,
1317         max_htlc_value_in_flight_msat,
1318         channel_reserve_satoshis,
1319         htlc_minimum_msat,
1320         feerate_per_kw,
1321         to_self_delay,
1322         max_accepted_htlcs,
1323         funding_pubkey,
1324         revocation_basepoint,
1325         payment_point,
1326         delayed_payment_basepoint,
1327         htlc_basepoint,
1328         first_per_commitment_point,
1329         channel_flags,
1330         shutdown_scriptpubkey
1331 }, {
1332         (1, channel_type, option),
1333 });
1334
1335 impl_writeable_msg!(RevokeAndACK, {
1336         channel_id,
1337         per_commitment_secret,
1338         next_per_commitment_point
1339 }, {});
1340
1341 impl_writeable_msg!(Shutdown, {
1342         channel_id,
1343         scriptpubkey
1344 }, {});
1345
1346 impl_writeable_msg!(UpdateFailHTLC, {
1347         channel_id,
1348         htlc_id,
1349         reason
1350 }, {});
1351
1352 impl_writeable_msg!(UpdateFailMalformedHTLC, {
1353         channel_id,
1354         htlc_id,
1355         sha256_of_onion,
1356         failure_code
1357 }, {});
1358
1359 impl_writeable_msg!(UpdateFee, {
1360         channel_id,
1361         feerate_per_kw
1362 }, {});
1363
1364 impl_writeable_msg!(UpdateFulfillHTLC, {
1365         channel_id,
1366         htlc_id,
1367         payment_preimage
1368 }, {});
1369
1370 // Note that this is written as a part of ChannelManager objects, and thus cannot change its
1371 // serialization format in a way which assumes we know the total serialized length/message end
1372 // position.
1373 impl_writeable!(OnionErrorPacket, {
1374         data
1375 });
1376
1377 // Note that this is written as a part of ChannelManager objects, and thus cannot change its
1378 // serialization format in a way which assumes we know the total serialized length/message end
1379 // position.
1380 impl Writeable for OnionPacket {
1381         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1382                 self.version.write(w)?;
1383                 match self.public_key {
1384                         Ok(pubkey) => pubkey.write(w)?,
1385                         Err(_) => [0u8;33].write(w)?,
1386                 }
1387                 w.write_all(&self.hop_data)?;
1388                 self.hmac.write(w)?;
1389                 Ok(())
1390         }
1391 }
1392
1393 impl Readable for OnionPacket {
1394         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1395                 Ok(OnionPacket {
1396                         version: Readable::read(r)?,
1397                         public_key: {
1398                                 let mut buf = [0u8;33];
1399                                 r.read_exact(&mut buf)?;
1400                                 PublicKey::from_slice(&buf)
1401                         },
1402                         hop_data: Readable::read(r)?,
1403                         hmac: Readable::read(r)?,
1404                 })
1405         }
1406 }
1407
1408 impl_writeable_msg!(UpdateAddHTLC, {
1409         channel_id,
1410         htlc_id,
1411         amount_msat,
1412         payment_hash,
1413         cltv_expiry,
1414         onion_routing_packet
1415 }, {});
1416
1417 impl Readable for OnionMessage {
1418         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1419                 let blinding_point: PublicKey = Readable::read(r)?;
1420                 let len: u16 = Readable::read(r)?;
1421                 let mut packet_reader = FixedLengthReader::new(r, len as u64);
1422                 let onion_routing_packet: onion_message::Packet = <onion_message::Packet as LengthReadable>::read(&mut packet_reader)?;
1423                 Ok(Self {
1424                         blinding_point,
1425                         onion_routing_packet,
1426                 })
1427         }
1428 }
1429
1430 impl Writeable for OnionMessage {
1431         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1432                 self.blinding_point.write(w)?;
1433                 let onion_packet_len = self.onion_routing_packet.serialized_length();
1434                 (onion_packet_len as u16).write(w)?;
1435                 self.onion_routing_packet.write(w)?;
1436                 Ok(())
1437         }
1438 }
1439
1440 impl Writeable for FinalOnionHopData {
1441         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1442                 self.payment_secret.0.write(w)?;
1443                 HighZeroBytesDroppedBigSize(self.total_msat).write(w)
1444         }
1445 }
1446
1447 impl Readable for FinalOnionHopData {
1448         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1449                 let secret: [u8; 32] = Readable::read(r)?;
1450                 let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
1451                 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
1452         }
1453 }
1454
1455 impl Writeable for OnionHopData {
1456         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1457                 match self.format {
1458                         OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1459                                 encode_varint_length_prefixed_tlv!(w, {
1460                                         (2, HighZeroBytesDroppedBigSize(self.amt_to_forward), required),
1461                                         (4, HighZeroBytesDroppedBigSize(self.outgoing_cltv_value), required),
1462                                         (6, short_channel_id, required)
1463                                 });
1464                         },
1465                         OnionHopDataFormat::FinalNode { ref payment_data, ref keysend_preimage } => {
1466                                 encode_varint_length_prefixed_tlv!(w, {
1467                                         (2, HighZeroBytesDroppedBigSize(self.amt_to_forward), required),
1468                                         (4, HighZeroBytesDroppedBigSize(self.outgoing_cltv_value), required),
1469                                         (8, payment_data, option),
1470                                         (5482373484, keysend_preimage, option)
1471                                 });
1472                         },
1473                 }
1474                 Ok(())
1475         }
1476 }
1477
1478 impl Readable for OnionHopData {
1479         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1480                 let mut amt = HighZeroBytesDroppedBigSize(0u64);
1481                 let mut cltv_value = HighZeroBytesDroppedBigSize(0u32);
1482                 let mut short_id: Option<u64> = None;
1483                 let mut payment_data: Option<FinalOnionHopData> = None;
1484                 let mut keysend_preimage: Option<PaymentPreimage> = None;
1485                 read_tlv_fields!(r, {
1486                         (2, amt, required),
1487                         (4, cltv_value, required),
1488                         (6, short_id, option),
1489                         (8, payment_data, option),
1490                         // See https://github.com/lightning/blips/blob/master/blip-0003.md
1491                         (5482373484, keysend_preimage, option)
1492                 });
1493
1494                 let format = if let Some(short_channel_id) = short_id {
1495                         if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1496                         OnionHopDataFormat::NonFinalNode {
1497                                 short_channel_id,
1498                         }
1499                 } else {
1500                         if let &Some(ref data) = &payment_data {
1501                                 if data.total_msat > MAX_VALUE_MSAT {
1502                                         return Err(DecodeError::InvalidValue);
1503                                 }
1504                         }
1505                         OnionHopDataFormat::FinalNode {
1506                                 payment_data,
1507                                 keysend_preimage,
1508                         }
1509                 };
1510
1511                 if amt.0 > MAX_VALUE_MSAT {
1512                         return Err(DecodeError::InvalidValue);
1513                 }
1514                 Ok(OnionHopData {
1515                         format,
1516                         amt_to_forward: amt.0,
1517                         outgoing_cltv_value: cltv_value.0,
1518                 })
1519         }
1520 }
1521
1522 // ReadableArgs because we need onion_utils::decode_next_hop to accommodate payment packets and
1523 // onion message packets.
1524 impl ReadableArgs<()> for OnionHopData {
1525         fn read<R: Read>(r: &mut R, _arg: ()) -> Result<Self, DecodeError> {
1526                 <Self as Readable>::read(r)
1527         }
1528 }
1529
1530 impl Writeable for Ping {
1531         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1532                 self.ponglen.write(w)?;
1533                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1534                 Ok(())
1535         }
1536 }
1537
1538 impl Readable for Ping {
1539         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1540                 Ok(Ping {
1541                         ponglen: Readable::read(r)?,
1542                         byteslen: {
1543                                 let byteslen = Readable::read(r)?;
1544                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1545                                 byteslen
1546                         }
1547                 })
1548         }
1549 }
1550
1551 impl Writeable for Pong {
1552         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1553                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1554                 Ok(())
1555         }
1556 }
1557
1558 impl Readable for Pong {
1559         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1560                 Ok(Pong {
1561                         byteslen: {
1562                                 let byteslen = Readable::read(r)?;
1563                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1564                                 byteslen
1565                         }
1566                 })
1567         }
1568 }
1569
1570 impl Writeable for UnsignedChannelAnnouncement {
1571         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1572                 self.features.write(w)?;
1573                 self.chain_hash.write(w)?;
1574                 self.short_channel_id.write(w)?;
1575                 self.node_id_1.write(w)?;
1576                 self.node_id_2.write(w)?;
1577                 self.bitcoin_key_1.write(w)?;
1578                 self.bitcoin_key_2.write(w)?;
1579                 w.write_all(&self.excess_data[..])?;
1580                 Ok(())
1581         }
1582 }
1583
1584 impl Readable for UnsignedChannelAnnouncement {
1585         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1586                 Ok(Self {
1587                         features: Readable::read(r)?,
1588                         chain_hash: Readable::read(r)?,
1589                         short_channel_id: Readable::read(r)?,
1590                         node_id_1: Readable::read(r)?,
1591                         node_id_2: Readable::read(r)?,
1592                         bitcoin_key_1: Readable::read(r)?,
1593                         bitcoin_key_2: Readable::read(r)?,
1594                         excess_data: read_to_end(r)?,
1595                 })
1596         }
1597 }
1598
1599 impl_writeable!(ChannelAnnouncement, {
1600         node_signature_1,
1601         node_signature_2,
1602         bitcoin_signature_1,
1603         bitcoin_signature_2,
1604         contents
1605 });
1606
1607 impl Writeable for UnsignedChannelUpdate {
1608         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1609                 // `message_flags` used to indicate presence of `htlc_maximum_msat`, but was deprecated in the spec.
1610                 const MESSAGE_FLAGS: u8 = 1;
1611                 self.chain_hash.write(w)?;
1612                 self.short_channel_id.write(w)?;
1613                 self.timestamp.write(w)?;
1614                 let all_flags = self.flags as u16 | ((MESSAGE_FLAGS as u16) << 8);
1615                 all_flags.write(w)?;
1616                 self.cltv_expiry_delta.write(w)?;
1617                 self.htlc_minimum_msat.write(w)?;
1618                 self.fee_base_msat.write(w)?;
1619                 self.fee_proportional_millionths.write(w)?;
1620                 self.htlc_maximum_msat.write(w)?;
1621                 w.write_all(&self.excess_data[..])?;
1622                 Ok(())
1623         }
1624 }
1625
1626 impl Readable for UnsignedChannelUpdate {
1627         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1628                 Ok(Self {
1629                         chain_hash: Readable::read(r)?,
1630                         short_channel_id: Readable::read(r)?,
1631                         timestamp: Readable::read(r)?,
1632                         flags: {
1633                                 let flags: u16 = Readable::read(r)?;
1634                                 // Note: we ignore the `message_flags` for now, since it was deprecated by the spec.
1635                                 flags as u8
1636                         },
1637                         cltv_expiry_delta: Readable::read(r)?,
1638                         htlc_minimum_msat: Readable::read(r)?,
1639                         fee_base_msat: Readable::read(r)?,
1640                         fee_proportional_millionths: Readable::read(r)?,
1641                         htlc_maximum_msat: Readable::read(r)?,
1642                         excess_data: read_to_end(r)?,
1643                 })
1644         }
1645 }
1646
1647 impl_writeable!(ChannelUpdate, {
1648         signature,
1649         contents
1650 });
1651
1652 impl Writeable for ErrorMessage {
1653         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1654                 self.channel_id.write(w)?;
1655                 (self.data.len() as u16).write(w)?;
1656                 w.write_all(self.data.as_bytes())?;
1657                 Ok(())
1658         }
1659 }
1660
1661 impl Readable for ErrorMessage {
1662         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1663                 Ok(Self {
1664                         channel_id: Readable::read(r)?,
1665                         data: {
1666                                 let sz: usize = <u16 as Readable>::read(r)? as usize;
1667                                 let mut data = Vec::with_capacity(sz);
1668                                 data.resize(sz, 0);
1669                                 r.read_exact(&mut data)?;
1670                                 match String::from_utf8(data) {
1671                                         Ok(s) => s,
1672                                         Err(_) => return Err(DecodeError::InvalidValue),
1673                                 }
1674                         }
1675                 })
1676         }
1677 }
1678
1679 impl Writeable for WarningMessage {
1680         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1681                 self.channel_id.write(w)?;
1682                 (self.data.len() as u16).write(w)?;
1683                 w.write_all(self.data.as_bytes())?;
1684                 Ok(())
1685         }
1686 }
1687
1688 impl Readable for WarningMessage {
1689         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1690                 Ok(Self {
1691                         channel_id: Readable::read(r)?,
1692                         data: {
1693                                 let sz: usize = <u16 as Readable>::read(r)? as usize;
1694                                 let mut data = Vec::with_capacity(sz);
1695                                 data.resize(sz, 0);
1696                                 r.read_exact(&mut data)?;
1697                                 match String::from_utf8(data) {
1698                                         Ok(s) => s,
1699                                         Err(_) => return Err(DecodeError::InvalidValue),
1700                                 }
1701                         }
1702                 })
1703         }
1704 }
1705
1706 impl Writeable for UnsignedNodeAnnouncement {
1707         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1708                 self.features.write(w)?;
1709                 self.timestamp.write(w)?;
1710                 self.node_id.write(w)?;
1711                 w.write_all(&self.rgb)?;
1712                 self.alias.write(w)?;
1713
1714                 let mut addr_len = 0;
1715                 for addr in self.addresses.iter() {
1716                         addr_len += 1 + addr.len();
1717                 }
1718                 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1719                 for addr in self.addresses.iter() {
1720                         addr.write(w)?;
1721                 }
1722                 w.write_all(&self.excess_address_data[..])?;
1723                 w.write_all(&self.excess_data[..])?;
1724                 Ok(())
1725         }
1726 }
1727
1728 impl Readable for UnsignedNodeAnnouncement {
1729         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1730                 let features: NodeFeatures = Readable::read(r)?;
1731                 let timestamp: u32 = Readable::read(r)?;
1732                 let node_id: PublicKey = Readable::read(r)?;
1733                 let mut rgb = [0; 3];
1734                 r.read_exact(&mut rgb)?;
1735                 let alias: [u8; 32] = Readable::read(r)?;
1736
1737                 let addr_len: u16 = Readable::read(r)?;
1738                 let mut addresses: Vec<NetAddress> = Vec::new();
1739                 let mut addr_readpos = 0;
1740                 let mut excess = false;
1741                 let mut excess_byte = 0;
1742                 loop {
1743                         if addr_len <= addr_readpos { break; }
1744                         match Readable::read(r) {
1745                                 Ok(Ok(addr)) => {
1746                                         if addr_len < addr_readpos + 1 + addr.len() {
1747                                                 return Err(DecodeError::BadLengthDescriptor);
1748                                         }
1749                                         addr_readpos += (1 + addr.len()) as u16;
1750                                         addresses.push(addr);
1751                                 },
1752                                 Ok(Err(unknown_descriptor)) => {
1753                                         excess = true;
1754                                         excess_byte = unknown_descriptor;
1755                                         break;
1756                                 },
1757                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1758                                 Err(e) => return Err(e),
1759                         }
1760                 }
1761
1762                 let mut excess_data = vec![];
1763                 let excess_address_data = if addr_readpos < addr_len {
1764                         let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1765                         r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1766                         if excess {
1767                                 excess_address_data[0] = excess_byte;
1768                         }
1769                         excess_address_data
1770                 } else {
1771                         if excess {
1772                                 excess_data.push(excess_byte);
1773                         }
1774                         Vec::new()
1775                 };
1776                 excess_data.extend(read_to_end(r)?.iter());
1777                 Ok(UnsignedNodeAnnouncement {
1778                         features,
1779                         timestamp,
1780                         node_id,
1781                         rgb,
1782                         alias,
1783                         addresses,
1784                         excess_address_data,
1785                         excess_data,
1786                 })
1787         }
1788 }
1789
1790 impl_writeable!(NodeAnnouncement, {
1791         signature,
1792         contents
1793 });
1794
1795 impl Readable for QueryShortChannelIds {
1796         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1797                 let chain_hash: BlockHash = Readable::read(r)?;
1798
1799                 let encoding_len: u16 = Readable::read(r)?;
1800                 let encoding_type: u8 = Readable::read(r)?;
1801
1802                 // Must be encoding_type=0 uncompressed serialization. We do not
1803                 // support encoding_type=1 zlib serialization.
1804                 if encoding_type != EncodingType::Uncompressed as u8 {
1805                         return Err(DecodeError::UnsupportedCompression);
1806                 }
1807
1808                 // We expect the encoding_len to always includes the 1-byte
1809                 // encoding_type and that short_channel_ids are 8-bytes each
1810                 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1811                         return Err(DecodeError::InvalidValue);
1812                 }
1813
1814                 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1815                 // less the 1-byte encoding_type
1816                 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1817                 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1818                 for _ in 0..short_channel_id_count {
1819                         short_channel_ids.push(Readable::read(r)?);
1820                 }
1821
1822                 Ok(QueryShortChannelIds {
1823                         chain_hash,
1824                         short_channel_ids,
1825                 })
1826         }
1827 }
1828
1829 impl Writeable for QueryShortChannelIds {
1830         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1831                 // Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
1832                 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1833
1834                 self.chain_hash.write(w)?;
1835                 encoding_len.write(w)?;
1836
1837                 // We only support type=0 uncompressed serialization
1838                 (EncodingType::Uncompressed as u8).write(w)?;
1839
1840                 for scid in self.short_channel_ids.iter() {
1841                         scid.write(w)?;
1842                 }
1843
1844                 Ok(())
1845         }
1846 }
1847
1848 impl_writeable_msg!(ReplyShortChannelIdsEnd, {
1849         chain_hash,
1850         full_information,
1851 }, {});
1852
1853 impl QueryChannelRange {
1854         /**
1855          * Calculates the overflow safe ending block height for the query.
1856          * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`
1857          */
1858         pub fn end_blocknum(&self) -> u32 {
1859                 match self.first_blocknum.checked_add(self.number_of_blocks) {
1860                         Some(block) => block,
1861                         None => u32::max_value(),
1862                 }
1863         }
1864 }
1865
1866 impl_writeable_msg!(QueryChannelRange, {
1867         chain_hash,
1868         first_blocknum,
1869         number_of_blocks
1870 }, {});
1871
1872 impl Readable for ReplyChannelRange {
1873         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1874                 let chain_hash: BlockHash = Readable::read(r)?;
1875                 let first_blocknum: u32 = Readable::read(r)?;
1876                 let number_of_blocks: u32 = Readable::read(r)?;
1877                 let sync_complete: bool = Readable::read(r)?;
1878
1879                 let encoding_len: u16 = Readable::read(r)?;
1880                 let encoding_type: u8 = Readable::read(r)?;
1881
1882                 // Must be encoding_type=0 uncompressed serialization. We do not
1883                 // support encoding_type=1 zlib serialization.
1884                 if encoding_type != EncodingType::Uncompressed as u8 {
1885                         return Err(DecodeError::UnsupportedCompression);
1886                 }
1887
1888                 // We expect the encoding_len to always includes the 1-byte
1889                 // encoding_type and that short_channel_ids are 8-bytes each
1890                 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1891                         return Err(DecodeError::InvalidValue);
1892                 }
1893
1894                 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1895                 // less the 1-byte encoding_type
1896                 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1897                 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1898                 for _ in 0..short_channel_id_count {
1899                         short_channel_ids.push(Readable::read(r)?);
1900                 }
1901
1902                 Ok(ReplyChannelRange {
1903                         chain_hash,
1904                         first_blocknum,
1905                         number_of_blocks,
1906                         sync_complete,
1907                         short_channel_ids
1908                 })
1909         }
1910 }
1911
1912 impl Writeable for ReplyChannelRange {
1913         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1914                 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1915                 self.chain_hash.write(w)?;
1916                 self.first_blocknum.write(w)?;
1917                 self.number_of_blocks.write(w)?;
1918                 self.sync_complete.write(w)?;
1919
1920                 encoding_len.write(w)?;
1921                 (EncodingType::Uncompressed as u8).write(w)?;
1922                 for scid in self.short_channel_ids.iter() {
1923                         scid.write(w)?;
1924                 }
1925
1926                 Ok(())
1927         }
1928 }
1929
1930 impl_writeable_msg!(GossipTimestampFilter, {
1931         chain_hash,
1932         first_timestamp,
1933         timestamp_range,
1934 }, {});
1935
1936 #[cfg(test)]
1937 mod tests {
1938         use hex;
1939         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
1940         use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
1941         use crate::ln::msgs;
1942         use crate::ln::msgs::{FinalOnionHopData, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1943         use crate::util::ser::{Writeable, Readable, Hostname};
1944
1945         use bitcoin::hashes::hex::FromHex;
1946         use bitcoin::util::address::Address;
1947         use bitcoin::network::constants::Network;
1948         use bitcoin::blockdata::script::Builder;
1949         use bitcoin::blockdata::opcodes;
1950         use bitcoin::hash_types::{Txid, BlockHash};
1951
1952         use bitcoin::secp256k1::{PublicKey,SecretKey};
1953         use bitcoin::secp256k1::{Secp256k1, Message};
1954
1955         use crate::io::{self, Cursor};
1956         use crate::prelude::*;
1957         use core::convert::TryFrom;
1958
1959         #[test]
1960         fn encoding_channel_reestablish_no_secret() {
1961                 let cr = msgs::ChannelReestablish {
1962                         channel_id: [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],
1963                         next_local_commitment_number: 3,
1964                         next_remote_commitment_number: 4,
1965                         data_loss_protect: OptionalField::Absent,
1966                 };
1967
1968                 let encoded_value = cr.encode();
1969                 assert_eq!(
1970                         encoded_value,
1971                         vec![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, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4]
1972                 );
1973         }
1974
1975         #[test]
1976         fn encoding_channel_reestablish_with_secret() {
1977                 let public_key = {
1978                         let secp_ctx = Secp256k1::new();
1979                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1980                 };
1981
1982                 let cr = msgs::ChannelReestablish {
1983                         channel_id: [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],
1984                         next_local_commitment_number: 3,
1985                         next_remote_commitment_number: 4,
1986                         data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1987                 };
1988
1989                 let encoded_value = cr.encode();
1990                 assert_eq!(
1991                         encoded_value,
1992                         vec![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, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 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, 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]
1993                 );
1994         }
1995
1996         macro_rules! get_keys_from {
1997                 ($slice: expr, $secp_ctx: expr) => {
1998                         {
1999                                 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
2000                                 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
2001                                 (privkey, pubkey)
2002                         }
2003                 }
2004         }
2005
2006         macro_rules! get_sig_on {
2007                 ($privkey: expr, $ctx: expr, $string: expr) => {
2008                         {
2009                                 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
2010                                 $ctx.sign_ecdsa(&sighash, &$privkey)
2011                         }
2012                 }
2013         }
2014
2015         #[test]
2016         fn encoding_announcement_signatures() {
2017                 let secp_ctx = Secp256k1::new();
2018                 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2019                 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
2020                 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
2021                 let announcement_signatures = msgs::AnnouncementSignatures {
2022                         channel_id: [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],
2023                         short_channel_id: 2316138423780173,
2024                         node_signature: sig_1,
2025                         bitcoin_signature: sig_2,
2026                 };
2027
2028                 let encoded_value = announcement_signatures.encode();
2029                 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
2030         }
2031
2032         fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
2033                 let secp_ctx = Secp256k1::new();
2034                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2035                 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2036                 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2037                 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2038                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2039                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2040                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2041                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2042                 let mut features = ChannelFeatures::empty();
2043                 if unknown_features_bits {
2044                         features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
2045                 }
2046                 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
2047                         features,
2048                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2049                         short_channel_id: 2316138423780173,
2050                         node_id_1: pubkey_1,
2051                         node_id_2: pubkey_2,
2052                         bitcoin_key_1: pubkey_3,
2053                         bitcoin_key_2: pubkey_4,
2054                         excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
2055                 };
2056                 let channel_announcement = msgs::ChannelAnnouncement {
2057                         node_signature_1: sig_1,
2058                         node_signature_2: sig_2,
2059                         bitcoin_signature_1: sig_3,
2060                         bitcoin_signature_2: sig_4,
2061                         contents: unsigned_channel_announcement,
2062                 };
2063                 let encoded_value = channel_announcement.encode();
2064                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
2065                 if unknown_features_bits {
2066                         target_value.append(&mut hex::decode("0002ffff").unwrap());
2067                 } else {
2068                         target_value.append(&mut hex::decode("0000").unwrap());
2069                 }
2070                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2071                 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
2072                 if excess_data {
2073                         target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
2074                 }
2075                 assert_eq!(encoded_value, target_value);
2076         }
2077
2078         #[test]
2079         fn encoding_channel_announcement() {
2080                 do_encoding_channel_announcement(true, false);
2081                 do_encoding_channel_announcement(false, true);
2082                 do_encoding_channel_announcement(false, false);
2083                 do_encoding_channel_announcement(true, true);
2084         }
2085
2086         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) {
2087                 let secp_ctx = Secp256k1::new();
2088                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2089                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2090                 let features = if unknown_features_bits {
2091                         NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
2092                 } else {
2093                         // Set to some features we may support
2094                         NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
2095                 };
2096                 let mut addresses = Vec::new();
2097                 if ipv4 {
2098                         addresses.push(msgs::NetAddress::IPv4 {
2099                                 addr: [255, 254, 253, 252],
2100                                 port: 9735
2101                         });
2102                 }
2103                 if ipv6 {
2104                         addresses.push(msgs::NetAddress::IPv6 {
2105                                 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
2106                                 port: 9735
2107                         });
2108                 }
2109                 if onionv2 {
2110                         addresses.push(msgs::NetAddress::OnionV2(
2111                                 [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]
2112                         ));
2113                 }
2114                 if onionv3 {
2115                         addresses.push(msgs::NetAddress::OnionV3 {
2116                                 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],
2117                                 checksum: 32,
2118                                 version: 16,
2119                                 port: 9735
2120                         });
2121                 }
2122                 if hostname {
2123                         addresses.push(msgs::NetAddress::Hostname {
2124                                 hostname: Hostname::try_from(String::from("host")).unwrap(),
2125                                 port: 9735,
2126                         });
2127                 }
2128                 let mut addr_len = 0;
2129                 for addr in &addresses {
2130                         addr_len += addr.len() + 1;
2131                 }
2132                 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
2133                         features,
2134                         timestamp: 20190119,
2135                         node_id: pubkey_1,
2136                         rgb: [32; 3],
2137                         alias: [16;32],
2138                         addresses,
2139                         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() },
2140                         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() },
2141                 };
2142                 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
2143                 let node_announcement = msgs::NodeAnnouncement {
2144                         signature: sig_1,
2145                         contents: unsigned_node_announcement,
2146                 };
2147                 let encoded_value = node_announcement.encode();
2148                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2149                 if unknown_features_bits {
2150                         target_value.append(&mut hex::decode("0002ffff").unwrap());
2151                 } else {
2152                         target_value.append(&mut hex::decode("000122").unwrap());
2153                 }
2154                 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
2155                 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
2156                 if ipv4 {
2157                         target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
2158                 }
2159                 if ipv6 {
2160                         target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
2161                 }
2162                 if onionv2 {
2163                         target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
2164                 }
2165                 if onionv3 {
2166                         target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
2167                 }
2168                 if hostname {
2169                         target_value.append(&mut hex::decode("0504686f73742607").unwrap());
2170                 }
2171                 if excess_address_data {
2172                         target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
2173                 }
2174                 if excess_data {
2175                         target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2176                 }
2177                 assert_eq!(encoded_value, target_value);
2178         }
2179
2180         #[test]
2181         fn encoding_node_announcement() {
2182                 do_encoding_node_announcement(true, true, true, true, true, true, true, true);
2183                 do_encoding_node_announcement(false, false, false, false, false, false, false, false);
2184                 do_encoding_node_announcement(false, true, false, false, false, false, false, false);
2185                 do_encoding_node_announcement(false, false, true, false, false, false, false, false);
2186                 do_encoding_node_announcement(false, false, false, true, false, false, false, false);
2187                 do_encoding_node_announcement(false, false, false, false, true, false, false, false);
2188                 do_encoding_node_announcement(false, false, false, false, false, true, false, false);
2189                 do_encoding_node_announcement(false, false, false, false, false, false, true, false);
2190                 do_encoding_node_announcement(false, true, false, true, false, false, true, false);
2191                 do_encoding_node_announcement(false, false, true, false, true, false, false, false);
2192         }
2193
2194         fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
2195                 let secp_ctx = Secp256k1::new();
2196                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2197                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2198                 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
2199                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2200                         short_channel_id: 2316138423780173,
2201                         timestamp: 20190119,
2202                         flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
2203                         cltv_expiry_delta: 144,
2204                         htlc_minimum_msat: 1000000,
2205                         htlc_maximum_msat: 131355275467161,
2206                         fee_base_msat: 10000,
2207                         fee_proportional_millionths: 20,
2208                         excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
2209                 };
2210                 let channel_update = msgs::ChannelUpdate {
2211                         signature: sig_1,
2212                         contents: unsigned_channel_update
2213                 };
2214                 let encoded_value = channel_update.encode();
2215                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2216                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2217                 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
2218                 target_value.append(&mut hex::decode("01").unwrap());
2219                 target_value.append(&mut hex::decode("00").unwrap());
2220                 if direction {
2221                         let flag = target_value.last_mut().unwrap();
2222                         *flag = 1;
2223                 }
2224                 if disable {
2225                         let flag = target_value.last_mut().unwrap();
2226                         *flag = *flag | 1 << 1;
2227                 }
2228                 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
2229                 target_value.append(&mut hex::decode("0000777788889999").unwrap());
2230                 if excess_data {
2231                         target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
2232                 }
2233                 assert_eq!(encoded_value, target_value);
2234         }
2235
2236         #[test]
2237         fn encoding_channel_update() {
2238                 do_encoding_channel_update(false, false, false);
2239                 do_encoding_channel_update(false, false, true);
2240                 do_encoding_channel_update(true, false, false);
2241                 do_encoding_channel_update(true, false, true);
2242                 do_encoding_channel_update(false, true, false);
2243                 do_encoding_channel_update(false, true, true);
2244                 do_encoding_channel_update(true, true, false);
2245                 do_encoding_channel_update(true, true, true);
2246         }
2247
2248         fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
2249                 let secp_ctx = Secp256k1::new();
2250                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2251                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2252                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2253                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2254                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2255                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2256                 let open_channel = msgs::OpenChannel {
2257                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2258                         temporary_channel_id: [2; 32],
2259                         funding_satoshis: 1311768467284833366,
2260                         push_msat: 2536655962884945560,
2261                         dust_limit_satoshis: 3608586615801332854,
2262                         max_htlc_value_in_flight_msat: 8517154655701053848,
2263                         channel_reserve_satoshis: 8665828695742877976,
2264                         htlc_minimum_msat: 2316138423780173,
2265                         feerate_per_kw: 821716,
2266                         to_self_delay: 49340,
2267                         max_accepted_htlcs: 49340,
2268                         funding_pubkey: pubkey_1,
2269                         revocation_basepoint: pubkey_2,
2270                         payment_point: pubkey_3,
2271                         delayed_payment_basepoint: pubkey_4,
2272                         htlc_basepoint: pubkey_5,
2273                         first_per_commitment_point: pubkey_6,
2274                         channel_flags: if random_bit { 1 << 5 } else { 0 },
2275                         shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent },
2276                         channel_type: if incl_chan_type { Some(ChannelTypeFeatures::empty()) } else { None },
2277                 };
2278                 let encoded_value = open_channel.encode();
2279                 let mut target_value = Vec::new();
2280                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2281                 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
2282                 if random_bit {
2283                         target_value.append(&mut hex::decode("20").unwrap());
2284                 } else {
2285                         target_value.append(&mut hex::decode("00").unwrap());
2286                 }
2287                 if shutdown {
2288                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2289                 }
2290                 if incl_chan_type {
2291                         target_value.append(&mut hex::decode("0100").unwrap());
2292                 }
2293                 assert_eq!(encoded_value, target_value);
2294         }
2295
2296         #[test]
2297         fn encoding_open_channel() {
2298                 do_encoding_open_channel(false, false, false);
2299                 do_encoding_open_channel(false, false, true);
2300                 do_encoding_open_channel(false, true, false);
2301                 do_encoding_open_channel(false, true, true);
2302                 do_encoding_open_channel(true, false, false);
2303                 do_encoding_open_channel(true, false, true);
2304                 do_encoding_open_channel(true, true, false);
2305                 do_encoding_open_channel(true, true, true);
2306         }
2307
2308         fn do_encoding_accept_channel(shutdown: bool) {
2309                 let secp_ctx = Secp256k1::new();
2310                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2311                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2312                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2313                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2314                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2315                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2316                 let accept_channel = msgs::AcceptChannel {
2317                         temporary_channel_id: [2; 32],
2318                         dust_limit_satoshis: 1311768467284833366,
2319                         max_htlc_value_in_flight_msat: 2536655962884945560,
2320                         channel_reserve_satoshis: 3608586615801332854,
2321                         htlc_minimum_msat: 2316138423780173,
2322                         minimum_depth: 821716,
2323                         to_self_delay: 49340,
2324                         max_accepted_htlcs: 49340,
2325                         funding_pubkey: pubkey_1,
2326                         revocation_basepoint: pubkey_2,
2327                         payment_point: pubkey_3,
2328                         delayed_payment_basepoint: pubkey_4,
2329                         htlc_basepoint: pubkey_5,
2330                         first_per_commitment_point: pubkey_6,
2331                         shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent },
2332                         channel_type: None,
2333                 };
2334                 let encoded_value = accept_channel.encode();
2335                 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
2336                 if shutdown {
2337                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2338                 }
2339                 assert_eq!(encoded_value, target_value);
2340         }
2341
2342         #[test]
2343         fn encoding_accept_channel() {
2344                 do_encoding_accept_channel(false);
2345                 do_encoding_accept_channel(true);
2346         }
2347
2348         #[test]
2349         fn encoding_funding_created() {
2350                 let secp_ctx = Secp256k1::new();
2351                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2352                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2353                 let funding_created = msgs::FundingCreated {
2354                         temporary_channel_id: [2; 32],
2355                         funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
2356                         funding_output_index: 255,
2357                         signature: sig_1,
2358                 };
2359                 let encoded_value = funding_created.encode();
2360                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2361                 assert_eq!(encoded_value, target_value);
2362         }
2363
2364         #[test]
2365         fn encoding_funding_signed() {
2366                 let secp_ctx = Secp256k1::new();
2367                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2368                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2369                 let funding_signed = msgs::FundingSigned {
2370                         channel_id: [2; 32],
2371                         signature: sig_1,
2372                 };
2373                 let encoded_value = funding_signed.encode();
2374                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2375                 assert_eq!(encoded_value, target_value);
2376         }
2377
2378         #[test]
2379         fn encoding_channel_ready() {
2380                 let secp_ctx = Secp256k1::new();
2381                 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2382                 let channel_ready = msgs::ChannelReady {
2383                         channel_id: [2; 32],
2384                         next_per_commitment_point: pubkey_1,
2385                         short_channel_id_alias: None,
2386                 };
2387                 let encoded_value = channel_ready.encode();
2388                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2389                 assert_eq!(encoded_value, target_value);
2390         }
2391
2392         fn do_encoding_shutdown(script_type: u8) {
2393                 let secp_ctx = Secp256k1::new();
2394                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2395                 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
2396                 let shutdown = msgs::Shutdown {
2397                         channel_id: [2; 32],
2398                         scriptpubkey:
2399                                      if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey() }
2400                                 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey() }
2401                                 else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).unwrap().script_pubkey() }
2402                                 else                     { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
2403                 };
2404                 let encoded_value = shutdown.encode();
2405                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
2406                 if script_type == 1 {
2407                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2408                 } else if script_type == 2 {
2409                         target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
2410                 } else if script_type == 3 {
2411                         target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
2412                 } else if script_type == 4 {
2413                         target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
2414                 }
2415                 assert_eq!(encoded_value, target_value);
2416         }
2417
2418         #[test]
2419         fn encoding_shutdown() {
2420                 do_encoding_shutdown(1);
2421                 do_encoding_shutdown(2);
2422                 do_encoding_shutdown(3);
2423                 do_encoding_shutdown(4);
2424         }
2425
2426         #[test]
2427         fn encoding_closing_signed() {
2428                 let secp_ctx = Secp256k1::new();
2429                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2430                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2431                 let closing_signed = msgs::ClosingSigned {
2432                         channel_id: [2; 32],
2433                         fee_satoshis: 2316138423780173,
2434                         signature: sig_1,
2435                         fee_range: None,
2436                 };
2437                 let encoded_value = closing_signed.encode();
2438                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2439                 assert_eq!(encoded_value, target_value);
2440                 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value)).unwrap(), closing_signed);
2441
2442                 let closing_signed_with_range = msgs::ClosingSigned {
2443                         channel_id: [2; 32],
2444                         fee_satoshis: 2316138423780173,
2445                         signature: sig_1,
2446                         fee_range: Some(msgs::ClosingSignedFeeRange {
2447                                 min_fee_satoshis: 0xdeadbeef,
2448                                 max_fee_satoshis: 0x1badcafe01234567,
2449                         }),
2450                 };
2451                 let encoded_value_with_range = closing_signed_with_range.encode();
2452                 let target_value_with_range = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
2453                 assert_eq!(encoded_value_with_range, target_value_with_range);
2454                 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value_with_range)).unwrap(),
2455                         closing_signed_with_range);
2456         }
2457
2458         #[test]
2459         fn encoding_update_add_htlc() {
2460                 let secp_ctx = Secp256k1::new();
2461                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2462                 let onion_routing_packet = msgs::OnionPacket {
2463                         version: 255,
2464                         public_key: Ok(pubkey_1),
2465                         hop_data: [1; 20*65],
2466                         hmac: [2; 32]
2467                 };
2468                 let update_add_htlc = msgs::UpdateAddHTLC {
2469                         channel_id: [2; 32],
2470                         htlc_id: 2316138423780173,
2471                         amount_msat: 3608586615801332854,
2472                         payment_hash: PaymentHash([1; 32]),
2473                         cltv_expiry: 821716,
2474                         onion_routing_packet
2475                 };
2476                 let encoded_value = update_add_htlc.encode();
2477                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2478                 assert_eq!(encoded_value, target_value);
2479         }
2480
2481         #[test]
2482         fn encoding_update_fulfill_htlc() {
2483                 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2484                         channel_id: [2; 32],
2485                         htlc_id: 2316138423780173,
2486                         payment_preimage: PaymentPreimage([1; 32]),
2487                 };
2488                 let encoded_value = update_fulfill_htlc.encode();
2489                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2490                 assert_eq!(encoded_value, target_value);
2491         }
2492
2493         #[test]
2494         fn encoding_update_fail_htlc() {
2495                 let reason = OnionErrorPacket {
2496                         data: [1; 32].to_vec(),
2497                 };
2498                 let update_fail_htlc = msgs::UpdateFailHTLC {
2499                         channel_id: [2; 32],
2500                         htlc_id: 2316138423780173,
2501                         reason
2502                 };
2503                 let encoded_value = update_fail_htlc.encode();
2504                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2505                 assert_eq!(encoded_value, target_value);
2506         }
2507
2508         #[test]
2509         fn encoding_update_fail_malformed_htlc() {
2510                 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2511                         channel_id: [2; 32],
2512                         htlc_id: 2316138423780173,
2513                         sha256_of_onion: [1; 32],
2514                         failure_code: 255
2515                 };
2516                 let encoded_value = update_fail_malformed_htlc.encode();
2517                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2518                 assert_eq!(encoded_value, target_value);
2519         }
2520
2521         fn do_encoding_commitment_signed(htlcs: bool) {
2522                 let secp_ctx = Secp256k1::new();
2523                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2524                 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2525                 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2526                 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2527                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2528                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2529                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2530                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2531                 let commitment_signed = msgs::CommitmentSigned {
2532                         channel_id: [2; 32],
2533                         signature: sig_1,
2534                         htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2535                 };
2536                 let encoded_value = commitment_signed.encode();
2537                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2538                 if htlcs {
2539                         target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2540                 } else {
2541                         target_value.append(&mut hex::decode("0000").unwrap());
2542                 }
2543                 assert_eq!(encoded_value, target_value);
2544         }
2545
2546         #[test]
2547         fn encoding_commitment_signed() {
2548                 do_encoding_commitment_signed(true);
2549                 do_encoding_commitment_signed(false);
2550         }
2551
2552         #[test]
2553         fn encoding_revoke_and_ack() {
2554                 let secp_ctx = Secp256k1::new();
2555                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2556                 let raa = msgs::RevokeAndACK {
2557                         channel_id: [2; 32],
2558                         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],
2559                         next_per_commitment_point: pubkey_1,
2560                 };
2561                 let encoded_value = raa.encode();
2562                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2563                 assert_eq!(encoded_value, target_value);
2564         }
2565
2566         #[test]
2567         fn encoding_update_fee() {
2568                 let update_fee = msgs::UpdateFee {
2569                         channel_id: [2; 32],
2570                         feerate_per_kw: 20190119,
2571                 };
2572                 let encoded_value = update_fee.encode();
2573                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2574                 assert_eq!(encoded_value, target_value);
2575         }
2576
2577         #[test]
2578         fn encoding_init() {
2579                 assert_eq!(msgs::Init {
2580                         features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2581                         remote_network_address: None,
2582                 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2583                 assert_eq!(msgs::Init {
2584                         features: InitFeatures::from_le_bytes(vec![0xFF]),
2585                         remote_network_address: None,
2586                 }.encode(), hex::decode("0001ff0001ff").unwrap());
2587                 assert_eq!(msgs::Init {
2588                         features: InitFeatures::from_le_bytes(vec![]),
2589                         remote_network_address: None,
2590                 }.encode(), hex::decode("00000000").unwrap());
2591
2592                 let init_msg = msgs::Init { features: InitFeatures::from_le_bytes(vec![]),
2593                         remote_network_address: Some(msgs::NetAddress::IPv4 {
2594                                 addr: [127, 0, 0, 1],
2595                                 port: 1000,
2596                         }),
2597                 };
2598                 let encoded_value = init_msg.encode();
2599                 let target_value = hex::decode("000000000307017f00000103e8").unwrap();
2600                 assert_eq!(encoded_value, target_value);
2601                 assert_eq!(msgs::Init::read(&mut Cursor::new(&target_value)).unwrap(), init_msg);
2602         }
2603
2604         #[test]
2605         fn encoding_error() {
2606                 let error = msgs::ErrorMessage {
2607                         channel_id: [2; 32],
2608                         data: String::from("rust-lightning"),
2609                 };
2610                 let encoded_value = error.encode();
2611                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2612                 assert_eq!(encoded_value, target_value);
2613         }
2614
2615         #[test]
2616         fn encoding_warning() {
2617                 let error = msgs::WarningMessage {
2618                         channel_id: [2; 32],
2619                         data: String::from("rust-lightning"),
2620                 };
2621                 let encoded_value = error.encode();
2622                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2623                 assert_eq!(encoded_value, target_value);
2624         }
2625
2626         #[test]
2627         fn encoding_ping() {
2628                 let ping = msgs::Ping {
2629                         ponglen: 64,
2630                         byteslen: 64
2631                 };
2632                 let encoded_value = ping.encode();
2633                 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2634                 assert_eq!(encoded_value, target_value);
2635         }
2636
2637         #[test]
2638         fn encoding_pong() {
2639                 let pong = msgs::Pong {
2640                         byteslen: 64
2641                 };
2642                 let encoded_value = pong.encode();
2643                 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2644                 assert_eq!(encoded_value, target_value);
2645         }
2646
2647         #[test]
2648         fn encoding_nonfinal_onion_hop_data() {
2649                 let mut msg = msgs::OnionHopData {
2650                         format: OnionHopDataFormat::NonFinalNode {
2651                                 short_channel_id: 0xdeadbeef1bad1dea,
2652                         },
2653                         amt_to_forward: 0x0badf00d01020304,
2654                         outgoing_cltv_value: 0xffffffff,
2655                 };
2656                 let encoded_value = msg.encode();
2657                 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2658                 assert_eq!(encoded_value, target_value);
2659                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2660                 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2661                         assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2662                 } else { panic!(); }
2663                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2664                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2665         }
2666
2667         #[test]
2668         fn encoding_final_onion_hop_data() {
2669                 let mut msg = msgs::OnionHopData {
2670                         format: OnionHopDataFormat::FinalNode {
2671                                 payment_data: None,
2672                                 keysend_preimage: None,
2673                         },
2674                         amt_to_forward: 0x0badf00d01020304,
2675                         outgoing_cltv_value: 0xffffffff,
2676                 };
2677                 let encoded_value = msg.encode();
2678                 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2679                 assert_eq!(encoded_value, target_value);
2680                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2681                 if let OnionHopDataFormat::FinalNode { payment_data: None, .. } = msg.format { } else { panic!(); }
2682                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2683                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2684         }
2685
2686         #[test]
2687         fn encoding_final_onion_hop_data_with_secret() {
2688                 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
2689                 let mut msg = msgs::OnionHopData {
2690                         format: OnionHopDataFormat::FinalNode {
2691                                 payment_data: Some(FinalOnionHopData {
2692                                         payment_secret: expected_payment_secret,
2693                                         total_msat: 0x1badca1f
2694                                 }),
2695                                 keysend_preimage: None,
2696                         },
2697                         amt_to_forward: 0x0badf00d01020304,
2698                         outgoing_cltv_value: 0xffffffff,
2699                 };
2700                 let encoded_value = msg.encode();
2701                 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2702                 assert_eq!(encoded_value, target_value);
2703                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2704                 if let OnionHopDataFormat::FinalNode {
2705                         payment_data: Some(FinalOnionHopData {
2706                                 payment_secret,
2707                                 total_msat: 0x1badca1f
2708                         }),
2709                         keysend_preimage: None,
2710                 } = msg.format {
2711                         assert_eq!(payment_secret, expected_payment_secret);
2712                 } else { panic!(); }
2713                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2714                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2715         }
2716
2717         #[test]
2718         fn query_channel_range_end_blocknum() {
2719                 let tests: Vec<(u32, u32, u32)> = vec![
2720                         (10000, 1500, 11500),
2721                         (0, 0xffffffff, 0xffffffff),
2722                         (1, 0xffffffff, 0xffffffff),
2723                 ];
2724
2725                 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
2726                         let sut = msgs::QueryChannelRange {
2727                                 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2728                                 first_blocknum,
2729                                 number_of_blocks,
2730                         };
2731                         assert_eq!(sut.end_blocknum(), expected);
2732                 }
2733         }
2734
2735         #[test]
2736         fn encoding_query_channel_range() {
2737                 let mut query_channel_range = msgs::QueryChannelRange {
2738                         chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2739                         first_blocknum: 100000,
2740                         number_of_blocks: 1500,
2741                 };
2742                 let encoded_value = query_channel_range.encode();
2743                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000186a0000005dc").unwrap();
2744                 assert_eq!(encoded_value, target_value);
2745
2746                 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2747                 assert_eq!(query_channel_range.first_blocknum, 100000);
2748                 assert_eq!(query_channel_range.number_of_blocks, 1500);
2749         }
2750
2751         #[test]
2752         fn encoding_reply_channel_range() {
2753                 do_encoding_reply_channel_range(0);
2754                 do_encoding_reply_channel_range(1);
2755         }
2756
2757         fn do_encoding_reply_channel_range(encoding_type: u8) {
2758                 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000b8a06000005dc01").unwrap();
2759                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2760                 let mut reply_channel_range = msgs::ReplyChannelRange {
2761                         chain_hash: expected_chain_hash,
2762                         first_blocknum: 756230,
2763                         number_of_blocks: 1500,
2764                         sync_complete: true,
2765                         short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2766                 };
2767
2768                 if encoding_type == 0 {
2769                         target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2770                         let encoded_value = reply_channel_range.encode();
2771                         assert_eq!(encoded_value, target_value);
2772
2773                         reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2774                         assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
2775                         assert_eq!(reply_channel_range.first_blocknum, 756230);
2776                         assert_eq!(reply_channel_range.number_of_blocks, 1500);
2777                         assert_eq!(reply_channel_range.sync_complete, true);
2778                         assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
2779                         assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
2780                         assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
2781                 } else {
2782                         target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2783                         let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2784                         assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2785                 }
2786         }
2787
2788         #[test]
2789         fn encoding_query_short_channel_ids() {
2790                 do_encoding_query_short_channel_ids(0);
2791                 do_encoding_query_short_channel_ids(1);
2792         }
2793
2794         fn do_encoding_query_short_channel_ids(encoding_type: u8) {
2795                 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206").unwrap();
2796                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2797                 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
2798                         chain_hash: expected_chain_hash,
2799                         short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2800                 };
2801
2802                 if encoding_type == 0 {
2803                         target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2804                         let encoded_value = query_short_channel_ids.encode();
2805                         assert_eq!(encoded_value, target_value);
2806
2807                         query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2808                         assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
2809                         assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
2810                         assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
2811                         assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
2812                 } else {
2813                         target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2814                         let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2815                         assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2816                 }
2817         }
2818
2819         #[test]
2820         fn encoding_reply_short_channel_ids_end() {
2821                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2822                 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
2823                         chain_hash: expected_chain_hash,
2824                         full_information: true,
2825                 };
2826                 let encoded_value = reply_short_channel_ids_end.encode();
2827                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e220601").unwrap();
2828                 assert_eq!(encoded_value, target_value);
2829
2830                 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2831                 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
2832                 assert_eq!(reply_short_channel_ids_end.full_information, true);
2833         }
2834
2835         #[test]
2836         fn encoding_gossip_timestamp_filter(){
2837                 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2838                 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
2839                         chain_hash: expected_chain_hash,
2840                         first_timestamp: 1590000000,
2841                         timestamp_range: 0xffff_ffff,
2842                 };
2843                 let encoded_value = gossip_timestamp_filter.encode();
2844                 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e22065ec57980ffffffff").unwrap();
2845                 assert_eq!(encoded_value, target_value);
2846
2847                 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2848                 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
2849                 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
2850                 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
2851         }
2852
2853         #[test]
2854         fn decode_onion_hop_data_len_as_bigsize() {
2855                 // Tests that we can decode an onion payload that is >253 bytes.
2856                 // Previously, receiving a payload of this size could've caused us to fail to decode a valid
2857                 // payload, because we were decoding the length (a BigSize, big-endian) as a VarInt
2858                 // (little-endian).
2859
2860                 // Encode a test onion payload with a big custom TLV such that it's >253 bytes, forcing the
2861                 // payload length to be encoded over multiple bytes rather than a single u8.
2862                 let big_payload = encode_big_payload().unwrap();
2863                 let mut rd = Cursor::new(&big_payload[..]);
2864                 <msgs::OnionHopData as Readable>::read(&mut rd).unwrap();
2865         }
2866         // see above test, needs to be a separate method for use of the serialization macros.
2867         fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
2868                 use crate::util::ser::HighZeroBytesDroppedBigSize;
2869                 let payload = msgs::OnionHopData {
2870                         format: OnionHopDataFormat::NonFinalNode {
2871                                 short_channel_id: 0xdeadbeef1bad1dea,
2872                         },
2873                         amt_to_forward: 1000,
2874                         outgoing_cltv_value: 0xffffffff,
2875                 };
2876                 let mut encoded_payload = Vec::new();
2877                 let test_bytes = vec![42u8; 1000];
2878                 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = payload.format {
2879                         encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
2880                                 (1, test_bytes, vec_type),
2881                                 (2, HighZeroBytesDroppedBigSize(payload.amt_to_forward), required),
2882                                 (4, HighZeroBytesDroppedBigSize(payload.outgoing_cltv_value), required),
2883                                 (6, short_channel_id, required)
2884                         });
2885                 }
2886                 Ok(encoded_payload)
2887         }
2888 }