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