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