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