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