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