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