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