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