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