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