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