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