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