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