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