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