Send shutdown/closing_signed msgs out-of-band for ordered delivery
[rust-lightning] / src / ln / msgs.rs
1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
2 //!
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
7 //! daemons/servers.
8 //!
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the mssage, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
17
18 use secp256k1::key::PublicKey;
19 use secp256k1::{Secp256k1, Signature};
20 use secp256k1;
21 use bitcoin::util::hash::Sha256dHash;
22 use bitcoin::blockdata::script::Script;
23
24 use std::error::Error;
25 use std::{cmp, fmt};
26 use std::io::Read;
27 use std::result::Result;
28
29 use util::{byte_utils, events};
30 use util::ser::{Readable, Writeable, Writer};
31
32 /// An error in decoding a message or struct.
33 #[derive(Debug)]
34 pub enum DecodeError {
35         /// A version byte specified something we don't know how to handle.
36         /// Includes unknown realm byte in an OnionHopData packet
37         UnknownVersion,
38         /// Unknown feature mandating we fail to parse message
39         UnknownRequiredFeature,
40         /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
41         /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
42         InvalidValue,
43         /// Buffer too short
44         ShortRead,
45         /// node_announcement included more than one address of a given type!
46         ExtraAddressesPerType,
47         /// A length descriptor in the packet didn't describe the later data correctly
48         /// (currently only generated in node_announcement)
49         BadLengthDescriptor,
50         /// Error from std::io
51         Io(::std::io::Error),
52 }
53
54 /// Tracks localfeatures which are only in init messages
55 #[derive(Clone, PartialEq)]
56 pub struct LocalFeatures {
57         flags: Vec<u8>,
58 }
59
60 impl LocalFeatures {
61         pub(crate) fn new() -> LocalFeatures {
62                 LocalFeatures {
63                         flags: Vec::new(),
64                 }
65         }
66
67         pub(crate) fn supports_data_loss_protect(&self) -> bool {
68                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
69         }
70         pub(crate) fn requires_data_loss_protect(&self) -> bool {
71                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
72         }
73
74         pub(crate) fn initial_routing_sync(&self) -> bool {
75                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
76         }
77         pub(crate) fn set_initial_routing_sync(&mut self) {
78                 if self.flags.len() == 0 {
79                         self.flags.resize(1, 1 << 3);
80                 } else {
81                         self.flags[0] |= 1 << 3;
82                 }
83         }
84
85         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
86                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
87         }
88         pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
89                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
90         }
91
92         pub(crate) fn requires_unknown_bits(&self) -> bool {
93                 for (idx, &byte) in self.flags.iter().enumerate() {
94                         if idx != 0 && (byte & 0x55) != 0 {
95                                 return true;
96                         } else if idx == 0 && (byte & 0x14) != 0 {
97                                 return true;
98                         }
99                 }
100                 return false;
101         }
102
103         pub(crate) fn supports_unknown_bits(&self) -> bool {
104                 for (idx, &byte) in self.flags.iter().enumerate() {
105                         if idx != 0 && byte != 0 {
106                                 return true;
107                         } else if idx == 0 && (byte & 0xc4) != 0 {
108                                 return true;
109                         }
110                 }
111                 return false;
112         }
113 }
114
115 /// Tracks globalfeatures which are in init messages and routing announcements
116 #[derive(Clone, PartialEq)]
117 pub struct GlobalFeatures {
118         flags: Vec<u8>,
119 }
120
121 impl GlobalFeatures {
122         pub(crate) fn new() -> GlobalFeatures {
123                 GlobalFeatures {
124                         flags: Vec::new(),
125                 }
126         }
127
128         pub(crate) fn requires_unknown_bits(&self) -> bool {
129                 for &byte in self.flags.iter() {
130                         if (byte & 0x55) != 0 {
131                                 return true;
132                         }
133                 }
134                 return false;
135         }
136
137         pub(crate) fn supports_unknown_bits(&self) -> bool {
138                 for &byte in self.flags.iter() {
139                         if byte != 0 {
140                                 return true;
141                         }
142                 }
143                 return false;
144         }
145 }
146
147 /// An init message to be sent or received from a peer
148 pub struct Init {
149         pub(crate) global_features: GlobalFeatures,
150         pub(crate) local_features: LocalFeatures,
151 }
152
153 /// An error message to be sent or received from a peer
154 pub struct ErrorMessage {
155         pub(crate) channel_id: [u8; 32],
156         pub(crate) data: String,
157 }
158
159 /// A ping message to be sent or received from a peer
160 pub struct Ping {
161         pub(crate) ponglen: u16,
162         pub(crate) byteslen: u16,
163 }
164
165 /// A pong message to be sent or received from a peer
166 pub struct Pong {
167         pub(crate) byteslen: u16,
168 }
169
170 /// An open_channel message to be sent or received from a peer
171 #[derive(Clone)]
172 pub struct OpenChannel {
173         pub(crate) chain_hash: Sha256dHash,
174         pub(crate) temporary_channel_id: [u8; 32],
175         pub(crate) funding_satoshis: u64,
176         pub(crate) push_msat: u64,
177         pub(crate) dust_limit_satoshis: u64,
178         pub(crate) max_htlc_value_in_flight_msat: u64,
179         pub(crate) channel_reserve_satoshis: u64,
180         pub(crate) htlc_minimum_msat: u64,
181         pub(crate) feerate_per_kw: u32,
182         pub(crate) to_self_delay: u16,
183         pub(crate) max_accepted_htlcs: u16,
184         pub(crate) funding_pubkey: PublicKey,
185         pub(crate) revocation_basepoint: PublicKey,
186         pub(crate) payment_basepoint: PublicKey,
187         pub(crate) delayed_payment_basepoint: PublicKey,
188         pub(crate) htlc_basepoint: PublicKey,
189         pub(crate) first_per_commitment_point: PublicKey,
190         pub(crate) channel_flags: u8,
191         pub(crate) shutdown_scriptpubkey: Option<Script>,
192 }
193
194 /// An accept_channel message to be sent or received from a peer
195 #[derive(Clone)]
196 pub struct AcceptChannel {
197         pub(crate) temporary_channel_id: [u8; 32],
198         pub(crate) dust_limit_satoshis: u64,
199         pub(crate) max_htlc_value_in_flight_msat: u64,
200         pub(crate) channel_reserve_satoshis: u64,
201         pub(crate) htlc_minimum_msat: u64,
202         pub(crate) minimum_depth: u32,
203         pub(crate) to_self_delay: u16,
204         pub(crate) max_accepted_htlcs: u16,
205         pub(crate) funding_pubkey: PublicKey,
206         pub(crate) revocation_basepoint: PublicKey,
207         pub(crate) payment_basepoint: PublicKey,
208         pub(crate) delayed_payment_basepoint: PublicKey,
209         pub(crate) htlc_basepoint: PublicKey,
210         pub(crate) first_per_commitment_point: PublicKey,
211         pub(crate) shutdown_scriptpubkey: Option<Script>,
212 }
213
214 /// A funding_created message to be sent or received from a peer
215 #[derive(Clone)]
216 pub struct FundingCreated {
217         pub(crate) temporary_channel_id: [u8; 32],
218         pub(crate) funding_txid: Sha256dHash,
219         pub(crate) funding_output_index: u16,
220         pub(crate) signature: Signature,
221 }
222
223 /// A funding_signed message to be sent or received from a peer
224 #[derive(Clone)]
225 pub struct FundingSigned {
226         pub(crate) channel_id: [u8; 32],
227         pub(crate) signature: Signature,
228 }
229
230 /// A funding_locked message to be sent or received from a peer
231 #[derive(Clone, PartialEq)]
232 pub struct FundingLocked {
233         pub(crate) channel_id: [u8; 32],
234         pub(crate) next_per_commitment_point: PublicKey,
235 }
236
237 /// A shutdown message to be sent or received from a peer
238 #[derive(Clone)]
239 pub struct Shutdown {
240         pub(crate) channel_id: [u8; 32],
241         pub(crate) scriptpubkey: Script,
242 }
243
244 /// A closing_signed message to be sent or received from a peer
245 #[derive(Clone)]
246 pub struct ClosingSigned {
247         pub(crate) channel_id: [u8; 32],
248         pub(crate) fee_satoshis: u64,
249         pub(crate) signature: Signature,
250 }
251
252 /// An update_add_htlc message to be sent or received from a peer
253 #[derive(Clone, PartialEq)]
254 pub struct UpdateAddHTLC {
255         pub(crate) channel_id: [u8; 32],
256         pub(crate) htlc_id: u64,
257         pub(crate) amount_msat: u64,
258         pub(crate) payment_hash: [u8; 32],
259         pub(crate) cltv_expiry: u32,
260         pub(crate) onion_routing_packet: OnionPacket,
261 }
262
263 /// An update_fulfill_htlc message to be sent or received from a peer
264 #[derive(Clone, PartialEq)]
265 pub struct UpdateFulfillHTLC {
266         pub(crate) channel_id: [u8; 32],
267         pub(crate) htlc_id: u64,
268         pub(crate) payment_preimage: [u8; 32],
269 }
270
271 /// An update_fail_htlc message to be sent or received from a peer
272 #[derive(Clone, PartialEq)]
273 pub struct UpdateFailHTLC {
274         pub(crate) channel_id: [u8; 32],
275         pub(crate) htlc_id: u64,
276         pub(crate) reason: OnionErrorPacket,
277 }
278
279 /// An update_fail_malformed_htlc message to be sent or received from a peer
280 #[derive(Clone, PartialEq)]
281 pub struct UpdateFailMalformedHTLC {
282         pub(crate) channel_id: [u8; 32],
283         pub(crate) htlc_id: u64,
284         pub(crate) sha256_of_onion: [u8; 32],
285         pub(crate) failure_code: u16,
286 }
287
288 /// A commitment_signed message to be sent or received from a peer
289 #[derive(Clone, PartialEq)]
290 pub struct CommitmentSigned {
291         pub(crate) channel_id: [u8; 32],
292         pub(crate) signature: Signature,
293         pub(crate) htlc_signatures: Vec<Signature>,
294 }
295
296 /// A revoke_and_ack message to be sent or received from a peer
297 #[derive(Clone, PartialEq)]
298 pub struct RevokeAndACK {
299         pub(crate) channel_id: [u8; 32],
300         pub(crate) per_commitment_secret: [u8; 32],
301         pub(crate) next_per_commitment_point: PublicKey,
302 }
303
304 /// An update_fee message to be sent or received from a peer
305 #[derive(PartialEq)]
306 pub struct UpdateFee {
307         pub(crate) channel_id: [u8; 32],
308         pub(crate) feerate_per_kw: u32,
309 }
310
311 #[derive(PartialEq)]
312 pub(crate) struct DataLossProtect {
313         pub(crate) your_last_per_commitment_secret: [u8; 32],
314         pub(crate) my_current_per_commitment_point: PublicKey,
315 }
316
317 /// A channel_reestablish message to be sent or received from a peer
318 #[derive(PartialEq)]
319 pub struct ChannelReestablish {
320         pub(crate) channel_id: [u8; 32],
321         pub(crate) next_local_commitment_number: u64,
322         pub(crate) next_remote_commitment_number: u64,
323         pub(crate) data_loss_protect: Option<DataLossProtect>,
324 }
325
326 /// An announcement_signatures message to be sent or received from a peer
327 #[derive(Clone)]
328 pub struct AnnouncementSignatures {
329         pub(crate) channel_id: [u8; 32],
330         pub(crate) short_channel_id: u64,
331         pub(crate) node_signature: Signature,
332         pub(crate) bitcoin_signature: Signature,
333 }
334
335 /// An address which can be used to connect to a remote peer
336 #[derive(Clone)]
337 pub enum NetAddress {
338         /// An IPv4 address/port on which the peer is listenting.
339         IPv4 {
340                 /// The 4-byte IPv4 address
341                 addr: [u8; 4],
342                 /// The port on which the node is listenting
343                 port: u16,
344         },
345         /// An IPv6 address/port on which the peer is listenting.
346         IPv6 {
347                 /// The 16-byte IPv6 address
348                 addr: [u8; 16],
349                 /// The port on which the node is listenting
350                 port: u16,
351         },
352         /// An old-style Tor onion address/port on which the peer is listening.
353         OnionV2 {
354                 /// The bytes (usually encoded in base32 with ".onion" appended)
355                 addr: [u8; 10],
356                 /// The port on which the node is listenting
357                 port: u16,
358         },
359         /// A new-style Tor onion address/port on which the peer is listening.
360         /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
361         /// wrap as base32 and append ".onion".
362         OnionV3 {
363                 /// The ed25519 long-term public key of the peer
364                 ed25519_pubkey: [u8; 32],
365                 /// The checksum of the pubkey and version, as included in the onion address
366                 checksum: u16,
367                 /// The version byte, as defined by the Tor Onion v3 spec.
368                 version: u8,
369                 /// The port on which the node is listenting
370                 port: u16,
371         },
372 }
373 impl NetAddress {
374         fn get_id(&self) -> u8 {
375                 match self {
376                         &NetAddress::IPv4 {..} => { 1 },
377                         &NetAddress::IPv6 {..} => { 2 },
378                         &NetAddress::OnionV2 {..} => { 3 },
379                         &NetAddress::OnionV3 {..} => { 4 },
380                 }
381         }
382 }
383
384 // Only exposed as broadcast of node_announcement should be filtered by node_id
385 /// The unsigned part of a node_announcement
386 pub struct UnsignedNodeAnnouncement {
387         pub(crate) features: GlobalFeatures,
388         pub(crate) timestamp: u32,
389         /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
390         /// to this node).
391         pub        node_id: PublicKey,
392         pub(crate) rgb: [u8; 3],
393         pub(crate) alias: [u8; 32],
394         /// List of addresses on which this node is reachable. Note that you may only have up to one
395         /// address of each type, if you have more, they may be silently discarded or we may panic!
396         pub(crate) addresses: Vec<NetAddress>,
397         pub(crate) excess_address_data: Vec<u8>,
398         pub(crate) excess_data: Vec<u8>,
399 }
400 /// A node_announcement message to be sent or received from a peer
401 pub struct NodeAnnouncement {
402         pub(crate) signature: Signature,
403         pub(crate) contents: UnsignedNodeAnnouncement,
404 }
405
406 // Only exposed as broadcast of channel_announcement should be filtered by node_id
407 /// The unsigned part of a channel_announcement
408 #[derive(PartialEq, Clone)]
409 pub struct UnsignedChannelAnnouncement {
410         pub(crate) features: GlobalFeatures,
411         pub(crate) chain_hash: Sha256dHash,
412         pub(crate) short_channel_id: u64,
413         /// One of the two node_ids which are endpoints of this channel
414         pub        node_id_1: PublicKey,
415         /// The other of the two node_ids which are endpoints of this channel
416         pub        node_id_2: PublicKey,
417         pub(crate) bitcoin_key_1: PublicKey,
418         pub(crate) bitcoin_key_2: PublicKey,
419         pub(crate) excess_data: Vec<u8>,
420 }
421 /// A channel_announcement message to be sent or received from a peer
422 #[derive(PartialEq, Clone)]
423 pub struct ChannelAnnouncement {
424         pub(crate) node_signature_1: Signature,
425         pub(crate) node_signature_2: Signature,
426         pub(crate) bitcoin_signature_1: Signature,
427         pub(crate) bitcoin_signature_2: Signature,
428         pub(crate) contents: UnsignedChannelAnnouncement,
429 }
430
431 #[derive(PartialEq, Clone)]
432 pub(crate) struct UnsignedChannelUpdate {
433         pub(crate) chain_hash: Sha256dHash,
434         pub(crate) short_channel_id: u64,
435         pub(crate) timestamp: u32,
436         pub(crate) flags: u16,
437         pub(crate) cltv_expiry_delta: u16,
438         pub(crate) htlc_minimum_msat: u64,
439         pub(crate) fee_base_msat: u32,
440         pub(crate) fee_proportional_millionths: u32,
441         pub(crate) excess_data: Vec<u8>,
442 }
443 /// A channel_update message to be sent or received from a peer
444 #[derive(PartialEq, Clone)]
445 pub struct ChannelUpdate {
446         pub(crate) signature: Signature,
447         pub(crate) contents: UnsignedChannelUpdate,
448 }
449
450 /// Used to put an error message in a HandleError
451 pub enum ErrorAction {
452         /// The peer took some action which made us think they were useless. Disconnect them.
453         DisconnectPeer {
454                 /// An error message which we should make an effort to send before we disconnect.
455                 msg: Option<ErrorMessage>
456         },
457         /// The peer did something harmless that we weren't able to process, just log and ignore
458         IgnoreError,
459         /// The peer did something incorrect. Tell them.
460         SendErrorMessage {
461                 /// The message to send.
462                 msg: ErrorMessage
463         },
464 }
465
466 /// An Err type for failure to process messages.
467 pub struct HandleError { //TODO: rename me
468         /// A human-readable message describing the error
469         pub err: &'static str,
470         /// The action which should be taken against the offending peer.
471         pub action: Option<ErrorAction>, //TODO: Make this required
472 }
473
474 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
475 /// transaction updates if they were pending.
476 #[derive(PartialEq)]
477 pub struct CommitmentUpdate {
478         pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
479         pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
480         pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
481         pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
482         pub(crate) update_fee: Option<UpdateFee>,
483         pub(crate) commitment_signed: CommitmentSigned,
484 }
485
486 /// The information we received from a peer along the route of a payment we originated. This is
487 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
488 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
489 pub enum HTLCFailChannelUpdate {
490         /// We received an error which included a full ChannelUpdate message.
491         ChannelUpdateMessage {
492                 /// The unwrapped message we received
493                 msg: ChannelUpdate,
494         },
495         /// We received an error which indicated only that a channel has been closed
496         ChannelClosed {
497                 /// The short_channel_id which has now closed.
498                 short_channel_id: u64,
499                 /// when this true, this channel should be permanently removed from the
500                 /// consideration. Otherwise, this channel can be restored as new channel_update is received
501                 is_permanent: bool,
502         },
503         /// We received an error which indicated only that a node has failed
504         NodeFailure {
505                 /// The node_id that has failed.
506                 node_id: PublicKey,
507                 /// when this true, node should be permanently removed from the
508                 /// consideration. Otherwise, the channels connected to this node can be
509                 /// restored as new channel_update is received
510                 is_permanent: bool,
511         }
512 }
513
514 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
515 /// be sent in the order they appear in the return value, however sometimes the order needs to be
516 /// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
517 /// were originally sent). In those cases, this enum is also returned.
518 #[derive(Clone, PartialEq)]
519 pub enum RAACommitmentOrder {
520         /// Send the CommitmentUpdate messages first
521         CommitmentFirst,
522         /// Send the RevokeAndACK message first
523         RevokeAndACKFirst,
524 }
525
526 /// A trait to describe an object which can receive channel messages.
527 ///
528 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
529 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
530 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
531         //Channel init:
532         /// Handle an incoming open_channel message from the given peer.
533         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
534         /// Handle an incoming accept_channel message from the given peer.
535         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
536         /// Handle an incoming funding_created message from the given peer.
537         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
538         /// Handle an incoming funding_signed message from the given peer.
539         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
540         /// Handle an incoming funding_locked message from the given peer.
541         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
542
543         // Channl close:
544         /// Handle an incoming shutdown message from the given peer.
545         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
546         /// Handle an incoming closing_signed message from the given peer.
547         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
548
549         // HTLC handling:
550         /// Handle an incoming update_add_htlc message from the given peer.
551         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
552         /// Handle an incoming update_fulfill_htlc message from the given peer.
553         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
554         /// Handle an incoming update_fail_htlc message from the given peer.
555         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
556         /// Handle an incoming update_fail_malformed_htlc message from the given peer.
557         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
558         /// Handle an incoming commitment_signed message from the given peer.
559         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
560         /// Handle an incoming revoke_and_ack message from the given peer.
561         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
562
563         /// Handle an incoming update_fee message from the given peer.
564         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
565
566         // Channel-to-announce:
567         /// Handle an incoming announcement_signatures message from the given peer.
568         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
569
570         // Connection loss/reestablish:
571         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
572         /// is believed to be possible in the future (eg they're sending us messages we don't
573         /// understand or indicate they require unknown feature bits), no_connection_possible is set
574         /// and any outstanding channels should be failed.
575         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
576
577         /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
578         fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
579         /// Handle an incoming channel_reestablish message from the given peer.
580         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;
581
582         // Error:
583         /// Handle an incoming error message from the given peer.
584         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
585 }
586
587 /// A trait to describe an object which can receive routing messages.
588 pub trait RoutingMessageHandler : Send + Sync {
589         /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
590         /// false or returning an Err otherwise.
591         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
592         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
593         /// or returning an Err otherwise.
594         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
595         /// Handle an incoming channel_update message, returning true if it should be forwarded on,
596         /// false or returning an Err otherwise.
597         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
598         /// Handle some updates to the route graph that we learned due to an outbound failed payment.
599         fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
600 }
601
602 pub(crate) struct OnionRealm0HopData {
603         pub(crate) short_channel_id: u64,
604         pub(crate) amt_to_forward: u64,
605         pub(crate) outgoing_cltv_value: u32,
606         // 12 bytes of 0-padding
607 }
608
609 mod fuzzy_internal_msgs {
610         // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
611         // them from untrusted input):
612
613         use super::OnionRealm0HopData;
614         pub struct OnionHopData {
615                 pub(crate) realm: u8,
616                 pub(crate) data: OnionRealm0HopData,
617                 pub(crate) hmac: [u8; 32],
618         }
619         unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
620
621         pub struct DecodedOnionErrorPacket {
622                 pub(crate) hmac: [u8; 32],
623                 pub(crate) failuremsg: Vec<u8>,
624                 pub(crate) pad: Vec<u8>,
625         }
626 }
627 #[cfg(feature = "fuzztarget")]
628 pub use self::fuzzy_internal_msgs::*;
629 #[cfg(not(feature = "fuzztarget"))]
630 pub(crate) use self::fuzzy_internal_msgs::*;
631
632 #[derive(Clone)]
633 pub(crate) struct OnionPacket {
634         pub(crate) version: u8,
635         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
636         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
637         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
638         pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
639         pub(crate) hop_data: [u8; 20*65],
640         pub(crate) hmac: [u8; 32],
641 }
642
643 impl PartialEq for OnionPacket {
644         fn eq(&self, other: &OnionPacket) -> bool {
645                 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
646                         if i != j { return false; }
647                 }
648                 self.version == other.version &&
649                         self.public_key == other.public_key &&
650                         self.hmac == other.hmac
651         }
652 }
653
654 #[derive(Clone, PartialEq)]
655 pub(crate) struct OnionErrorPacket {
656         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
657         // (TODO) We limit it in decode to much lower...
658         pub(crate) data: Vec<u8>,
659 }
660
661 impl Error for DecodeError {
662         fn description(&self) -> &str {
663                 match *self {
664                         DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
665                         DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
666                         DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
667                         DecodeError::ShortRead => "Packet extended beyond the provided bytes",
668                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
669                         DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
670                         DecodeError::Io(ref e) => e.description(),
671                 }
672         }
673 }
674 impl fmt::Display for DecodeError {
675         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676                 f.write_str(self.description())
677         }
678 }
679
680 impl fmt::Debug for HandleError {
681         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
682                 f.write_str(self.err)
683         }
684 }
685
686 impl From<::std::io::Error> for DecodeError {
687         fn from(e: ::std::io::Error) -> Self {
688                 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
689                         DecodeError::ShortRead
690                 } else {
691                         DecodeError::Io(e)
692                 }
693         }
694 }
695
696 impl_writeable_len_match!(AcceptChannel, {
697                 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
698                 {_, 270}
699         }, {
700         temporary_channel_id,
701         dust_limit_satoshis,
702         max_htlc_value_in_flight_msat,
703         channel_reserve_satoshis,
704         htlc_minimum_msat,
705         minimum_depth,
706         to_self_delay,
707         max_accepted_htlcs,
708         funding_pubkey,
709         revocation_basepoint,
710         payment_basepoint,
711         delayed_payment_basepoint,
712         htlc_basepoint,
713         first_per_commitment_point,
714         shutdown_scriptpubkey
715 });
716
717 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
718         channel_id,
719         short_channel_id,
720         node_signature,
721         bitcoin_signature
722 });
723
724 impl Writeable for ChannelReestablish {
725         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
726                 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
727                 self.channel_id.write(w)?;
728                 self.next_local_commitment_number.write(w)?;
729                 self.next_remote_commitment_number.write(w)?;
730                 if let Some(ref data_loss_protect) = self.data_loss_protect {
731                         data_loss_protect.your_last_per_commitment_secret.write(w)?;
732                         data_loss_protect.my_current_per_commitment_point.write(w)?;
733                 }
734                 Ok(())
735         }
736 }
737
738 impl<R: Read> Readable<R> for ChannelReestablish{
739         fn read(r: &mut R) -> Result<Self, DecodeError> {
740                 Ok(Self {
741                         channel_id: Readable::read(r)?,
742                         next_local_commitment_number: Readable::read(r)?,
743                         next_remote_commitment_number: Readable::read(r)?,
744                         data_loss_protect: {
745                                 match <[u8; 32] as Readable<R>>::read(r) {
746                                         Ok(your_last_per_commitment_secret) =>
747                                                 Some(DataLossProtect {
748                                                         your_last_per_commitment_secret,
749                                                         my_current_per_commitment_point: Readable::read(r)?,
750                                                 }),
751                                         Err(DecodeError::ShortRead) => None,
752                                         Err(e) => return Err(e)
753                                 }
754                         }
755                 })
756         }
757 }
758
759 impl_writeable!(ClosingSigned, 32+8+64, {
760         channel_id,
761         fee_satoshis,
762         signature
763 });
764
765 impl_writeable_len_match!(CommitmentSigned, {
766                 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
767         }, {
768         channel_id,
769         signature,
770         htlc_signatures
771 });
772
773 impl_writeable_len_match!(DecodedOnionErrorPacket, {
774                 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
775         }, {
776         hmac,
777         failuremsg,
778         pad
779 });
780
781 impl_writeable!(FundingCreated, 32+32+2+64, {
782         temporary_channel_id,
783         funding_txid,
784         funding_output_index,
785         signature
786 });
787
788 impl_writeable!(FundingSigned, 32+64, {
789         channel_id,
790         signature
791 });
792
793 impl_writeable!(FundingLocked, 32+33, {
794         channel_id,
795         next_per_commitment_point
796 });
797
798 impl_writeable_len_match!(GlobalFeatures, {
799                 { GlobalFeatures { ref flags }, flags.len() + 2 }
800         }, {
801         flags
802 });
803
804 impl_writeable_len_match!(LocalFeatures, {
805                 { LocalFeatures { ref flags }, flags.len() + 2 }
806         }, {
807         flags
808 });
809
810 impl_writeable_len_match!(Init, {
811                 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
812         }, {
813         global_features,
814         local_features
815 });
816
817 impl_writeable_len_match!(OpenChannel, {
818                 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
819                 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
820         }, {
821         chain_hash,
822         temporary_channel_id,
823         funding_satoshis,
824         push_msat,
825         dust_limit_satoshis,
826         max_htlc_value_in_flight_msat,
827         channel_reserve_satoshis,
828         htlc_minimum_msat,
829         feerate_per_kw,
830         to_self_delay,
831         max_accepted_htlcs,
832         funding_pubkey,
833         revocation_basepoint,
834         payment_basepoint,
835         delayed_payment_basepoint,
836         htlc_basepoint,
837         first_per_commitment_point,
838         channel_flags,
839         shutdown_scriptpubkey
840 });
841
842 impl_writeable!(RevokeAndACK, 32+32+33, {
843         channel_id,
844         per_commitment_secret,
845         next_per_commitment_point
846 });
847
848 impl_writeable_len_match!(Shutdown, {
849                 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
850         }, {
851         channel_id,
852         scriptpubkey
853 });
854
855 impl_writeable_len_match!(UpdateFailHTLC, {
856                 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
857         }, {
858         channel_id,
859         htlc_id,
860         reason
861 });
862
863 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
864         channel_id,
865         htlc_id,
866         sha256_of_onion,
867         failure_code
868 });
869
870 impl_writeable!(UpdateFee, 32+4, {
871         channel_id,
872         feerate_per_kw
873 });
874
875 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
876         channel_id,
877         htlc_id,
878         payment_preimage
879 });
880
881 impl_writeable_len_match!(OnionErrorPacket, {
882                 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
883         }, {
884         data
885 });
886
887 impl Writeable for OnionPacket {
888         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
889                 w.size_hint(1 + 33 + 20*65 + 32);
890                 self.version.write(w)?;
891                 match self.public_key {
892                         Ok(pubkey) => pubkey.write(w)?,
893                         Err(_) => [0u8;33].write(w)?,
894                 }
895                 w.write_all(&self.hop_data)?;
896                 self.hmac.write(w)?;
897                 Ok(())
898         }
899 }
900
901 impl<R: Read> Readable<R> for OnionPacket {
902         fn read(r: &mut R) -> Result<Self, DecodeError> {
903                 Ok(OnionPacket {
904                         version: Readable::read(r)?,
905                         public_key: {
906                                 let mut buf = [0u8;33];
907                                 r.read_exact(&mut buf)?;
908                                 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
909                         },
910                         hop_data: Readable::read(r)?,
911                         hmac: Readable::read(r)?,
912                 })
913         }
914 }
915
916 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
917         channel_id,
918         htlc_id,
919         amount_msat,
920         payment_hash,
921         cltv_expiry,
922         onion_routing_packet
923 });
924
925 impl Writeable for OnionRealm0HopData {
926         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
927                 w.size_hint(32);
928                 self.short_channel_id.write(w)?;
929                 self.amt_to_forward.write(w)?;
930                 self.outgoing_cltv_value.write(w)?;
931                 w.write_all(&[0;12])?;
932                 Ok(())
933         }
934 }
935
936 impl<R: Read> Readable<R> for OnionRealm0HopData {
937         fn read(r: &mut R) -> Result<Self, DecodeError> {
938                 Ok(OnionRealm0HopData {
939                         short_channel_id: Readable::read(r)?,
940                         amt_to_forward: Readable::read(r)?,
941                         outgoing_cltv_value: {
942                                 let v: u32 = Readable::read(r)?;
943                                 r.read_exact(&mut [0; 12])?;
944                                 v
945                         }
946                 })
947         }
948 }
949
950 impl Writeable for OnionHopData {
951         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
952                 w.size_hint(65);
953                 self.realm.write(w)?;
954                 self.data.write(w)?;
955                 self.hmac.write(w)?;
956                 Ok(())
957         }
958 }
959
960 impl<R: Read> Readable<R> for OnionHopData {
961         fn read(r: &mut R) -> Result<Self, DecodeError> {
962                 Ok(OnionHopData {
963                         realm: {
964                                 let r: u8 = Readable::read(r)?;
965                                 if r != 0 {
966                                         return Err(DecodeError::UnknownVersion);
967                                 }
968                                 r
969                         },
970                         data: Readable::read(r)?,
971                         hmac: Readable::read(r)?,
972                 })
973         }
974 }
975
976 impl Writeable for Ping {
977         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
978                 w.size_hint(self.byteslen as usize + 4);
979                 self.ponglen.write(w)?;
980                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
981                 Ok(())
982         }
983 }
984
985 impl<R: Read> Readable<R> for Ping {
986         fn read(r: &mut R) -> Result<Self, DecodeError> {
987                 Ok(Ping {
988                         ponglen: Readable::read(r)?,
989                         byteslen: {
990                                 let byteslen = Readable::read(r)?;
991                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
992                                 byteslen
993                         }
994                 })
995         }
996 }
997
998 impl Writeable for Pong {
999         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1000                 w.size_hint(self.byteslen as usize + 2);
1001                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1002                 Ok(())
1003         }
1004 }
1005
1006 impl<R: Read> Readable<R> for Pong {
1007         fn read(r: &mut R) -> Result<Self, DecodeError> {
1008                 Ok(Pong {
1009                         byteslen: {
1010                                 let byteslen = Readable::read(r)?;
1011                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1012                                 byteslen
1013                         }
1014                 })
1015         }
1016 }
1017
1018 impl Writeable for UnsignedChannelAnnouncement {
1019         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1020                 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1021                 self.features.write(w)?;
1022                 self.chain_hash.write(w)?;
1023                 self.short_channel_id.write(w)?;
1024                 self.node_id_1.write(w)?;
1025                 self.node_id_2.write(w)?;
1026                 self.bitcoin_key_1.write(w)?;
1027                 self.bitcoin_key_2.write(w)?;
1028                 w.write_all(&self.excess_data[..])?;
1029                 Ok(())
1030         }
1031 }
1032
1033 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1034         fn read(r: &mut R) -> Result<Self, DecodeError> {
1035                 Ok(Self {
1036                         features: {
1037                                 let f: GlobalFeatures = Readable::read(r)?;
1038                                 if f.requires_unknown_bits() {
1039                                         return Err(DecodeError::UnknownRequiredFeature);
1040                                 }
1041                                 f
1042                         },
1043                         chain_hash: Readable::read(r)?,
1044                         short_channel_id: Readable::read(r)?,
1045                         node_id_1: Readable::read(r)?,
1046                         node_id_2: Readable::read(r)?,
1047                         bitcoin_key_1: Readable::read(r)?,
1048                         bitcoin_key_2: Readable::read(r)?,
1049                         excess_data: {
1050                                 let mut excess_data = vec![];
1051                                 r.read_to_end(&mut excess_data)?;
1052                                 excess_data
1053                         },
1054                 })
1055         }
1056 }
1057
1058 impl_writeable_len_match!(ChannelAnnouncement, {
1059                 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1060                         2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1061         }, {
1062         node_signature_1,
1063         node_signature_2,
1064         bitcoin_signature_1,
1065         bitcoin_signature_2,
1066         contents
1067 });
1068
1069 impl Writeable for UnsignedChannelUpdate {
1070         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1071                 w.size_hint(64 + self.excess_data.len());
1072                 self.chain_hash.write(w)?;
1073                 self.short_channel_id.write(w)?;
1074                 self.timestamp.write(w)?;
1075                 self.flags.write(w)?;
1076                 self.cltv_expiry_delta.write(w)?;
1077                 self.htlc_minimum_msat.write(w)?;
1078                 self.fee_base_msat.write(w)?;
1079                 self.fee_proportional_millionths.write(w)?;
1080                 w.write_all(&self.excess_data[..])?;
1081                 Ok(())
1082         }
1083 }
1084
1085 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1086         fn read(r: &mut R) -> Result<Self, DecodeError> {
1087                 Ok(Self {
1088                         chain_hash: Readable::read(r)?,
1089                         short_channel_id: Readable::read(r)?,
1090                         timestamp: Readable::read(r)?,
1091                         flags: Readable::read(r)?,
1092                         cltv_expiry_delta: Readable::read(r)?,
1093                         htlc_minimum_msat: Readable::read(r)?,
1094                         fee_base_msat: Readable::read(r)?,
1095                         fee_proportional_millionths: Readable::read(r)?,
1096                         excess_data: {
1097                                 let mut excess_data = vec![];
1098                                 r.read_to_end(&mut excess_data)?;
1099                                 excess_data
1100                         },
1101                 })
1102         }
1103 }
1104
1105 impl_writeable_len_match!(ChannelUpdate, {
1106                 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1107                         64 + excess_data.len() + 64 }
1108         }, {
1109         signature,
1110         contents
1111 });
1112
1113 impl Writeable for ErrorMessage {
1114         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1115                 w.size_hint(32 + 2 + self.data.len());
1116                 self.channel_id.write(w)?;
1117                 (self.data.len() as u16).write(w)?;
1118                 w.write_all(self.data.as_bytes())?;
1119                 Ok(())
1120         }
1121 }
1122
1123 impl<R: Read> Readable<R> for ErrorMessage {
1124         fn read(r: &mut R) -> Result<Self, DecodeError> {
1125                 Ok(Self {
1126                         channel_id: Readable::read(r)?,
1127                         data: {
1128                                 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1129                                 let mut data = vec![];
1130                                 let data_len = r.read_to_end(&mut data)?;
1131                                 sz = cmp::min(data_len, sz);
1132                                 match String::from_utf8(data[..sz as usize].to_vec()) {
1133                                         Ok(s) => s,
1134                                         Err(_) => return Err(DecodeError::InvalidValue),
1135                                 }
1136                         }
1137                 })
1138         }
1139 }
1140
1141 impl Writeable for UnsignedNodeAnnouncement {
1142         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1143                 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1144                 self.features.write(w)?;
1145                 self.timestamp.write(w)?;
1146                 self.node_id.write(w)?;
1147                 w.write_all(&self.rgb)?;
1148                 self.alias.write(w)?;
1149
1150                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1151                 let mut addrs_to_encode = self.addresses.clone();
1152                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1153                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1154                 for addr in addrs_to_encode.iter() {
1155                         match addr {
1156                                 &NetAddress::IPv4{addr, port} => {
1157                                         addr_slice.push(1);
1158                                         addr_slice.extend_from_slice(&addr);
1159                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1160                                 },
1161                                 &NetAddress::IPv6{addr, port} => {
1162                                         addr_slice.push(2);
1163                                         addr_slice.extend_from_slice(&addr);
1164                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1165                                 },
1166                                 &NetAddress::OnionV2{addr, port} => {
1167                                         addr_slice.push(3);
1168                                         addr_slice.extend_from_slice(&addr);
1169                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1170                                 },
1171                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1172                                         addr_slice.push(4);
1173                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1174                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1175                                         addr_slice.push(version);
1176                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1177                                 },
1178                         }
1179                 }
1180                 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1181                 w.write_all(&addr_slice[..])?;
1182                 w.write_all(&self.excess_address_data[..])?;
1183                 w.write_all(&self.excess_data[..])?;
1184                 Ok(())
1185         }
1186 }
1187
1188 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1189         fn read(r: &mut R) -> Result<Self, DecodeError> {
1190                 let features: GlobalFeatures = Readable::read(r)?;
1191                 if features.requires_unknown_bits() {
1192                         return Err(DecodeError::UnknownRequiredFeature);
1193                 }
1194                 let timestamp: u32 = Readable::read(r)?;
1195                 let node_id: PublicKey = Readable::read(r)?;
1196                 let mut rgb = [0; 3];
1197                 r.read_exact(&mut rgb)?;
1198                 let alias: [u8; 32] = Readable::read(r)?;
1199
1200                 let addrlen: u16 = Readable::read(r)?;
1201                 let mut addr_readpos = 0;
1202                 let mut addresses = Vec::with_capacity(4);
1203                 let mut f: u8 = 0;
1204                 let mut excess = 0;
1205                 loop {
1206                         if addrlen <= addr_readpos { break; }
1207                         f = Readable::read(r)?;
1208                         match f {
1209                                 1 => {
1210                                         if addresses.len() > 0 {
1211                                                 return Err(DecodeError::ExtraAddressesPerType);
1212                                         }
1213                                         if addrlen < addr_readpos + 1 + 6 {
1214                                                 return Err(DecodeError::BadLengthDescriptor);
1215                                         }
1216                                         addresses.push(NetAddress::IPv4 {
1217                                                 addr: {
1218                                                         let mut addr = [0; 4];
1219                                                         r.read_exact(&mut addr)?;
1220                                                         addr
1221                                                 },
1222                                                 port: Readable::read(r)?,
1223                                         });
1224                                         addr_readpos += 1 + 6
1225                                 },
1226                                 2 => {
1227                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1228                                                 return Err(DecodeError::ExtraAddressesPerType);
1229                                         }
1230                                         if addrlen < addr_readpos + 1 + 18 {
1231                                                 return Err(DecodeError::BadLengthDescriptor);
1232                                         }
1233                                         addresses.push(NetAddress::IPv6 {
1234                                                 addr: {
1235                                                         let mut addr = [0; 16];
1236                                                         r.read_exact(&mut addr)?;
1237                                                         addr
1238                                                 },
1239                                                 port: Readable::read(r)?,
1240                                         });
1241                                         addr_readpos += 1 + 18
1242                                 },
1243                                 3 => {
1244                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1245                                                 return Err(DecodeError::ExtraAddressesPerType);
1246                                         }
1247                                         if addrlen < addr_readpos + 1 + 12 {
1248                                                 return Err(DecodeError::BadLengthDescriptor);
1249                                         }
1250                                         addresses.push(NetAddress::OnionV2 {
1251                                                 addr: {
1252                                                         let mut addr = [0; 10];
1253                                                         r.read_exact(&mut addr)?;
1254                                                         addr
1255                                                 },
1256                                                 port: Readable::read(r)?,
1257                                         });
1258                                         addr_readpos += 1 + 12
1259                                 },
1260                                 4 => {
1261                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1262                                                 return Err(DecodeError::ExtraAddressesPerType);
1263                                         }
1264                                         if addrlen < addr_readpos + 1 + 37 {
1265                                                 return Err(DecodeError::BadLengthDescriptor);
1266                                         }
1267                                         addresses.push(NetAddress::OnionV3 {
1268                                                 ed25519_pubkey: Readable::read(r)?,
1269                                                 checksum: Readable::read(r)?,
1270                                                 version: Readable::read(r)?,
1271                                                 port: Readable::read(r)?,
1272                                         });
1273                                         addr_readpos += 1 + 37
1274                                 },
1275                                 _ => { excess = 1; break; }
1276                         }
1277                 }
1278
1279                 let mut excess_data = vec![];
1280                 let excess_address_data = if addr_readpos < addrlen {
1281                         let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1282                         r.read_exact(&mut excess_address_data[excess..])?;
1283                         if excess == 1 {
1284                                 excess_address_data[0] = f;
1285                         }
1286                         excess_address_data
1287                 } else {
1288                         if excess == 1 {
1289                                 excess_data.push(f);
1290                         }
1291                         Vec::new()
1292                 };
1293
1294                 Ok(UnsignedNodeAnnouncement {
1295                         features: features,
1296                         timestamp: timestamp,
1297                         node_id: node_id,
1298                         rgb: rgb,
1299                         alias: alias,
1300                         addresses: addresses,
1301                         excess_address_data: excess_address_data,
1302                         excess_data: {
1303                                 r.read_to_end(&mut excess_data)?;
1304                                 excess_data
1305                         },
1306                 })
1307         }
1308 }
1309
1310 impl_writeable_len_match!(NodeAnnouncement, {
1311                 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1312                         64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1313         }, {
1314         signature,
1315         contents
1316 });
1317
1318 #[cfg(test)]
1319 mod tests {
1320         use hex;
1321         use ln::msgs;
1322         use util::ser::Writeable;
1323         use secp256k1::key::{PublicKey,SecretKey};
1324         use secp256k1::Secp256k1;
1325
1326         #[test]
1327         fn encoding_channel_reestablish_no_secret() {
1328                 let cr = msgs::ChannelReestablish {
1329                         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],
1330                         next_local_commitment_number: 3,
1331                         next_remote_commitment_number: 4,
1332                         data_loss_protect: None,
1333                 };
1334
1335                 let encoded_value = cr.encode();
1336                 assert_eq!(
1337                         encoded_value,
1338                         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]
1339                 );
1340         }
1341
1342         #[test]
1343         fn encoding_channel_reestablish_with_secret() {
1344                 let public_key = {
1345                         let secp_ctx = Secp256k1::new();
1346                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1347                 };
1348
1349                 let cr = msgs::ChannelReestablish {
1350                         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],
1351                         next_local_commitment_number: 3,
1352                         next_remote_commitment_number: 4,
1353                         data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1354                 };
1355
1356                 let encoded_value = cr.encode();
1357                 assert_eq!(
1358                         encoded_value,
1359                         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]
1360                 );
1361         }
1362 }