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