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