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