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