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