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