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