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