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