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