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