Relicense as dual Apache-2.0 + MIT
[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;
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 pub struct Init {
68         #[cfg(not(feature = "fuzztarget"))]
69         pub(crate) features: InitFeatures,
70         #[cfg(feature = "fuzztarget")]
71         pub features: InitFeatures,
72 }
73
74 /// An error message to be sent or received from a peer
75 #[derive(Clone)]
76 pub struct ErrorMessage {
77         pub(crate) channel_id: [u8; 32],
78         pub(crate) data: String,
79 }
80
81 /// A ping message to be sent or received from a peer
82 pub struct Ping {
83         pub(crate) ponglen: u16,
84         pub(crate) byteslen: u16,
85 }
86
87 /// A pong message to be sent or received from a peer
88 pub struct Pong {
89         pub(crate) byteslen: u16,
90 }
91
92 /// An open_channel message to be sent or received from a peer
93 #[derive(Clone)]
94 pub struct OpenChannel {
95         pub(crate) chain_hash: BlockHash,
96         pub(crate) temporary_channel_id: [u8; 32],
97         pub(crate) funding_satoshis: u64,
98         pub(crate) push_msat: u64,
99         pub(crate) dust_limit_satoshis: u64,
100         pub(crate) max_htlc_value_in_flight_msat: u64,
101         pub(crate) channel_reserve_satoshis: u64,
102         pub(crate) htlc_minimum_msat: u64,
103         pub(crate) feerate_per_kw: u32,
104         pub(crate) to_self_delay: u16,
105         pub(crate) max_accepted_htlcs: u16,
106         pub(crate) funding_pubkey: PublicKey,
107         pub(crate) revocation_basepoint: PublicKey,
108         pub(crate) payment_point: PublicKey,
109         pub(crate) delayed_payment_basepoint: PublicKey,
110         pub(crate) htlc_basepoint: PublicKey,
111         pub(crate) first_per_commitment_point: PublicKey,
112         pub(crate) channel_flags: u8,
113         pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
114 }
115
116 /// An accept_channel message to be sent or received from a peer
117 #[derive(Clone)]
118 pub struct AcceptChannel {
119         pub(crate) temporary_channel_id: [u8; 32],
120         pub(crate) dust_limit_satoshis: u64,
121         pub(crate) max_htlc_value_in_flight_msat: u64,
122         pub(crate) channel_reserve_satoshis: u64,
123         pub(crate) htlc_minimum_msat: u64,
124         pub(crate) minimum_depth: u32,
125         pub(crate) to_self_delay: u16,
126         pub(crate) max_accepted_htlcs: u16,
127         pub(crate) funding_pubkey: PublicKey,
128         pub(crate) revocation_basepoint: PublicKey,
129         pub(crate) payment_point: PublicKey,
130         pub(crate) delayed_payment_basepoint: PublicKey,
131         pub(crate) htlc_basepoint: PublicKey,
132         pub(crate) first_per_commitment_point: PublicKey,
133         pub(crate) shutdown_scriptpubkey: OptionalField<Script>
134 }
135
136 /// A funding_created message to be sent or received from a peer
137 #[derive(Clone)]
138 pub struct FundingCreated {
139         pub(crate) temporary_channel_id: [u8; 32],
140         pub(crate) funding_txid: Txid,
141         pub(crate) funding_output_index: u16,
142         pub(crate) signature: Signature,
143 }
144
145 /// A funding_signed message to be sent or received from a peer
146 #[derive(Clone)]
147 pub struct FundingSigned {
148         pub(crate) channel_id: [u8; 32],
149         pub(crate) signature: Signature,
150 }
151
152 /// A funding_locked message to be sent or received from a peer
153 #[derive(Clone, PartialEq)]
154 #[allow(missing_docs)]
155 pub struct FundingLocked {
156         pub channel_id: [u8; 32],
157         pub next_per_commitment_point: PublicKey,
158 }
159
160 /// A shutdown message to be sent or received from a peer
161 #[derive(Clone, PartialEq)]
162 pub struct Shutdown {
163         pub(crate) channel_id: [u8; 32],
164         pub(crate) scriptpubkey: Script,
165 }
166
167 /// A closing_signed message to be sent or received from a peer
168 #[derive(Clone, PartialEq)]
169 pub struct ClosingSigned {
170         pub(crate) channel_id: [u8; 32],
171         pub(crate) fee_satoshis: u64,
172         pub(crate) signature: Signature,
173 }
174
175 /// An update_add_htlc message to be sent or received from a peer
176 #[derive(Clone, PartialEq)]
177 pub struct UpdateAddHTLC {
178         pub(crate) channel_id: [u8; 32],
179         pub(crate) htlc_id: u64,
180         pub(crate) amount_msat: u64,
181         pub(crate) payment_hash: PaymentHash,
182         pub(crate) cltv_expiry: u32,
183         pub(crate) onion_routing_packet: OnionPacket,
184 }
185
186 /// An update_fulfill_htlc message to be sent or received from a peer
187 #[derive(Clone, PartialEq)]
188 pub struct UpdateFulfillHTLC {
189         pub(crate) channel_id: [u8; 32],
190         pub(crate) htlc_id: u64,
191         pub(crate) payment_preimage: PaymentPreimage,
192 }
193
194 /// An update_fail_htlc message to be sent or received from a peer
195 #[derive(Clone, PartialEq)]
196 pub struct UpdateFailHTLC {
197         pub(crate) channel_id: [u8; 32],
198         pub(crate) htlc_id: u64,
199         pub(crate) reason: OnionErrorPacket,
200 }
201
202 /// An update_fail_malformed_htlc message to be sent or received from a peer
203 #[derive(Clone, PartialEq)]
204 pub struct UpdateFailMalformedHTLC {
205         pub(crate) channel_id: [u8; 32],
206         pub(crate) htlc_id: u64,
207         pub(crate) sha256_of_onion: [u8; 32],
208         pub(crate) failure_code: u16,
209 }
210
211 /// A commitment_signed message to be sent or received from a peer
212 #[derive(Clone, PartialEq)]
213 pub struct CommitmentSigned {
214         pub(crate) channel_id: [u8; 32],
215         pub(crate) signature: Signature,
216         pub(crate) htlc_signatures: Vec<Signature>,
217 }
218
219 /// A revoke_and_ack message to be sent or received from a peer
220 #[derive(Clone, PartialEq)]
221 pub struct RevokeAndACK {
222         pub(crate) channel_id: [u8; 32],
223         pub(crate) per_commitment_secret: [u8; 32],
224         pub(crate) next_per_commitment_point: PublicKey,
225 }
226
227 /// An update_fee message to be sent or received from a peer
228 #[derive(PartialEq, Clone)]
229 pub struct UpdateFee {
230         pub(crate) channel_id: [u8; 32],
231         pub(crate) feerate_per_kw: u32,
232 }
233
234 #[derive(PartialEq, Clone)]
235 pub(crate) struct DataLossProtect {
236         pub(crate) your_last_per_commitment_secret: [u8; 32],
237         pub(crate) my_current_per_commitment_point: PublicKey,
238 }
239
240 /// A channel_reestablish message to be sent or received from a peer
241 #[derive(PartialEq, Clone)]
242 pub struct ChannelReestablish {
243         pub(crate) channel_id: [u8; 32],
244         pub(crate) next_local_commitment_number: u64,
245         pub(crate) next_remote_commitment_number: u64,
246         pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
247 }
248
249 /// An announcement_signatures message to be sent or received from a peer
250 #[derive(PartialEq, Clone, Debug)]
251 pub struct AnnouncementSignatures {
252         pub(crate) channel_id: [u8; 32],
253         pub(crate) short_channel_id: u64,
254         pub(crate) node_signature: Signature,
255         pub(crate) bitcoin_signature: Signature,
256 }
257
258 /// An address which can be used to connect to a remote peer
259 #[derive(Clone, PartialEq, Debug)]
260 pub enum NetAddress {
261         /// An IPv4 address/port on which the peer is listening.
262         IPv4 {
263                 /// The 4-byte IPv4 address
264                 addr: [u8; 4],
265                 /// The port on which the node is listening
266                 port: u16,
267         },
268         /// An IPv6 address/port on which the peer is listening.
269         IPv6 {
270                 /// The 16-byte IPv6 address
271                 addr: [u8; 16],
272                 /// The port on which the node is listening
273                 port: u16,
274         },
275         /// An old-style Tor onion address/port on which the peer is listening.
276         OnionV2 {
277                 /// The bytes (usually encoded in base32 with ".onion" appended)
278                 addr: [u8; 10],
279                 /// The port on which the node is listening
280                 port: u16,
281         },
282         /// A new-style Tor onion address/port on which the peer is listening.
283         /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
284         /// wrap as base32 and append ".onion".
285         OnionV3 {
286                 /// The ed25519 long-term public key of the peer
287                 ed25519_pubkey: [u8; 32],
288                 /// The checksum of the pubkey and version, as included in the onion address
289                 checksum: u16,
290                 /// The version byte, as defined by the Tor Onion v3 spec.
291                 version: u8,
292                 /// The port on which the node is listening
293                 port: u16,
294         },
295 }
296 impl NetAddress {
297         fn get_id(&self) -> u8 {
298                 match self {
299                         &NetAddress::IPv4 {..} => { 1 },
300                         &NetAddress::IPv6 {..} => { 2 },
301                         &NetAddress::OnionV2 {..} => { 3 },
302                         &NetAddress::OnionV3 {..} => { 4 },
303                 }
304         }
305
306         /// Strict byte-length of address descriptor, 1-byte type not recorded
307         fn len(&self) -> u16 {
308                 match self {
309                         &NetAddress::IPv4 { .. } => { 6 },
310                         &NetAddress::IPv6 { .. } => { 18 },
311                         &NetAddress::OnionV2 { .. } => { 12 },
312                         &NetAddress::OnionV3 { .. } => { 37 },
313                 }
314         }
315
316         /// The maximum length of any address descriptor, not including the 1-byte type
317         pub(crate) const MAX_LEN: u16 = 37;
318 }
319
320 impl Writeable for NetAddress {
321         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
322                 match self {
323                         &NetAddress::IPv4 { ref addr, ref port } => {
324                                 1u8.write(writer)?;
325                                 addr.write(writer)?;
326                                 port.write(writer)?;
327                         },
328                         &NetAddress::IPv6 { ref addr, ref port } => {
329                                 2u8.write(writer)?;
330                                 addr.write(writer)?;
331                                 port.write(writer)?;
332                         },
333                         &NetAddress::OnionV2 { ref addr, ref port } => {
334                                 3u8.write(writer)?;
335                                 addr.write(writer)?;
336                                 port.write(writer)?;
337                         },
338                         &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
339                                 4u8.write(writer)?;
340                                 ed25519_pubkey.write(writer)?;
341                                 checksum.write(writer)?;
342                                 version.write(writer)?;
343                                 port.write(writer)?;
344                         }
345                 }
346                 Ok(())
347         }
348 }
349
350 impl Readable for Result<NetAddress, u8> {
351         fn read<R: Read>(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
352                 let byte = <u8 as Readable>::read(reader)?;
353                 match byte {
354                         1 => {
355                                 Ok(Ok(NetAddress::IPv4 {
356                                         addr: Readable::read(reader)?,
357                                         port: Readable::read(reader)?,
358                                 }))
359                         },
360                         2 => {
361                                 Ok(Ok(NetAddress::IPv6 {
362                                         addr: Readable::read(reader)?,
363                                         port: Readable::read(reader)?,
364                                 }))
365                         },
366                         3 => {
367                                 Ok(Ok(NetAddress::OnionV2 {
368                                         addr: Readable::read(reader)?,
369                                         port: Readable::read(reader)?,
370                                 }))
371                         },
372                         4 => {
373                                 Ok(Ok(NetAddress::OnionV3 {
374                                         ed25519_pubkey: Readable::read(reader)?,
375                                         checksum: Readable::read(reader)?,
376                                         version: Readable::read(reader)?,
377                                         port: Readable::read(reader)?,
378                                 }))
379                         },
380                         _ => return Ok(Err(byte)),
381                 }
382         }
383 }
384
385 // Only exposed as broadcast of node_announcement should be filtered by node_id
386 /// The unsigned part of a node_announcement
387 #[derive(PartialEq, Clone, Debug)]
388 pub struct UnsignedNodeAnnouncement {
389         pub(crate) features: NodeFeatures,
390         pub(crate) timestamp: u32,
391         /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
392         /// to this node).
393         pub        node_id: PublicKey,
394         pub(crate) rgb: [u8; 3],
395         pub(crate) alias: [u8; 32],
396         /// List of addresses on which this node is reachable. Note that you may only have up to one
397         /// address of each type, if you have more, they may be silently discarded or we may panic!
398         pub(crate) addresses: Vec<NetAddress>,
399         pub(crate) excess_address_data: Vec<u8>,
400         pub(crate) excess_data: Vec<u8>,
401 }
402 #[derive(PartialEq, Clone, Debug)]
403 /// A node_announcement message to be sent or received from a peer
404 pub struct NodeAnnouncement {
405         pub(crate) signature: Signature,
406         pub(crate) contents: UnsignedNodeAnnouncement,
407 }
408
409 // Only exposed as broadcast of channel_announcement should be filtered by node_id
410 /// The unsigned part of a channel_announcement
411 #[derive(PartialEq, Clone, Debug)]
412 pub struct UnsignedChannelAnnouncement {
413         pub(crate) features: ChannelFeatures,
414         pub(crate) chain_hash: BlockHash,
415         pub(crate) short_channel_id: u64,
416         /// One of the two node_ids which are endpoints of this channel
417         pub        node_id_1: PublicKey,
418         /// The other of the two node_ids which are endpoints of this channel
419         pub        node_id_2: PublicKey,
420         pub(crate) bitcoin_key_1: PublicKey,
421         pub(crate) bitcoin_key_2: PublicKey,
422         pub(crate) excess_data: Vec<u8>,
423 }
424 /// A channel_announcement message to be sent or received from a peer
425 #[derive(PartialEq, Clone, Debug)]
426 pub struct ChannelAnnouncement {
427         pub(crate) node_signature_1: Signature,
428         pub(crate) node_signature_2: Signature,
429         pub(crate) bitcoin_signature_1: Signature,
430         pub(crate) bitcoin_signature_2: Signature,
431         pub(crate) contents: UnsignedChannelAnnouncement,
432 }
433
434 #[derive(PartialEq, Clone, Debug)]
435 pub(crate) struct UnsignedChannelUpdate {
436         pub(crate) chain_hash: BlockHash,
437         pub(crate) short_channel_id: u64,
438         pub(crate) timestamp: u32,
439         pub(crate) flags: u8,
440         pub(crate) cltv_expiry_delta: u16,
441         pub(crate) htlc_minimum_msat: u64,
442         pub(crate) htlc_maximum_msat: OptionalField<u64>,
443         pub(crate) fee_base_msat: u32,
444         pub(crate) fee_proportional_millionths: u32,
445         pub(crate) excess_data: Vec<u8>,
446 }
447 /// A channel_update message to be sent or received from a peer
448 #[derive(PartialEq, Clone, Debug)]
449 pub struct ChannelUpdate {
450         pub(crate) signature: Signature,
451         pub(crate) contents: UnsignedChannelUpdate,
452 }
453
454 /// Used to put an error message in a LightningError
455 #[derive(Clone)]
456 pub enum ErrorAction {
457         /// The peer took some action which made us think they were useless. Disconnect them.
458         DisconnectPeer {
459                 /// An error message which we should make an effort to send before we disconnect.
460                 msg: Option<ErrorMessage>
461         },
462         /// The peer did something harmless that we weren't able to process, just log and ignore
463         IgnoreError,
464         /// The peer did something incorrect. Tell them.
465         SendErrorMessage {
466                 /// The message to send.
467                 msg: ErrorMessage
468         },
469 }
470
471 /// An Err type for failure to process messages.
472 pub struct LightningError {
473         /// A human-readable message describing the error
474         pub err: String,
475         /// The action which should be taken against the offending peer.
476         pub action: ErrorAction,
477 }
478
479 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
480 /// transaction updates if they were pending.
481 #[derive(PartialEq, Clone)]
482 pub struct CommitmentUpdate {
483         /// update_add_htlc messages which should be sent
484         pub update_add_htlcs: Vec<UpdateAddHTLC>,
485         /// update_fulfill_htlc messages which should be sent
486         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
487         /// update_fail_htlc messages which should be sent
488         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
489         /// update_fail_malformed_htlc messages which should be sent
490         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
491         /// An update_fee message which should be sent
492         pub update_fee: Option<UpdateFee>,
493         /// Finally, the commitment_signed message which should be sent
494         pub commitment_signed: CommitmentSigned,
495 }
496
497 /// The information we received from a peer along the route of a payment we originated. This is
498 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
499 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
500 #[derive(Clone)]
501 pub enum HTLCFailChannelUpdate {
502         /// We received an error which included a full ChannelUpdate message.
503         ChannelUpdateMessage {
504                 /// The unwrapped message we received
505                 msg: ChannelUpdate,
506         },
507         /// We received an error which indicated only that a channel has been closed
508         ChannelClosed {
509                 /// The short_channel_id which has now closed.
510                 short_channel_id: u64,
511                 /// when this true, this channel should be permanently removed from the
512                 /// consideration. Otherwise, this channel can be restored as new channel_update is received
513                 is_permanent: bool,
514         },
515         /// We received an error which indicated only that a node has failed
516         NodeFailure {
517                 /// The node_id that has failed.
518                 node_id: PublicKey,
519                 /// when this true, node should be permanently removed from the
520                 /// consideration. Otherwise, the channels connected to this node can be
521                 /// restored as new channel_update is received
522                 is_permanent: bool,
523         }
524 }
525
526 /// Messages could have optional fields to use with extended features
527 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
528 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
529 /// separate enum type for them.
530 #[derive(Clone, PartialEq, Debug)]
531 pub enum OptionalField<T> {
532         /// Optional field is included in message
533         Present(T),
534         /// Optional field is absent in message
535         Absent
536 }
537
538 /// A trait to describe an object which can receive channel messages.
539 ///
540 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
541 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
542 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
543         //Channel init:
544         /// Handle an incoming open_channel message from the given peer.
545         fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
546         /// Handle an incoming accept_channel message from the given peer.
547         fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
548         /// Handle an incoming funding_created message from the given peer.
549         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
550         /// Handle an incoming funding_signed message from the given peer.
551         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
552         /// Handle an incoming funding_locked message from the given peer.
553         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
554
555         // Channl close:
556         /// Handle an incoming shutdown message from the given peer.
557         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
558         /// Handle an incoming closing_signed message from the given peer.
559         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
560
561         // HTLC handling:
562         /// Handle an incoming update_add_htlc message from the given peer.
563         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
564         /// Handle an incoming update_fulfill_htlc message from the given peer.
565         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
566         /// Handle an incoming update_fail_htlc message from the given peer.
567         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
568         /// Handle an incoming update_fail_malformed_htlc message from the given peer.
569         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
570         /// Handle an incoming commitment_signed message from the given peer.
571         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
572         /// Handle an incoming revoke_and_ack message from the given peer.
573         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
574
575         /// Handle an incoming update_fee message from the given peer.
576         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
577
578         // Channel-to-announce:
579         /// Handle an incoming announcement_signatures message from the given peer.
580         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
581
582         // Connection loss/reestablish:
583         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
584         /// is believed to be possible in the future (eg they're sending us messages we don't
585         /// understand or indicate they require unknown feature bits), no_connection_possible is set
586         /// and any outstanding channels should be failed.
587         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
588
589         /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
590         fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init);
591         /// Handle an incoming channel_reestablish message from the given peer.
592         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
593
594         // Error:
595         /// Handle an incoming error message from the given peer.
596         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
597 }
598
599 /// A trait to describe an object which can receive routing messages.
600 pub trait RoutingMessageHandler : Send + Sync {
601         /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
602         /// false or returning an Err otherwise.
603         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
604         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
605         /// or returning an Err otherwise.
606         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
607         /// Handle an incoming channel_update message, returning true if it should be forwarded on,
608         /// false or returning an Err otherwise.
609         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
610         /// Handle some updates to the route graph that we learned due to an outbound failed payment.
611         fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
612         /// Gets a subset of the channel announcements and updates required to dump our routing table
613         /// to a remote node, starting at the short_channel_id indicated by starting_point and
614         /// including the batch_amount entries immediately higher in numerical value than starting_point.
615         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
616         /// Gets a subset of the node announcements required to dump our routing table to a remote node,
617         /// starting at the node *after* the provided publickey and including batch_amount entries
618         /// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
619         /// If None is provided for starting_point, we start at the first node.
620         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
621         /// Returns whether a full sync should be requested from a peer.
622         fn should_request_full_sync(&self, node_id: &PublicKey) -> bool;
623 }
624
625 mod fuzzy_internal_msgs {
626         use ln::channelmanager::PaymentSecret;
627
628         // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
629         // them from untrusted input):
630         #[derive(Clone)]
631         pub(crate) struct FinalOnionHopData {
632                 pub(crate) payment_secret: PaymentSecret,
633                 /// The total value, in msat, of the payment as received by the ultimate recipient.
634                 /// Message serialization may panic if this value is more than 21 million Bitcoin.
635                 pub(crate) total_msat: u64,
636         }
637
638         pub(crate) enum OnionHopDataFormat {
639                 Legacy { // aka Realm-0
640                         short_channel_id: u64,
641                 },
642                 NonFinalNode {
643                         short_channel_id: u64,
644                 },
645                 FinalNode {
646                         payment_data: Option<FinalOnionHopData>,
647                 },
648         }
649
650         pub struct OnionHopData {
651                 pub(crate) format: OnionHopDataFormat,
652                 /// The value, in msat, of the payment after this hop's fee is deducted.
653                 /// Message serialization may panic if this value is more than 21 million Bitcoin.
654                 pub(crate) amt_to_forward: u64,
655                 pub(crate) outgoing_cltv_value: u32,
656                 // 12 bytes of 0-padding for Legacy format
657         }
658
659         pub struct DecodedOnionErrorPacket {
660                 pub(crate) hmac: [u8; 32],
661                 pub(crate) failuremsg: Vec<u8>,
662                 pub(crate) pad: Vec<u8>,
663         }
664 }
665 #[cfg(feature = "fuzztarget")]
666 pub use self::fuzzy_internal_msgs::*;
667 #[cfg(not(feature = "fuzztarget"))]
668 pub(crate) use self::fuzzy_internal_msgs::*;
669
670 #[derive(Clone)]
671 pub(crate) struct OnionPacket {
672         pub(crate) version: u8,
673         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
674         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
675         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
676         pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
677         pub(crate) hop_data: [u8; 20*65],
678         pub(crate) hmac: [u8; 32],
679 }
680
681 impl PartialEq for OnionPacket {
682         fn eq(&self, other: &OnionPacket) -> bool {
683                 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
684                         if i != j { return false; }
685                 }
686                 self.version == other.version &&
687                         self.public_key == other.public_key &&
688                         self.hmac == other.hmac
689         }
690 }
691
692 #[derive(Clone, PartialEq)]
693 pub(crate) struct OnionErrorPacket {
694         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
695         // (TODO) We limit it in decode to much lower...
696         pub(crate) data: Vec<u8>,
697 }
698
699 impl fmt::Display for DecodeError {
700         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701                 match *self {
702                         DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
703                         DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
704                         DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
705                         DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
706                         DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
707                         DecodeError::Io(ref e) => e.fmt(f),
708                 }
709         }
710 }
711
712 impl fmt::Debug for LightningError {
713         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
714                 f.write_str(self.err.as_str())
715         }
716 }
717
718 impl From<::std::io::Error> for DecodeError {
719         fn from(e: ::std::io::Error) -> Self {
720                 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
721                         DecodeError::ShortRead
722                 } else {
723                         DecodeError::Io(e)
724                 }
725         }
726 }
727
728 impl Writeable for OptionalField<Script> {
729         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
730                 match *self {
731                         OptionalField::Present(ref script) => {
732                                 // Note that Writeable for script includes the 16-bit length tag for us
733                                 script.write(w)?;
734                         },
735                         OptionalField::Absent => {}
736                 }
737                 Ok(())
738         }
739 }
740
741 impl Readable for OptionalField<Script> {
742         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
743                 match <u16 as Readable>::read(r) {
744                         Ok(len) => {
745                                 let mut buf = vec![0; len as usize];
746                                 r.read_exact(&mut buf)?;
747                                 Ok(OptionalField::Present(Script::from(buf)))
748                         },
749                         Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
750                         Err(e) => Err(e)
751                 }
752         }
753 }
754
755 impl Writeable for OptionalField<u64> {
756         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
757                 match *self {
758                         OptionalField::Present(ref value) => {
759                                 value.write(w)?;
760                         },
761                         OptionalField::Absent => {}
762                 }
763                 Ok(())
764         }
765 }
766
767 impl Readable for OptionalField<u64> {
768         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
769                 let value: u64 = Readable::read(r)?;
770                 Ok(OptionalField::Present(value))
771         }
772 }
773
774
775 impl_writeable_len_match!(AcceptChannel, {
776                 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
777                 {_, 270}
778         }, {
779         temporary_channel_id,
780         dust_limit_satoshis,
781         max_htlc_value_in_flight_msat,
782         channel_reserve_satoshis,
783         htlc_minimum_msat,
784         minimum_depth,
785         to_self_delay,
786         max_accepted_htlcs,
787         funding_pubkey,
788         revocation_basepoint,
789         payment_point,
790         delayed_payment_basepoint,
791         htlc_basepoint,
792         first_per_commitment_point,
793         shutdown_scriptpubkey
794 });
795
796 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
797         channel_id,
798         short_channel_id,
799         node_signature,
800         bitcoin_signature
801 });
802
803 impl Writeable for ChannelReestablish {
804         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
805                 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
806                 self.channel_id.write(w)?;
807                 self.next_local_commitment_number.write(w)?;
808                 self.next_remote_commitment_number.write(w)?;
809                 match self.data_loss_protect {
810                         OptionalField::Present(ref data_loss_protect) => {
811                                 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
812                                 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
813                         },
814                         OptionalField::Absent => {}
815                 }
816                 Ok(())
817         }
818 }
819
820 impl Readable for ChannelReestablish{
821         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
822                 Ok(Self {
823                         channel_id: Readable::read(r)?,
824                         next_local_commitment_number: Readable::read(r)?,
825                         next_remote_commitment_number: Readable::read(r)?,
826                         data_loss_protect: {
827                                 match <[u8; 32] as Readable>::read(r) {
828                                         Ok(your_last_per_commitment_secret) =>
829                                                 OptionalField::Present(DataLossProtect {
830                                                         your_last_per_commitment_secret,
831                                                         my_current_per_commitment_point: Readable::read(r)?,
832                                                 }),
833                                         Err(DecodeError::ShortRead) => OptionalField::Absent,
834                                         Err(e) => return Err(e)
835                                 }
836                         }
837                 })
838         }
839 }
840
841 impl_writeable!(ClosingSigned, 32+8+64, {
842         channel_id,
843         fee_satoshis,
844         signature
845 });
846
847 impl_writeable_len_match!(CommitmentSigned, {
848                 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
849         }, {
850         channel_id,
851         signature,
852         htlc_signatures
853 });
854
855 impl_writeable_len_match!(DecodedOnionErrorPacket, {
856                 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
857         }, {
858         hmac,
859         failuremsg,
860         pad
861 });
862
863 impl_writeable!(FundingCreated, 32+32+2+64, {
864         temporary_channel_id,
865         funding_txid,
866         funding_output_index,
867         signature
868 });
869
870 impl_writeable!(FundingSigned, 32+64, {
871         channel_id,
872         signature
873 });
874
875 impl_writeable!(FundingLocked, 32+33, {
876         channel_id,
877         next_per_commitment_point
878 });
879
880 impl Writeable for Init {
881         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
882                 // global_features gets the bottom 13 bits of our features, and local_features gets all of
883                 // our relevant feature bits. This keeps us compatible with old nodes.
884                 self.features.write_up_to_13(w)?;
885                 self.features.write(w)
886         }
887 }
888
889 impl Readable for Init {
890         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
891                 let global_features: InitFeatures = Readable::read(r)?;
892                 let features: InitFeatures = Readable::read(r)?;
893                 Ok(Init {
894                         features: features.or(global_features),
895                 })
896         }
897 }
898
899 impl_writeable_len_match!(OpenChannel, {
900                 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
901                 { _, 319 }
902         }, {
903         chain_hash,
904         temporary_channel_id,
905         funding_satoshis,
906         push_msat,
907         dust_limit_satoshis,
908         max_htlc_value_in_flight_msat,
909         channel_reserve_satoshis,
910         htlc_minimum_msat,
911         feerate_per_kw,
912         to_self_delay,
913         max_accepted_htlcs,
914         funding_pubkey,
915         revocation_basepoint,
916         payment_point,
917         delayed_payment_basepoint,
918         htlc_basepoint,
919         first_per_commitment_point,
920         channel_flags,
921         shutdown_scriptpubkey
922 });
923
924 impl_writeable!(RevokeAndACK, 32+32+33, {
925         channel_id,
926         per_commitment_secret,
927         next_per_commitment_point
928 });
929
930 impl_writeable_len_match!(Shutdown, {
931                 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
932         }, {
933         channel_id,
934         scriptpubkey
935 });
936
937 impl_writeable_len_match!(UpdateFailHTLC, {
938                 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
939         }, {
940         channel_id,
941         htlc_id,
942         reason
943 });
944
945 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
946         channel_id,
947         htlc_id,
948         sha256_of_onion,
949         failure_code
950 });
951
952 impl_writeable!(UpdateFee, 32+4, {
953         channel_id,
954         feerate_per_kw
955 });
956
957 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
958         channel_id,
959         htlc_id,
960         payment_preimage
961 });
962
963 impl_writeable_len_match!(OnionErrorPacket, {
964                 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
965         }, {
966         data
967 });
968
969 impl Writeable for OnionPacket {
970         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
971                 w.size_hint(1 + 33 + 20*65 + 32);
972                 self.version.write(w)?;
973                 match self.public_key {
974                         Ok(pubkey) => pubkey.write(w)?,
975                         Err(_) => [0u8;33].write(w)?,
976                 }
977                 w.write_all(&self.hop_data)?;
978                 self.hmac.write(w)?;
979                 Ok(())
980         }
981 }
982
983 impl Readable for OnionPacket {
984         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
985                 Ok(OnionPacket {
986                         version: Readable::read(r)?,
987                         public_key: {
988                                 let mut buf = [0u8;33];
989                                 r.read_exact(&mut buf)?;
990                                 PublicKey::from_slice(&buf)
991                         },
992                         hop_data: Readable::read(r)?,
993                         hmac: Readable::read(r)?,
994                 })
995         }
996 }
997
998 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
999         channel_id,
1000         htlc_id,
1001         amount_msat,
1002         payment_hash,
1003         cltv_expiry,
1004         onion_routing_packet
1005 });
1006
1007 impl Writeable for FinalOnionHopData {
1008         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1009                 w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
1010                 self.payment_secret.0.write(w)?;
1011                 HighZeroBytesDroppedVarInt(self.total_msat).write(w)
1012         }
1013 }
1014
1015 impl Readable for FinalOnionHopData {
1016         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1017                 let secret: [u8; 32] = Readable::read(r)?;
1018                 let amt: HighZeroBytesDroppedVarInt<u64> = Readable::read(r)?;
1019                 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
1020         }
1021 }
1022
1023 impl Writeable for OnionHopData {
1024         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1025                 w.size_hint(33);
1026                 // Note that this should never be reachable if Rust-Lightning generated the message, as we
1027                 // check values are sane long before we get here, though its possible in the future
1028                 // user-generated messages may hit this.
1029                 if self.amt_to_forward > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1030                 match self.format {
1031                         OnionHopDataFormat::Legacy { short_channel_id } => {
1032                                 0u8.write(w)?;
1033                                 short_channel_id.write(w)?;
1034                                 self.amt_to_forward.write(w)?;
1035                                 self.outgoing_cltv_value.write(w)?;
1036                                 w.write_all(&[0;12])?;
1037                         },
1038                         OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1039                                 encode_varint_length_prefixed_tlv!(w, {
1040                                         (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1041                                         (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1042                                         (6, short_channel_id)
1043                                 });
1044                         },
1045                         OnionHopDataFormat::FinalNode { payment_data: Some(ref final_data) } => {
1046                                 if final_data.total_msat > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1047                                 encode_varint_length_prefixed_tlv!(w, {
1048                                         (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1049                                         (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1050                                         (8, final_data)
1051                                 });
1052                         },
1053                         OnionHopDataFormat::FinalNode { payment_data: None } => {
1054                                 encode_varint_length_prefixed_tlv!(w, {
1055                                         (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1056                                         (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
1057                                 });
1058                         },
1059                 }
1060                 Ok(())
1061         }
1062 }
1063
1064 impl Readable for OnionHopData {
1065         fn read<R: Read>(mut r: &mut R) -> Result<Self, DecodeError> {
1066                 use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1067                 let v: VarInt = Decodable::consensus_decode(&mut r)
1068                         .map_err(|e| match e {
1069                                 Error::Io(ioe) => DecodeError::from(ioe),
1070                                 _ => DecodeError::InvalidValue
1071                         })?;
1072                 const LEGACY_ONION_HOP_FLAG: u64 = 0;
1073                 let (format, amt, cltv_value) = if v.0 != LEGACY_ONION_HOP_FLAG {
1074                         let mut rd = FixedLengthReader::new(r, v.0);
1075                         let mut amt = HighZeroBytesDroppedVarInt(0u64);
1076                         let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
1077                         let mut short_id: Option<u64> = None;
1078                         let mut payment_data: Option<FinalOnionHopData> = None;
1079                         decode_tlv!(&mut rd, {
1080                                 (2, amt),
1081                                 (4, cltv_value)
1082                         }, {
1083                                 (6, short_id),
1084                                 (8, payment_data)
1085                         });
1086                         rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1087                         let format = if let Some(short_channel_id) = short_id {
1088                                 if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1089                                 OnionHopDataFormat::NonFinalNode {
1090                                         short_channel_id,
1091                                 }
1092                         } else {
1093                                 if let &Some(ref data) = &payment_data {
1094                                         if data.total_msat > MAX_VALUE_MSAT {
1095                                                 return Err(DecodeError::InvalidValue);
1096                                         }
1097                                 }
1098                                 OnionHopDataFormat::FinalNode {
1099                                         payment_data
1100                                 }
1101                         };
1102                         (format, amt.0, cltv_value.0)
1103                 } else {
1104                         let format = OnionHopDataFormat::Legacy {
1105                                 short_channel_id: Readable::read(r)?,
1106                         };
1107                         let amt: u64 = Readable::read(r)?;
1108                         let cltv_value: u32 = Readable::read(r)?;
1109                         r.read_exact(&mut [0; 12])?;
1110                         (format, amt, cltv_value)
1111                 };
1112
1113                 if amt > MAX_VALUE_MSAT {
1114                         return Err(DecodeError::InvalidValue);
1115                 }
1116                 Ok(OnionHopData {
1117                         format,
1118                         amt_to_forward: amt,
1119                         outgoing_cltv_value: cltv_value,
1120                 })
1121         }
1122 }
1123
1124 impl Writeable for Ping {
1125         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1126                 w.size_hint(self.byteslen as usize + 4);
1127                 self.ponglen.write(w)?;
1128                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1129                 Ok(())
1130         }
1131 }
1132
1133 impl Readable for Ping {
1134         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1135                 Ok(Ping {
1136                         ponglen: Readable::read(r)?,
1137                         byteslen: {
1138                                 let byteslen = Readable::read(r)?;
1139                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1140                                 byteslen
1141                         }
1142                 })
1143         }
1144 }
1145
1146 impl Writeable for Pong {
1147         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1148                 w.size_hint(self.byteslen as usize + 2);
1149                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1150                 Ok(())
1151         }
1152 }
1153
1154 impl Readable for Pong {
1155         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1156                 Ok(Pong {
1157                         byteslen: {
1158                                 let byteslen = Readable::read(r)?;
1159                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1160                                 byteslen
1161                         }
1162                 })
1163         }
1164 }
1165
1166 impl Writeable for UnsignedChannelAnnouncement {
1167         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1168                 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1169                 self.features.write(w)?;
1170                 self.chain_hash.write(w)?;
1171                 self.short_channel_id.write(w)?;
1172                 self.node_id_1.write(w)?;
1173                 self.node_id_2.write(w)?;
1174                 self.bitcoin_key_1.write(w)?;
1175                 self.bitcoin_key_2.write(w)?;
1176                 w.write_all(&self.excess_data[..])?;
1177                 Ok(())
1178         }
1179 }
1180
1181 impl Readable for UnsignedChannelAnnouncement {
1182         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1183                 Ok(Self {
1184                         features: Readable::read(r)?,
1185                         chain_hash: Readable::read(r)?,
1186                         short_channel_id: Readable::read(r)?,
1187                         node_id_1: Readable::read(r)?,
1188                         node_id_2: Readable::read(r)?,
1189                         bitcoin_key_1: Readable::read(r)?,
1190                         bitcoin_key_2: Readable::read(r)?,
1191                         excess_data: {
1192                                 let mut excess_data = vec![];
1193                                 r.read_to_end(&mut excess_data)?;
1194                                 excess_data
1195                         },
1196                 })
1197         }
1198 }
1199
1200 impl_writeable_len_match!(ChannelAnnouncement, {
1201                 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1202                         2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1203         }, {
1204         node_signature_1,
1205         node_signature_2,
1206         bitcoin_signature_1,
1207         bitcoin_signature_2,
1208         contents
1209 });
1210
1211 impl Writeable for UnsignedChannelUpdate {
1212         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1213                 let mut size = 64 + self.excess_data.len();
1214                 let mut message_flags: u8 = 0;
1215                 if let OptionalField::Present(_) = self.htlc_maximum_msat {
1216                         size += 8;
1217                         message_flags = 1;
1218                 }
1219                 w.size_hint(size);
1220                 self.chain_hash.write(w)?;
1221                 self.short_channel_id.write(w)?;
1222                 self.timestamp.write(w)?;
1223                 let all_flags = self.flags as u16 | ((message_flags as u16) << 8);
1224                 all_flags.write(w)?;
1225                 self.cltv_expiry_delta.write(w)?;
1226                 self.htlc_minimum_msat.write(w)?;
1227                 self.fee_base_msat.write(w)?;
1228                 self.fee_proportional_millionths.write(w)?;
1229                 self.htlc_maximum_msat.write(w)?;
1230                 w.write_all(&self.excess_data[..])?;
1231                 Ok(())
1232         }
1233 }
1234
1235 impl Readable for UnsignedChannelUpdate {
1236         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1237                 let has_htlc_maximum_msat;
1238                 Ok(Self {
1239                         chain_hash: Readable::read(r)?,
1240                         short_channel_id: Readable::read(r)?,
1241                         timestamp: Readable::read(r)?,
1242                         flags: {
1243                                 let flags: u16 = Readable::read(r)?;
1244                                 let message_flags = flags >> 8;
1245                                 has_htlc_maximum_msat = (message_flags as i32 & 1) == 1;
1246                                 flags as u8
1247                         },
1248                         cltv_expiry_delta: Readable::read(r)?,
1249                         htlc_minimum_msat: Readable::read(r)?,
1250                         fee_base_msat: Readable::read(r)?,
1251                         fee_proportional_millionths: Readable::read(r)?,
1252                         htlc_maximum_msat: if has_htlc_maximum_msat { Readable::read(r)? } else { OptionalField::Absent },
1253                         excess_data: {
1254                                 let mut excess_data = vec![];
1255                                 r.read_to_end(&mut excess_data)?;
1256                                 excess_data
1257                         },
1258                 })
1259         }
1260 }
1261
1262 impl_writeable_len_match!(ChannelUpdate, {
1263                 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1264                         64 + excess_data.len() + 64 }
1265         }, {
1266         signature,
1267         contents
1268 });
1269
1270 impl Writeable for ErrorMessage {
1271         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1272                 w.size_hint(32 + 2 + self.data.len());
1273                 self.channel_id.write(w)?;
1274                 (self.data.len() as u16).write(w)?;
1275                 w.write_all(self.data.as_bytes())?;
1276                 Ok(())
1277         }
1278 }
1279
1280 impl Readable for ErrorMessage {
1281         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1282                 Ok(Self {
1283                         channel_id: Readable::read(r)?,
1284                         data: {
1285                                 let mut sz: usize = <u16 as Readable>::read(r)? as usize;
1286                                 let mut data = vec![];
1287                                 let data_len = r.read_to_end(&mut data)?;
1288                                 sz = cmp::min(data_len, sz);
1289                                 match String::from_utf8(data[..sz as usize].to_vec()) {
1290                                         Ok(s) => s,
1291                                         Err(_) => return Err(DecodeError::InvalidValue),
1292                                 }
1293                         }
1294                 })
1295         }
1296 }
1297
1298 impl Writeable for UnsignedNodeAnnouncement {
1299         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1300                 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1301                 self.features.write(w)?;
1302                 self.timestamp.write(w)?;
1303                 self.node_id.write(w)?;
1304                 w.write_all(&self.rgb)?;
1305                 self.alias.write(w)?;
1306
1307                 let mut addrs_to_encode = self.addresses.clone();
1308                 addrs_to_encode.sort_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1309                 let mut addr_len = 0;
1310                 for addr in &addrs_to_encode {
1311                         addr_len += 1 + addr.len();
1312                 }
1313                 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1314                 for addr in addrs_to_encode {
1315                         addr.write(w)?;
1316                 }
1317                 w.write_all(&self.excess_address_data[..])?;
1318                 w.write_all(&self.excess_data[..])?;
1319                 Ok(())
1320         }
1321 }
1322
1323 impl Readable for UnsignedNodeAnnouncement {
1324         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1325                 let features: NodeFeatures = Readable::read(r)?;
1326                 let timestamp: u32 = Readable::read(r)?;
1327                 let node_id: PublicKey = Readable::read(r)?;
1328                 let mut rgb = [0; 3];
1329                 r.read_exact(&mut rgb)?;
1330                 let alias: [u8; 32] = Readable::read(r)?;
1331
1332                 let addr_len: u16 = Readable::read(r)?;
1333                 let mut addresses: Vec<NetAddress> = Vec::new();
1334                 let mut highest_addr_type = 0;
1335                 let mut addr_readpos = 0;
1336                 let mut excess = false;
1337                 let mut excess_byte = 0;
1338                 loop {
1339                         if addr_len <= addr_readpos { break; }
1340                         match Readable::read(r) {
1341                                 Ok(Ok(addr)) => {
1342                                         if addr.get_id() < highest_addr_type {
1343                                                 // Addresses must be sorted in increasing order
1344                                                 return Err(DecodeError::InvalidValue);
1345                                         }
1346                                         highest_addr_type = addr.get_id();
1347                                         if addr_len < addr_readpos + 1 + addr.len() {
1348                                                 return Err(DecodeError::BadLengthDescriptor);
1349                                         }
1350                                         addr_readpos += (1 + addr.len()) as u16;
1351                                         addresses.push(addr);
1352                                 },
1353                                 Ok(Err(unknown_descriptor)) => {
1354                                         excess = true;
1355                                         excess_byte = unknown_descriptor;
1356                                         break;
1357                                 },
1358                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1359                                 Err(e) => return Err(e),
1360                         }
1361                 }
1362
1363                 let mut excess_data = vec![];
1364                 let excess_address_data = if addr_readpos < addr_len {
1365                         let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1366                         r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1367                         if excess {
1368                                 excess_address_data[0] = excess_byte;
1369                         }
1370                         excess_address_data
1371                 } else {
1372                         if excess {
1373                                 excess_data.push(excess_byte);
1374                         }
1375                         Vec::new()
1376                 };
1377                 r.read_to_end(&mut excess_data)?;
1378                 Ok(UnsignedNodeAnnouncement {
1379                         features,
1380                         timestamp,
1381                         node_id,
1382                         rgb,
1383                         alias,
1384                         addresses,
1385                         excess_address_data,
1386                         excess_data,
1387                 })
1388         }
1389 }
1390
1391 impl_writeable_len_match!(NodeAnnouncement, {
1392                 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1393                         64 + 76 + features.byte_count() + addresses.len()*(NetAddress::MAX_LEN as usize + 1) + excess_address_data.len() + excess_data.len() }
1394         }, {
1395         signature,
1396         contents
1397 });
1398
1399 #[cfg(test)]
1400 mod tests {
1401         use hex;
1402         use ln::msgs;
1403         use ln::msgs::{ChannelFeatures, FinalOnionHopData, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1404         use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
1405         use util::ser::{Writeable, Readable};
1406
1407         use bitcoin::hashes::hex::FromHex;
1408         use bitcoin::util::address::Address;
1409         use bitcoin::network::constants::Network;
1410         use bitcoin::blockdata::script::Builder;
1411         use bitcoin::blockdata::opcodes;
1412         use bitcoin::hash_types::{Txid, BlockHash};
1413
1414         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1415         use bitcoin::secp256k1::{Secp256k1, Message};
1416
1417         use std::io::Cursor;
1418
1419         #[test]
1420         fn encoding_channel_reestablish_no_secret() {
1421                 let cr = msgs::ChannelReestablish {
1422                         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],
1423                         next_local_commitment_number: 3,
1424                         next_remote_commitment_number: 4,
1425                         data_loss_protect: OptionalField::Absent,
1426                 };
1427
1428                 let encoded_value = cr.encode();
1429                 assert_eq!(
1430                         encoded_value,
1431                         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]
1432                 );
1433         }
1434
1435         #[test]
1436         fn encoding_channel_reestablish_with_secret() {
1437                 let public_key = {
1438                         let secp_ctx = Secp256k1::new();
1439                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1440                 };
1441
1442                 let cr = msgs::ChannelReestablish {
1443                         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],
1444                         next_local_commitment_number: 3,
1445                         next_remote_commitment_number: 4,
1446                         data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1447                 };
1448
1449                 let encoded_value = cr.encode();
1450                 assert_eq!(
1451                         encoded_value,
1452                         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]
1453                 );
1454         }
1455
1456         macro_rules! get_keys_from {
1457                 ($slice: expr, $secp_ctx: expr) => {
1458                         {
1459                                 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1460                                 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1461                                 (privkey, pubkey)
1462                         }
1463                 }
1464         }
1465
1466         macro_rules! get_sig_on {
1467                 ($privkey: expr, $ctx: expr, $string: expr) => {
1468                         {
1469                                 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1470                                 $ctx.sign(&sighash, &$privkey)
1471                         }
1472                 }
1473         }
1474
1475         #[test]
1476         fn encoding_announcement_signatures() {
1477                 let secp_ctx = Secp256k1::new();
1478                 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1479                 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1480                 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1481                 let announcement_signatures = msgs::AnnouncementSignatures {
1482                         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],
1483                         short_channel_id: 2316138423780173,
1484                         node_signature: sig_1,
1485                         bitcoin_signature: sig_2,
1486                 };
1487
1488                 let encoded_value = announcement_signatures.encode();
1489                 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1490         }
1491
1492         fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
1493                 let secp_ctx = Secp256k1::new();
1494                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1495                 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1496                 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1497                 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1498                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1499                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1500                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1501                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1502                 let mut features = ChannelFeatures::known();
1503                 if unknown_features_bits {
1504                         features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1505                 }
1506                 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1507                         features,
1508                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1509                         short_channel_id: 2316138423780173,
1510                         node_id_1: pubkey_1,
1511                         node_id_2: pubkey_2,
1512                         bitcoin_key_1: pubkey_3,
1513                         bitcoin_key_2: pubkey_4,
1514                         excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1515                 };
1516                 let channel_announcement = msgs::ChannelAnnouncement {
1517                         node_signature_1: sig_1,
1518                         node_signature_2: sig_2,
1519                         bitcoin_signature_1: sig_3,
1520                         bitcoin_signature_2: sig_4,
1521                         contents: unsigned_channel_announcement,
1522                 };
1523                 let encoded_value = channel_announcement.encode();
1524                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1525                 if unknown_features_bits {
1526                         target_value.append(&mut hex::decode("0002ffff").unwrap());
1527                 } else {
1528                         target_value.append(&mut hex::decode("0000").unwrap());
1529                 }
1530                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1531                 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1532                 if excess_data {
1533                         target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1534                 }
1535                 assert_eq!(encoded_value, target_value);
1536         }
1537
1538         #[test]
1539         fn encoding_channel_announcement() {
1540                 do_encoding_channel_announcement(true, false);
1541                 do_encoding_channel_announcement(false, true);
1542                 do_encoding_channel_announcement(false, false);
1543                 do_encoding_channel_announcement(true, true);
1544         }
1545
1546         fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1547                 let secp_ctx = Secp256k1::new();
1548                 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1549                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1550                 let features = if unknown_features_bits {
1551                         NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1552                 } else {
1553                         // Set to some features we may support
1554                         NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1555                 };
1556                 let mut addresses = Vec::new();
1557                 if ipv4 {
1558                         addresses.push(msgs::NetAddress::IPv4 {
1559                                 addr: [255, 254, 253, 252],
1560                                 port: 9735
1561                         });
1562                 }
1563                 if ipv6 {
1564                         addresses.push(msgs::NetAddress::IPv6 {
1565                                 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1566                                 port: 9735
1567                         });
1568                 }
1569                 if onionv2 {
1570                         addresses.push(msgs::NetAddress::OnionV2 {
1571                                 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1572                                 port: 9735
1573                         });
1574                 }
1575                 if onionv3 {
1576                         addresses.push(msgs::NetAddress::OnionV3 {
1577                                 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],
1578                                 checksum: 32,
1579                                 version: 16,
1580                                 port: 9735
1581                         });
1582                 }
1583                 let mut addr_len = 0;
1584                 for addr in &addresses {
1585                         addr_len += addr.len() + 1;
1586                 }
1587                 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1588                         features,
1589                         timestamp: 20190119,
1590                         node_id: pubkey_1,
1591                         rgb: [32; 3],
1592                         alias: [16;32],
1593                         addresses,
1594                         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() },
1595                         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() },
1596                 };
1597                 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1598                 let node_announcement = msgs::NodeAnnouncement {
1599                         signature: sig_1,
1600                         contents: unsigned_node_announcement,
1601                 };
1602                 let encoded_value = node_announcement.encode();
1603                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1604                 if unknown_features_bits {
1605                         target_value.append(&mut hex::decode("0002ffff").unwrap());
1606                 } else {
1607                         target_value.append(&mut hex::decode("000122").unwrap());
1608                 }
1609                 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1610                 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1611                 if ipv4 {
1612                         target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1613                 }
1614                 if ipv6 {
1615                         target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1616                 }
1617                 if onionv2 {
1618                         target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1619                 }
1620                 if onionv3 {
1621                         target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1622                 }
1623                 if excess_address_data {
1624                         target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1625                 }
1626                 if excess_data {
1627                         target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1628                 }
1629                 assert_eq!(encoded_value, target_value);
1630         }
1631
1632         #[test]
1633         fn encoding_node_announcement() {
1634                 do_encoding_node_announcement(true, true, true, true, true, true, true);
1635                 do_encoding_node_announcement(false, false, false, false, false, false, false);
1636                 do_encoding_node_announcement(false, true, false, false, false, false, false);
1637                 do_encoding_node_announcement(false, false, true, false, false, false, false);
1638                 do_encoding_node_announcement(false, false, false, true, false, false, false);
1639                 do_encoding_node_announcement(false, false, false, false, true, false, false);
1640                 do_encoding_node_announcement(false, false, false, false, false, true, false);
1641                 do_encoding_node_announcement(false, true, false, true, false, true, false);
1642                 do_encoding_node_announcement(false, false, true, false, true, false, false);
1643         }
1644
1645         fn do_encoding_channel_update(direction: bool, disable: bool, htlc_maximum_msat: bool, excess_data: bool) {
1646                 let secp_ctx = Secp256k1::new();
1647                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1648                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1649                 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1650                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1651                         short_channel_id: 2316138423780173,
1652                         timestamp: 20190119,
1653                         flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
1654                         cltv_expiry_delta: 144,
1655                         htlc_minimum_msat: 1000000,
1656                         htlc_maximum_msat: if htlc_maximum_msat { OptionalField::Present(131355275467161) } else { OptionalField::Absent },
1657                         fee_base_msat: 10000,
1658                         fee_proportional_millionths: 20,
1659                         excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1660                 };
1661                 let channel_update = msgs::ChannelUpdate {
1662                         signature: sig_1,
1663                         contents: unsigned_channel_update
1664                 };
1665                 let encoded_value = channel_update.encode();
1666                 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1667                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1668                 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1669                 if htlc_maximum_msat {
1670                         target_value.append(&mut hex::decode("01").unwrap());
1671                 } else {
1672                         target_value.append(&mut hex::decode("00").unwrap());
1673                 }
1674                 target_value.append(&mut hex::decode("00").unwrap());
1675                 if direction {
1676                         let flag = target_value.last_mut().unwrap();
1677                         *flag = 1;
1678                 }
1679                 if disable {
1680                         let flag = target_value.last_mut().unwrap();
1681                         *flag = *flag | 1 << 1;
1682                 }
1683                 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1684                 if htlc_maximum_msat {
1685                         target_value.append(&mut hex::decode("0000777788889999").unwrap());
1686                 }
1687                 if excess_data {
1688                         target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1689                 }
1690                 assert_eq!(encoded_value, target_value);
1691         }
1692
1693         #[test]
1694         fn encoding_channel_update() {
1695                 do_encoding_channel_update(false, false, false, false);
1696                 do_encoding_channel_update(false, false, false, true);
1697                 do_encoding_channel_update(true, false, false, false);
1698                 do_encoding_channel_update(true, false, false, true);
1699                 do_encoding_channel_update(false, true, false, false);
1700                 do_encoding_channel_update(false, true, false, true);
1701                 do_encoding_channel_update(false, false, true, false);
1702                 do_encoding_channel_update(false, false, true, true);
1703                 do_encoding_channel_update(true, true, true, false);
1704                 do_encoding_channel_update(true, true, true, true);
1705         }
1706
1707         fn do_encoding_open_channel(random_bit: bool, shutdown: bool) {
1708                 let secp_ctx = Secp256k1::new();
1709                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1710                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1711                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1712                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1713                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1714                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1715                 let open_channel = msgs::OpenChannel {
1716                         chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1717                         temporary_channel_id: [2; 32],
1718                         funding_satoshis: 1311768467284833366,
1719                         push_msat: 2536655962884945560,
1720                         dust_limit_satoshis: 3608586615801332854,
1721                         max_htlc_value_in_flight_msat: 8517154655701053848,
1722                         channel_reserve_satoshis: 8665828695742877976,
1723                         htlc_minimum_msat: 2316138423780173,
1724                         feerate_per_kw: 821716,
1725                         to_self_delay: 49340,
1726                         max_accepted_htlcs: 49340,
1727                         funding_pubkey: pubkey_1,
1728                         revocation_basepoint: pubkey_2,
1729                         payment_point: pubkey_3,
1730                         delayed_payment_basepoint: pubkey_4,
1731                         htlc_basepoint: pubkey_5,
1732                         first_per_commitment_point: pubkey_6,
1733                         channel_flags: if random_bit { 1 << 5 } else { 0 },
1734                         shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1735                 };
1736                 let encoded_value = open_channel.encode();
1737                 let mut target_value = Vec::new();
1738                 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1739                 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1740                 if random_bit {
1741                         target_value.append(&mut hex::decode("20").unwrap());
1742                 } else {
1743                         target_value.append(&mut hex::decode("00").unwrap());
1744                 }
1745                 if shutdown {
1746                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1747                 }
1748                 assert_eq!(encoded_value, target_value);
1749         }
1750
1751         #[test]
1752         fn encoding_open_channel() {
1753                 do_encoding_open_channel(false, false);
1754                 do_encoding_open_channel(true, false);
1755                 do_encoding_open_channel(false, true);
1756                 do_encoding_open_channel(true, true);
1757         }
1758
1759         fn do_encoding_accept_channel(shutdown: bool) {
1760                 let secp_ctx = Secp256k1::new();
1761                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1762                 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1763                 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1764                 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1765                 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1766                 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1767                 let accept_channel = msgs::AcceptChannel {
1768                         temporary_channel_id: [2; 32],
1769                         dust_limit_satoshis: 1311768467284833366,
1770                         max_htlc_value_in_flight_msat: 2536655962884945560,
1771                         channel_reserve_satoshis: 3608586615801332854,
1772                         htlc_minimum_msat: 2316138423780173,
1773                         minimum_depth: 821716,
1774                         to_self_delay: 49340,
1775                         max_accepted_htlcs: 49340,
1776                         funding_pubkey: pubkey_1,
1777                         revocation_basepoint: pubkey_2,
1778                         payment_point: pubkey_3,
1779                         delayed_payment_basepoint: pubkey_4,
1780                         htlc_basepoint: pubkey_5,
1781                         first_per_commitment_point: pubkey_6,
1782                         shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1783                 };
1784                 let encoded_value = accept_channel.encode();
1785                 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1786                 if shutdown {
1787                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1788                 }
1789                 assert_eq!(encoded_value, target_value);
1790         }
1791
1792         #[test]
1793         fn encoding_accept_channel() {
1794                 do_encoding_accept_channel(false);
1795                 do_encoding_accept_channel(true);
1796         }
1797
1798         #[test]
1799         fn encoding_funding_created() {
1800                 let secp_ctx = Secp256k1::new();
1801                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1802                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1803                 let funding_created = msgs::FundingCreated {
1804                         temporary_channel_id: [2; 32],
1805                         funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1806                         funding_output_index: 255,
1807                         signature: sig_1,
1808                 };
1809                 let encoded_value = funding_created.encode();
1810                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1811                 assert_eq!(encoded_value, target_value);
1812         }
1813
1814         #[test]
1815         fn encoding_funding_signed() {
1816                 let secp_ctx = Secp256k1::new();
1817                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1818                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1819                 let funding_signed = msgs::FundingSigned {
1820                         channel_id: [2; 32],
1821                         signature: sig_1,
1822                 };
1823                 let encoded_value = funding_signed.encode();
1824                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1825                 assert_eq!(encoded_value, target_value);
1826         }
1827
1828         #[test]
1829         fn encoding_funding_locked() {
1830                 let secp_ctx = Secp256k1::new();
1831                 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1832                 let funding_locked = msgs::FundingLocked {
1833                         channel_id: [2; 32],
1834                         next_per_commitment_point: pubkey_1,
1835                 };
1836                 let encoded_value = funding_locked.encode();
1837                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1838                 assert_eq!(encoded_value, target_value);
1839         }
1840
1841         fn do_encoding_shutdown(script_type: u8) {
1842                 let secp_ctx = Secp256k1::new();
1843                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1844                 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1845                 let shutdown = msgs::Shutdown {
1846                         channel_id: [2; 32],
1847                         scriptpubkey: if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() } else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
1848                 };
1849                 let encoded_value = shutdown.encode();
1850                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1851                 if script_type == 1 {
1852                         target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1853                 } else if script_type == 2 {
1854                         target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1855                 } else if script_type == 3 {
1856                         target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1857                 } else if script_type == 4 {
1858                         target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1859                 }
1860                 assert_eq!(encoded_value, target_value);
1861         }
1862
1863         #[test]
1864         fn encoding_shutdown() {
1865                 do_encoding_shutdown(1);
1866                 do_encoding_shutdown(2);
1867                 do_encoding_shutdown(3);
1868                 do_encoding_shutdown(4);
1869         }
1870
1871         #[test]
1872         fn encoding_closing_signed() {
1873                 let secp_ctx = Secp256k1::new();
1874                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1875                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1876                 let closing_signed = msgs::ClosingSigned {
1877                         channel_id: [2; 32],
1878                         fee_satoshis: 2316138423780173,
1879                         signature: sig_1,
1880                 };
1881                 let encoded_value = closing_signed.encode();
1882                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1883                 assert_eq!(encoded_value, target_value);
1884         }
1885
1886         #[test]
1887         fn encoding_update_add_htlc() {
1888                 let secp_ctx = Secp256k1::new();
1889                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1890                 let onion_routing_packet = msgs::OnionPacket {
1891                         version: 255,
1892                         public_key: Ok(pubkey_1),
1893                         hop_data: [1; 20*65],
1894                         hmac: [2; 32]
1895                 };
1896                 let update_add_htlc = msgs::UpdateAddHTLC {
1897                         channel_id: [2; 32],
1898                         htlc_id: 2316138423780173,
1899                         amount_msat: 3608586615801332854,
1900                         payment_hash: PaymentHash([1; 32]),
1901                         cltv_expiry: 821716,
1902                         onion_routing_packet
1903                 };
1904                 let encoded_value = update_add_htlc.encode();
1905                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
1906                 assert_eq!(encoded_value, target_value);
1907         }
1908
1909         #[test]
1910         fn encoding_update_fulfill_htlc() {
1911                 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
1912                         channel_id: [2; 32],
1913                         htlc_id: 2316138423780173,
1914                         payment_preimage: PaymentPreimage([1; 32]),
1915                 };
1916                 let encoded_value = update_fulfill_htlc.encode();
1917                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
1918                 assert_eq!(encoded_value, target_value);
1919         }
1920
1921         #[test]
1922         fn encoding_update_fail_htlc() {
1923                 let reason = OnionErrorPacket {
1924                         data: [1; 32].to_vec(),
1925                 };
1926                 let update_fail_htlc = msgs::UpdateFailHTLC {
1927                         channel_id: [2; 32],
1928                         htlc_id: 2316138423780173,
1929                         reason
1930                 };
1931                 let encoded_value = update_fail_htlc.encode();
1932                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
1933                 assert_eq!(encoded_value, target_value);
1934         }
1935
1936         #[test]
1937         fn encoding_update_fail_malformed_htlc() {
1938                 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
1939                         channel_id: [2; 32],
1940                         htlc_id: 2316138423780173,
1941                         sha256_of_onion: [1; 32],
1942                         failure_code: 255
1943                 };
1944                 let encoded_value = update_fail_malformed_htlc.encode();
1945                 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
1946                 assert_eq!(encoded_value, target_value);
1947         }
1948
1949         fn do_encoding_commitment_signed(htlcs: bool) {
1950                 let secp_ctx = Secp256k1::new();
1951                 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1952                 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1953                 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1954                 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1955                 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1956                 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1957                 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1958                 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1959                 let commitment_signed = msgs::CommitmentSigned {
1960                         channel_id: [2; 32],
1961                         signature: sig_1,
1962                         htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
1963                 };
1964                 let encoded_value = commitment_signed.encode();
1965                 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1966                 if htlcs {
1967                         target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1968                 } else {
1969                         target_value.append(&mut hex::decode("0000").unwrap());
1970                 }
1971                 assert_eq!(encoded_value, target_value);
1972         }
1973
1974         #[test]
1975         fn encoding_commitment_signed() {
1976                 do_encoding_commitment_signed(true);
1977                 do_encoding_commitment_signed(false);
1978         }
1979
1980         #[test]
1981         fn encoding_revoke_and_ack() {
1982                 let secp_ctx = Secp256k1::new();
1983                 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1984                 let raa = msgs::RevokeAndACK {
1985                         channel_id: [2; 32],
1986                         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],
1987                         next_per_commitment_point: pubkey_1,
1988                 };
1989                 let encoded_value = raa.encode();
1990                 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1991                 assert_eq!(encoded_value, target_value);
1992         }
1993
1994         #[test]
1995         fn encoding_update_fee() {
1996                 let update_fee = msgs::UpdateFee {
1997                         channel_id: [2; 32],
1998                         feerate_per_kw: 20190119,
1999                 };
2000                 let encoded_value = update_fee.encode();
2001                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2002                 assert_eq!(encoded_value, target_value);
2003         }
2004
2005         #[test]
2006         fn encoding_init() {
2007                 assert_eq!(msgs::Init {
2008                         features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2009                 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2010                 assert_eq!(msgs::Init {
2011                         features: InitFeatures::from_le_bytes(vec![0xFF]),
2012                 }.encode(), hex::decode("0001ff0001ff").unwrap());
2013                 assert_eq!(msgs::Init {
2014                         features: InitFeatures::from_le_bytes(vec![]),
2015                 }.encode(), hex::decode("00000000").unwrap());
2016         }
2017
2018         #[test]
2019         fn encoding_error() {
2020                 let error = msgs::ErrorMessage {
2021                         channel_id: [2; 32],
2022                         data: String::from("rust-lightning"),
2023                 };
2024                 let encoded_value = error.encode();
2025                 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2026                 assert_eq!(encoded_value, target_value);
2027         }
2028
2029         #[test]
2030         fn encoding_ping() {
2031                 let ping = msgs::Ping {
2032                         ponglen: 64,
2033                         byteslen: 64
2034                 };
2035                 let encoded_value = ping.encode();
2036                 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2037                 assert_eq!(encoded_value, target_value);
2038         }
2039
2040         #[test]
2041         fn encoding_pong() {
2042                 let pong = msgs::Pong {
2043                         byteslen: 64
2044                 };
2045                 let encoded_value = pong.encode();
2046                 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2047                 assert_eq!(encoded_value, target_value);
2048         }
2049
2050         #[test]
2051         fn encoding_legacy_onion_hop_data() {
2052                 let msg = msgs::OnionHopData {
2053                         format: OnionHopDataFormat::Legacy {
2054                                 short_channel_id: 0xdeadbeef1bad1dea,
2055                         },
2056                         amt_to_forward: 0x0badf00d01020304,
2057                         outgoing_cltv_value: 0xffffffff,
2058                 };
2059                 let encoded_value = msg.encode();
2060                 let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
2061                 assert_eq!(encoded_value, target_value);
2062         }
2063
2064         #[test]
2065         fn encoding_nonfinal_onion_hop_data() {
2066                 let mut msg = msgs::OnionHopData {
2067                         format: OnionHopDataFormat::NonFinalNode {
2068                                 short_channel_id: 0xdeadbeef1bad1dea,
2069                         },
2070                         amt_to_forward: 0x0badf00d01020304,
2071                         outgoing_cltv_value: 0xffffffff,
2072                 };
2073                 let encoded_value = msg.encode();
2074                 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2075                 assert_eq!(encoded_value, target_value);
2076                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2077                 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2078                         assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2079                 } else { panic!(); }
2080                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2081                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2082         }
2083
2084         #[test]
2085         fn encoding_final_onion_hop_data() {
2086                 let mut msg = msgs::OnionHopData {
2087                         format: OnionHopDataFormat::FinalNode {
2088                                 payment_data: None,
2089                         },
2090                         amt_to_forward: 0x0badf00d01020304,
2091                         outgoing_cltv_value: 0xffffffff,
2092                 };
2093                 let encoded_value = msg.encode();
2094                 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2095                 assert_eq!(encoded_value, target_value);
2096                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2097                 if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
2098                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2099                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2100         }
2101
2102         #[test]
2103         fn encoding_final_onion_hop_data_with_secret() {
2104                 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
2105                 let mut msg = msgs::OnionHopData {
2106                         format: OnionHopDataFormat::FinalNode {
2107                                 payment_data: Some(FinalOnionHopData {
2108                                         payment_secret: expected_payment_secret,
2109                                         total_msat: 0x1badca1f
2110                                 }),
2111                         },
2112                         amt_to_forward: 0x0badf00d01020304,
2113                         outgoing_cltv_value: 0xffffffff,
2114                 };
2115                 let encoded_value = msg.encode();
2116                 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2117                 assert_eq!(encoded_value, target_value);
2118                 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2119                 if let OnionHopDataFormat::FinalNode {
2120                         payment_data: Some(FinalOnionHopData {
2121                                 payment_secret,
2122                                 total_msat: 0x1badca1f
2123                         })
2124                 } = msg.format {
2125                         assert_eq!(payment_secret, expected_payment_secret);
2126                 } else { panic!(); }
2127                 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2128                 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2129         }
2130 }