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