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