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