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