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