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