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