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