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