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