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