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