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