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