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