Expose CommitmentUpdate contents
[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         /// update_add_htlc messages which should be sent
559         pub update_add_htlcs: Vec<UpdateAddHTLC>,
560         /// update_fulfill_htlc messages which should be sent
561         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
562         /// update_fail_htlc messages which should be sent
563         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
564         /// update_fail_malformed_htlc messages which should be sent
565         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
566         /// An update_fee message which should be sent
567         pub update_fee: Option<UpdateFee>,
568         /// Finally, the commitment_signed message which should be sent
569         pub commitment_signed: CommitmentSigned,
570 }
571
572 /// The information we received from a peer along the route of a payment we originated. This is
573 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
574 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
575 #[derive(Clone)]
576 pub enum HTLCFailChannelUpdate {
577         /// We received an error which included a full ChannelUpdate message.
578         ChannelUpdateMessage {
579                 /// The unwrapped message we received
580                 msg: ChannelUpdate,
581         },
582         /// We received an error which indicated only that a channel has been closed
583         ChannelClosed {
584                 /// The short_channel_id which has now closed.
585                 short_channel_id: u64,
586                 /// when this true, this channel should be permanently removed from the
587                 /// consideration. Otherwise, this channel can be restored as new channel_update is received
588                 is_permanent: bool,
589         },
590         /// We received an error which indicated only that a node has failed
591         NodeFailure {
592                 /// The node_id that has failed.
593                 node_id: PublicKey,
594                 /// when this true, node should be permanently removed from the
595                 /// consideration. Otherwise, the channels connected to this node can be
596                 /// restored as new channel_update is received
597                 is_permanent: bool,
598         }
599 }
600
601 /// Messages could have optional fields to use with extended features
602 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
603 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
604 /// separate enum type for them.
605 #[derive(Clone, PartialEq)]
606 pub enum OptionalField<T> {
607         /// Optional field is included in message
608         Present(T),
609         /// Optional field is absent in message
610         Absent
611 }
612
613 /// A trait to describe an object which can receive channel messages.
614 ///
615 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
616 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
617 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
618         //Channel init:
619         /// Handle an incoming open_channel message from the given peer.
620         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
621         /// Handle an incoming accept_channel message from the given peer.
622         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
623         /// Handle an incoming funding_created message from the given peer.
624         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
625         /// Handle an incoming funding_signed message from the given peer.
626         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
627         /// Handle an incoming funding_locked message from the given peer.
628         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
629
630         // Channl close:
631         /// Handle an incoming shutdown message from the given peer.
632         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
633         /// Handle an incoming closing_signed message from the given peer.
634         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
635
636         // HTLC handling:
637         /// Handle an incoming update_add_htlc message from the given peer.
638         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
639         /// Handle an incoming update_fulfill_htlc message from the given peer.
640         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
641         /// Handle an incoming update_fail_htlc message from the given peer.
642         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
643         /// Handle an incoming update_fail_malformed_htlc message from the given peer.
644         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
645         /// Handle an incoming commitment_signed message from the given peer.
646         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
647         /// Handle an incoming revoke_and_ack message from the given peer.
648         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
649
650         /// Handle an incoming update_fee message from the given peer.
651         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
652
653         // Channel-to-announce:
654         /// Handle an incoming announcement_signatures message from the given peer.
655         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
656
657         // Connection loss/reestablish:
658         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
659         /// is believed to be possible in the future (eg they're sending us messages we don't
660         /// understand or indicate they require unknown feature bits), no_connection_possible is set
661         /// and any outstanding channels should be failed.
662         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
663
664         /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
665         fn peer_connected(&self, their_node_id: &PublicKey);
666         /// Handle an incoming channel_reestablish message from the given peer.
667         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
668
669         // Error:
670         /// Handle an incoming error message from the given peer.
671         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
672 }
673
674 /// A trait to describe an object which can receive routing messages.
675 pub trait RoutingMessageHandler : Send + Sync {
676         /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
677         /// false or returning an Err otherwise.
678         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
679         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
680         /// or returning an Err otherwise.
681         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
682         /// Handle an incoming channel_update message, returning true if it should be forwarded on,
683         /// false or returning an Err otherwise.
684         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
685         /// Handle some updates to the route graph that we learned due to an outbound failed payment.
686         fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
687         /// Gets a subset of the channel announcements and updates required to dump our routing table
688         /// to a remote node, starting at the short_channel_id indicated by starting_point and
689         /// including batch_amount entries.
690         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
691         /// Gets a subset of the node announcements required to dump our routing table to a remote node,
692         /// starting at the node *after* the provided publickey and including batch_amount entries.
693         /// If None is provided for starting_point, we start at the first node.
694         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
695 }
696
697 pub(crate) struct OnionRealm0HopData {
698         pub(crate) short_channel_id: u64,
699         pub(crate) amt_to_forward: u64,
700         pub(crate) outgoing_cltv_value: u32,
701         // 12 bytes of 0-padding
702 }
703
704 mod fuzzy_internal_msgs {
705         // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
706         // them from untrusted input):
707
708         use super::OnionRealm0HopData;
709         pub struct OnionHopData {
710                 pub(crate) realm: u8,
711                 pub(crate) data: OnionRealm0HopData,
712                 pub(crate) hmac: [u8; 32],
713         }
714         unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
715
716         pub struct DecodedOnionErrorPacket {
717                 pub(crate) hmac: [u8; 32],
718                 pub(crate) failuremsg: Vec<u8>,
719                 pub(crate) pad: Vec<u8>,
720         }
721 }
722 #[cfg(feature = "fuzztarget")]
723 pub use self::fuzzy_internal_msgs::*;
724 #[cfg(not(feature = "fuzztarget"))]
725 pub(crate) use self::fuzzy_internal_msgs::*;
726
727 #[derive(Clone)]
728 pub(crate) struct OnionPacket {
729         pub(crate) version: u8,
730         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
731         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
732         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
733         pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
734         pub(crate) hop_data: [u8; 20*65],
735         pub(crate) hmac: [u8; 32],
736 }
737
738 impl PartialEq for OnionPacket {
739         fn eq(&self, other: &OnionPacket) -> bool {
740                 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
741                         if i != j { return false; }
742                 }
743                 self.version == other.version &&
744                         self.public_key == other.public_key &&
745                         self.hmac == other.hmac
746         }
747 }
748
749 #[derive(Clone, PartialEq)]
750 pub(crate) struct OnionErrorPacket {
751         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
752         // (TODO) We limit it in decode to much lower...
753         pub(crate) data: Vec<u8>,
754 }
755
756 impl Error for DecodeError {
757         fn description(&self) -> &str {
758                 match *self {
759                         DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
760                         DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
761                         DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
762                         DecodeError::ShortRead => "Packet extended beyond the provided bytes",
763                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
764                         DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
765                         DecodeError::Io(ref e) => e.description(),
766                 }
767         }
768 }
769 impl fmt::Display for DecodeError {
770         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771                 f.write_str(self.description())
772         }
773 }
774
775 impl fmt::Debug for HandleError {
776         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777                 f.write_str(self.err)
778         }
779 }
780
781 impl From<::std::io::Error> for DecodeError {
782         fn from(e: ::std::io::Error) -> Self {
783                 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
784                         DecodeError::ShortRead
785                 } else {
786                         DecodeError::Io(e)
787                 }
788         }
789 }
790
791 impl Writeable for OptionalField<Script> {
792         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
793                 match *self {
794                         OptionalField::Present(ref script) => {
795                                 // Note that Writeable for script includes the 16-bit length tag for us
796                                 script.write(w)?;
797                         },
798                         OptionalField::Absent => {}
799                 }
800                 Ok(())
801         }
802 }
803
804 impl<R: Read> Readable<R> for OptionalField<Script> {
805         fn read(r: &mut R) -> Result<Self, DecodeError> {
806                 match <u16 as Readable<R>>::read(r) {
807                         Ok(len) => {
808                                 let mut buf = vec![0; len as usize];
809                                 r.read_exact(&mut buf)?;
810                                 Ok(OptionalField::Present(Script::from(buf)))
811                         },
812                         Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
813                         Err(e) => Err(e)
814                 }
815         }
816 }
817
818 impl_writeable_len_match!(AcceptChannel, {
819                 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
820                 {_, 270}
821         }, {
822         temporary_channel_id,
823         dust_limit_satoshis,
824         max_htlc_value_in_flight_msat,
825         channel_reserve_satoshis,
826         htlc_minimum_msat,
827         minimum_depth,
828         to_self_delay,
829         max_accepted_htlcs,
830         funding_pubkey,
831         revocation_basepoint,
832         payment_basepoint,
833         delayed_payment_basepoint,
834         htlc_basepoint,
835         first_per_commitment_point,
836         shutdown_scriptpubkey
837 });
838
839 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
840         channel_id,
841         short_channel_id,
842         node_signature,
843         bitcoin_signature
844 });
845
846 impl Writeable for ChannelReestablish {
847         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
848                 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
849                 self.channel_id.write(w)?;
850                 self.next_local_commitment_number.write(w)?;
851                 self.next_remote_commitment_number.write(w)?;
852                 match self.data_loss_protect {
853                         OptionalField::Present(ref data_loss_protect) => {
854                                 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
855                                 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
856                         },
857                         OptionalField::Absent => {}
858                 }
859                 Ok(())
860         }
861 }
862
863 impl<R: Read> Readable<R> for ChannelReestablish{
864         fn read(r: &mut R) -> Result<Self, DecodeError> {
865                 Ok(Self {
866                         channel_id: Readable::read(r)?,
867                         next_local_commitment_number: Readable::read(r)?,
868                         next_remote_commitment_number: Readable::read(r)?,
869                         data_loss_protect: {
870                                 match <[u8; 32] as Readable<R>>::read(r) {
871                                         Ok(your_last_per_commitment_secret) =>
872                                                 OptionalField::Present(DataLossProtect {
873                                                         your_last_per_commitment_secret,
874                                                         my_current_per_commitment_point: Readable::read(r)?,
875                                                 }),
876                                         Err(DecodeError::ShortRead) => OptionalField::Absent,
877                                         Err(e) => return Err(e)
878                                 }
879                         }
880                 })
881         }
882 }
883
884 impl_writeable!(ClosingSigned, 32+8+64, {
885         channel_id,
886         fee_satoshis,
887         signature
888 });
889
890 impl_writeable_len_match!(CommitmentSigned, {
891                 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
892         }, {
893         channel_id,
894         signature,
895         htlc_signatures
896 });
897
898 impl_writeable_len_match!(DecodedOnionErrorPacket, {
899                 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
900         }, {
901         hmac,
902         failuremsg,
903         pad
904 });
905
906 impl_writeable!(FundingCreated, 32+32+2+64, {
907         temporary_channel_id,
908         funding_txid,
909         funding_output_index,
910         signature
911 });
912
913 impl_writeable!(FundingSigned, 32+64, {
914         channel_id,
915         signature
916 });
917
918 impl_writeable!(FundingLocked, 32+33, {
919         channel_id,
920         next_per_commitment_point
921 });
922
923 impl_writeable_len_match!(GlobalFeatures, {
924                 { GlobalFeatures { ref flags }, flags.len() + 2 }
925         }, {
926         flags
927 });
928
929 impl_writeable_len_match!(LocalFeatures, {
930                 { LocalFeatures { ref flags }, flags.len() + 2 }
931         }, {
932         flags
933 });
934
935 impl_writeable_len_match!(Init, {
936                 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
937         }, {
938         global_features,
939         local_features
940 });
941
942 impl_writeable_len_match!(OpenChannel, {
943                 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
944                 { _, 319 }
945         }, {
946         chain_hash,
947         temporary_channel_id,
948         funding_satoshis,
949         push_msat,
950         dust_limit_satoshis,
951         max_htlc_value_in_flight_msat,
952         channel_reserve_satoshis,
953         htlc_minimum_msat,
954         feerate_per_kw,
955         to_self_delay,
956         max_accepted_htlcs,
957         funding_pubkey,
958         revocation_basepoint,
959         payment_basepoint,
960         delayed_payment_basepoint,
961         htlc_basepoint,
962         first_per_commitment_point,
963         channel_flags,
964         shutdown_scriptpubkey
965 });
966
967 impl_writeable!(RevokeAndACK, 32+32+33, {
968         channel_id,
969         per_commitment_secret,
970         next_per_commitment_point
971 });
972
973 impl_writeable_len_match!(Shutdown, {
974                 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
975         }, {
976         channel_id,
977         scriptpubkey
978 });
979
980 impl_writeable_len_match!(UpdateFailHTLC, {
981                 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
982         }, {
983         channel_id,
984         htlc_id,
985         reason
986 });
987
988 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
989         channel_id,
990         htlc_id,
991         sha256_of_onion,
992         failure_code
993 });
994
995 impl_writeable!(UpdateFee, 32+4, {
996         channel_id,
997         feerate_per_kw
998 });
999
1000 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1001         channel_id,
1002         htlc_id,
1003         payment_preimage
1004 });
1005
1006 impl_writeable_len_match!(OnionErrorPacket, {
1007                 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1008         }, {
1009         data
1010 });
1011
1012 impl Writeable for OnionPacket {
1013         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1014                 w.size_hint(1 + 33 + 20*65 + 32);
1015                 self.version.write(w)?;
1016                 match self.public_key {
1017                         Ok(pubkey) => pubkey.write(w)?,
1018                         Err(_) => [0u8;33].write(w)?,
1019                 }
1020                 w.write_all(&self.hop_data)?;
1021                 self.hmac.write(w)?;
1022                 Ok(())
1023         }
1024 }
1025
1026 impl<R: Read> Readable<R> for OnionPacket {
1027         fn read(r: &mut R) -> Result<Self, DecodeError> {
1028                 Ok(OnionPacket {
1029                         version: Readable::read(r)?,
1030                         public_key: {
1031                                 let mut buf = [0u8;33];
1032                                 r.read_exact(&mut buf)?;
1033                                 PublicKey::from_slice(&buf)
1034                         },
1035                         hop_data: Readable::read(r)?,
1036                         hmac: Readable::read(r)?,
1037                 })
1038         }
1039 }
1040
1041 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1042         channel_id,
1043         htlc_id,
1044         amount_msat,
1045         payment_hash,
1046         cltv_expiry,
1047         onion_routing_packet
1048 });
1049
1050 impl Writeable for OnionRealm0HopData {
1051         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1052                 w.size_hint(32);
1053                 self.short_channel_id.write(w)?;
1054                 self.amt_to_forward.write(w)?;
1055                 self.outgoing_cltv_value.write(w)?;
1056                 w.write_all(&[0;12])?;
1057                 Ok(())
1058         }
1059 }
1060
1061 impl<R: Read> Readable<R> for OnionRealm0HopData {
1062         fn read(r: &mut R) -> Result<Self, DecodeError> {
1063                 Ok(OnionRealm0HopData {
1064                         short_channel_id: Readable::read(r)?,
1065                         amt_to_forward: Readable::read(r)?,
1066                         outgoing_cltv_value: {
1067                                 let v: u32 = Readable::read(r)?;
1068                                 r.read_exact(&mut [0; 12])?;
1069                                 v
1070                         }
1071                 })
1072         }
1073 }
1074
1075 impl Writeable for OnionHopData {
1076         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1077                 w.size_hint(65);
1078                 self.realm.write(w)?;
1079                 self.data.write(w)?;
1080                 self.hmac.write(w)?;
1081                 Ok(())
1082         }
1083 }
1084
1085 impl<R: Read> Readable<R> for OnionHopData {
1086         fn read(r: &mut R) -> Result<Self, DecodeError> {
1087                 Ok(OnionHopData {
1088                         realm: {
1089                                 let r: u8 = Readable::read(r)?;
1090                                 if r != 0 {
1091                                         return Err(DecodeError::UnknownVersion);
1092                                 }
1093                                 r
1094                         },
1095                         data: Readable::read(r)?,
1096                         hmac: Readable::read(r)?,
1097                 })
1098         }
1099 }
1100
1101 impl Writeable for Ping {
1102         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1103                 w.size_hint(self.byteslen as usize + 4);
1104                 self.ponglen.write(w)?;
1105                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1106                 Ok(())
1107         }
1108 }
1109
1110 impl<R: Read> Readable<R> for Ping {
1111         fn read(r: &mut R) -> Result<Self, DecodeError> {
1112                 Ok(Ping {
1113                         ponglen: Readable::read(r)?,
1114                         byteslen: {
1115                                 let byteslen = Readable::read(r)?;
1116                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1117                                 byteslen
1118                         }
1119                 })
1120         }
1121 }
1122
1123 impl Writeable for Pong {
1124         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1125                 w.size_hint(self.byteslen as usize + 2);
1126                 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1127                 Ok(())
1128         }
1129 }
1130
1131 impl<R: Read> Readable<R> for Pong {
1132         fn read(r: &mut R) -> Result<Self, DecodeError> {
1133                 Ok(Pong {
1134                         byteslen: {
1135                                 let byteslen = Readable::read(r)?;
1136                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1137                                 byteslen
1138                         }
1139                 })
1140         }
1141 }
1142
1143 impl Writeable for UnsignedChannelAnnouncement {
1144         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1145                 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1146                 self.features.write(w)?;
1147                 self.chain_hash.write(w)?;
1148                 self.short_channel_id.write(w)?;
1149                 self.node_id_1.write(w)?;
1150                 self.node_id_2.write(w)?;
1151                 self.bitcoin_key_1.write(w)?;
1152                 self.bitcoin_key_2.write(w)?;
1153                 w.write_all(&self.excess_data[..])?;
1154                 Ok(())
1155         }
1156 }
1157
1158 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1159         fn read(r: &mut R) -> Result<Self, DecodeError> {
1160                 Ok(Self {
1161                         features: {
1162                                 let f: GlobalFeatures = Readable::read(r)?;
1163                                 if f.requires_unknown_bits() {
1164                                         return Err(DecodeError::UnknownRequiredFeature);
1165                                 }
1166                                 f
1167                         },
1168                         chain_hash: Readable::read(r)?,
1169                         short_channel_id: Readable::read(r)?,
1170                         node_id_1: Readable::read(r)?,
1171                         node_id_2: Readable::read(r)?,
1172                         bitcoin_key_1: Readable::read(r)?,
1173                         bitcoin_key_2: Readable::read(r)?,
1174                         excess_data: {
1175                                 let mut excess_data = vec![];
1176                                 r.read_to_end(&mut excess_data)?;
1177                                 excess_data
1178                         },
1179                 })
1180         }
1181 }
1182
1183 impl_writeable_len_match!(ChannelAnnouncement, {
1184                 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1185                         2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1186         }, {
1187         node_signature_1,
1188         node_signature_2,
1189         bitcoin_signature_1,
1190         bitcoin_signature_2,
1191         contents
1192 });
1193
1194 impl Writeable for UnsignedChannelUpdate {
1195         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1196                 w.size_hint(64 + self.excess_data.len());
1197                 self.chain_hash.write(w)?;
1198                 self.short_channel_id.write(w)?;
1199                 self.timestamp.write(w)?;
1200                 self.flags.write(w)?;
1201                 self.cltv_expiry_delta.write(w)?;
1202                 self.htlc_minimum_msat.write(w)?;
1203                 self.fee_base_msat.write(w)?;
1204                 self.fee_proportional_millionths.write(w)?;
1205                 w.write_all(&self.excess_data[..])?;
1206                 Ok(())
1207         }
1208 }
1209
1210 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1211         fn read(r: &mut R) -> Result<Self, DecodeError> {
1212                 Ok(Self {
1213                         chain_hash: Readable::read(r)?,
1214                         short_channel_id: Readable::read(r)?,
1215                         timestamp: Readable::read(r)?,
1216                         flags: Readable::read(r)?,
1217                         cltv_expiry_delta: Readable::read(r)?,
1218                         htlc_minimum_msat: Readable::read(r)?,
1219                         fee_base_msat: Readable::read(r)?,
1220                         fee_proportional_millionths: Readable::read(r)?,
1221                         excess_data: {
1222                                 let mut excess_data = vec![];
1223                                 r.read_to_end(&mut excess_data)?;
1224                                 excess_data
1225                         },
1226                 })
1227         }
1228 }
1229
1230 impl_writeable_len_match!(ChannelUpdate, {
1231                 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1232                         64 + excess_data.len() + 64 }
1233         }, {
1234         signature,
1235         contents
1236 });
1237
1238 impl Writeable for ErrorMessage {
1239         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1240                 w.size_hint(32 + 2 + self.data.len());
1241                 self.channel_id.write(w)?;
1242                 (self.data.len() as u16).write(w)?;
1243                 w.write_all(self.data.as_bytes())?;
1244                 Ok(())
1245         }
1246 }
1247
1248 impl<R: Read> Readable<R> for ErrorMessage {
1249         fn read(r: &mut R) -> Result<Self, DecodeError> {
1250                 Ok(Self {
1251                         channel_id: Readable::read(r)?,
1252                         data: {
1253                                 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1254                                 let mut data = vec![];
1255                                 let data_len = r.read_to_end(&mut data)?;
1256                                 sz = cmp::min(data_len, sz);
1257                                 match String::from_utf8(data[..sz as usize].to_vec()) {
1258                                         Ok(s) => s,
1259                                         Err(_) => return Err(DecodeError::InvalidValue),
1260                                 }
1261                         }
1262                 })
1263         }
1264 }
1265
1266 impl Writeable for UnsignedNodeAnnouncement {
1267         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1268                 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1269                 self.features.write(w)?;
1270                 self.timestamp.write(w)?;
1271                 self.node_id.write(w)?;
1272                 w.write_all(&self.rgb)?;
1273                 self.alias.write(w)?;
1274
1275                 let mut addrs_to_encode = self.addresses.clone();
1276                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1277                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1278                 let mut addr_len = 0;
1279                 for addr in &addrs_to_encode {
1280                         addr_len += 1 + addr.len();
1281                 }
1282                 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1283                 for addr in addrs_to_encode {
1284                         addr.write(w)?;
1285                 }
1286                 w.write_all(&self.excess_address_data[..])?;
1287                 w.write_all(&self.excess_data[..])?;
1288                 Ok(())
1289         }
1290 }
1291
1292 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1293         fn read(r: &mut R) -> Result<Self, DecodeError> {
1294                 let features: GlobalFeatures = Readable::read(r)?;
1295                 if features.requires_unknown_bits() {
1296                         return Err(DecodeError::UnknownRequiredFeature);
1297                 }
1298                 let timestamp: u32 = Readable::read(r)?;
1299                 let node_id: PublicKey = Readable::read(r)?;
1300                 let mut rgb = [0; 3];
1301                 r.read_exact(&mut rgb)?;
1302                 let alias: [u8; 32] = Readable::read(r)?;
1303
1304                 let addr_len: u16 = Readable::read(r)?;
1305                 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1306                 let mut addr_readpos = 0;
1307                 let mut excess = false;
1308                 let mut excess_byte = 0;
1309                 loop {
1310                         if addr_len <= addr_readpos { break; }
1311                         match Readable::read(r) {
1312                                 Ok(Ok(addr)) => {
1313                                         match addr {
1314                                                 NetAddress::IPv4 { .. } => {
1315                                                         if addresses.len() > 0 {
1316                                                                 return Err(DecodeError::ExtraAddressesPerType);
1317                                                         }
1318                                                 },
1319                                                 NetAddress::IPv6 { .. } => {
1320                                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1321                                                                 return Err(DecodeError::ExtraAddressesPerType);
1322                                                         }
1323                                                 },
1324                                                 NetAddress::OnionV2 { .. } => {
1325                                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1326                                                                 return Err(DecodeError::ExtraAddressesPerType);
1327                                                         }
1328                                                 },
1329                                                 NetAddress::OnionV3 { .. } => {
1330                                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1331                                                                 return Err(DecodeError::ExtraAddressesPerType);
1332                                                         }
1333                                                 },
1334                                         }
1335                                         if addr_len < addr_readpos + 1 + addr.len() {
1336                                                 return Err(DecodeError::BadLengthDescriptor);
1337                                         }
1338                                         addr_readpos += (1 + addr.len()) as u16;
1339                                         addresses.push(addr);
1340                                 },
1341                                 Ok(Err(unknown_descriptor)) => {
1342                                         excess = true;
1343                                         excess_byte = unknown_descriptor;
1344                                         break;
1345                                 },
1346                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1347                                 Err(e) => return Err(e),
1348                         }
1349                 }
1350
1351                 let mut excess_data = vec![];
1352                 let excess_address_data = if addr_readpos < addr_len {
1353                         let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1354                         r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1355                         if excess {
1356                                 excess_address_data[0] = excess_byte;
1357                         }
1358                         excess_address_data
1359                 } else {
1360                         if excess {
1361                                 excess_data.push(excess_byte);
1362                         }
1363                         Vec::new()
1364                 };
1365                 r.read_to_end(&mut excess_data)?;
1366                 Ok(UnsignedNodeAnnouncement {
1367                         features,
1368                         timestamp,
1369                         node_id,
1370                         rgb,
1371                         alias,
1372                         addresses,
1373                         excess_address_data,
1374                         excess_data,
1375                 })
1376         }
1377 }
1378
1379 impl_writeable_len_match!(NodeAnnouncement, {
1380                 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1381                         64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1382         }, {
1383         signature,
1384         contents
1385 });
1386
1387 #[cfg(test)]
1388 mod tests {
1389         use hex;
1390         use ln::msgs;
1391         use ln::msgs::OptionalField;
1392         use util::ser::Writeable;
1393         use secp256k1::key::{PublicKey,SecretKey};
1394         use secp256k1::Secp256k1;
1395
1396         #[test]
1397         fn encoding_channel_reestablish_no_secret() {
1398                 let cr = msgs::ChannelReestablish {
1399                         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],
1400                         next_local_commitment_number: 3,
1401                         next_remote_commitment_number: 4,
1402                         data_loss_protect: OptionalField::Absent,
1403                 };
1404
1405                 let encoded_value = cr.encode();
1406                 assert_eq!(
1407                         encoded_value,
1408                         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]
1409                 );
1410         }
1411
1412         #[test]
1413         fn encoding_channel_reestablish_with_secret() {
1414                 let public_key = {
1415                         let secp_ctx = Secp256k1::new();
1416                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1417                 };
1418
1419                 let cr = msgs::ChannelReestablish {
1420                         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],
1421                         next_local_commitment_number: 3,
1422                         next_remote_commitment_number: 4,
1423                         data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1424                 };
1425
1426                 let encoded_value = cr.encode();
1427                 assert_eq!(
1428                         encoded_value,
1429                         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]
1430                 );
1431         }
1432 }