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