]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/wire.rs
Add counterparty_node_id & channel_capacity to ChannelClosed
[rust-lightning] / lightning / src / ln / wire.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Wire encoding/decoding for Lightning messages according to [BOLT #1], and for
11 //! custom message through the [`CustomMessageReader`] trait.
12 //!
13 //! [BOLT #1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
14
15 use crate::io;
16 use crate::ln::msgs;
17 use crate::util::ser::{Readable, Writeable, Writer};
18
19 /// Trait to be implemented by custom message (unrelated to the channel/gossip LN layers)
20 /// decoders.
21 pub trait CustomMessageReader {
22         /// The type of the message decoded by the implementation.
23         type CustomMessage: Type;
24         /// Decodes a custom message to `CustomMessageType`. If the given message type is known to the
25         /// implementation and the message could be decoded, must return `Ok(Some(message))`. If the
26         /// message type is unknown to the implementation, must return `Ok(None)`. If a decoding error
27         /// occur, must return `Err(DecodeError::X)` where `X` details the encountered error.
28         fn read<R: io::Read>(&self, message_type: u16, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
29 }
30
31 // TestEq is a dummy trait which requires PartialEq when built in testing, and otherwise is
32 // blanket-implemented for all types.
33
34 #[cfg(test)]
35 pub trait TestEq : PartialEq {}
36 #[cfg(test)]
37 impl<T: PartialEq> TestEq for T {}
38
39 #[cfg(not(test))]
40 pub(crate) trait TestEq {}
41 #[cfg(not(test))]
42 impl<T> TestEq for T {}
43
44
45 /// A Lightning message returned by [`read`] when decoding bytes received over the wire. Each
46 /// variant contains a message from [`msgs`] or otherwise the message type if unknown.
47 #[allow(missing_docs)]
48 #[derive(Debug)]
49 #[cfg_attr(test, derive(PartialEq))]
50 pub(crate) enum Message<T> where T: core::fmt::Debug + Type + TestEq {
51         Init(msgs::Init),
52         Error(msgs::ErrorMessage),
53         Warning(msgs::WarningMessage),
54         Ping(msgs::Ping),
55         Pong(msgs::Pong),
56         OpenChannel(msgs::OpenChannel),
57         OpenChannelV2(msgs::OpenChannelV2),
58         AcceptChannel(msgs::AcceptChannel),
59         AcceptChannelV2(msgs::AcceptChannelV2),
60         FundingCreated(msgs::FundingCreated),
61         FundingSigned(msgs::FundingSigned),
62         TxAddInput(msgs::TxAddInput),
63         TxAddOutput(msgs::TxAddOutput),
64         TxRemoveInput(msgs::TxRemoveInput),
65         TxRemoveOutput(msgs::TxRemoveOutput),
66         TxComplete(msgs::TxComplete),
67         TxSignatures(msgs::TxSignatures),
68         TxInitRbf(msgs::TxInitRbf),
69         TxAckRbf(msgs::TxAckRbf),
70         TxAbort(msgs::TxAbort),
71         ChannelReady(msgs::ChannelReady),
72         Shutdown(msgs::Shutdown),
73         ClosingSigned(msgs::ClosingSigned),
74         OnionMessage(msgs::OnionMessage),
75         UpdateAddHTLC(msgs::UpdateAddHTLC),
76         UpdateFulfillHTLC(msgs::UpdateFulfillHTLC),
77         UpdateFailHTLC(msgs::UpdateFailHTLC),
78         UpdateFailMalformedHTLC(msgs::UpdateFailMalformedHTLC),
79         CommitmentSigned(msgs::CommitmentSigned),
80         RevokeAndACK(msgs::RevokeAndACK),
81         UpdateFee(msgs::UpdateFee),
82         ChannelReestablish(msgs::ChannelReestablish),
83         AnnouncementSignatures(msgs::AnnouncementSignatures),
84         ChannelAnnouncement(msgs::ChannelAnnouncement),
85         NodeAnnouncement(msgs::NodeAnnouncement),
86         ChannelUpdate(msgs::ChannelUpdate),
87         QueryShortChannelIds(msgs::QueryShortChannelIds),
88         ReplyShortChannelIdsEnd(msgs::ReplyShortChannelIdsEnd),
89         QueryChannelRange(msgs::QueryChannelRange),
90         ReplyChannelRange(msgs::ReplyChannelRange),
91         GossipTimestampFilter(msgs::GossipTimestampFilter),
92         /// A message that could not be decoded because its type is unknown.
93         Unknown(u16),
94         /// A message that was produced by a [`CustomMessageReader`] and is to be handled by a
95         /// [`crate::ln::peer_handler::CustomMessageHandler`].
96         Custom(T),
97 }
98
99 impl<T> Writeable for Message<T> where T: core::fmt::Debug + Type + TestEq {
100         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
101                 match self {
102                         &Message::Init(ref msg) => msg.write(writer),
103                         &Message::Error(ref msg) => msg.write(writer),
104                         &Message::Warning(ref msg) => msg.write(writer),
105                         &Message::Ping(ref msg) => msg.write(writer),
106                         &Message::Pong(ref msg) => msg.write(writer),
107                         &Message::OpenChannel(ref msg) => msg.write(writer),
108                         &Message::OpenChannelV2(ref msg) => msg.write(writer),
109                         &Message::AcceptChannel(ref msg) => msg.write(writer),
110                         &Message::AcceptChannelV2(ref msg) => msg.write(writer),
111                         &Message::FundingCreated(ref msg) => msg.write(writer),
112                         &Message::FundingSigned(ref msg) => msg.write(writer),
113                         &Message::TxAddInput(ref msg) => msg.write(writer),
114                         &Message::TxAddOutput(ref msg) => msg.write(writer),
115                         &Message::TxRemoveInput(ref msg) => msg.write(writer),
116                         &Message::TxRemoveOutput(ref msg) => msg.write(writer),
117                         &Message::TxComplete(ref msg) => msg.write(writer),
118                         &Message::TxSignatures(ref msg) => msg.write(writer),
119                         &Message::TxInitRbf(ref msg) => msg.write(writer),
120                         &Message::TxAckRbf(ref msg) => msg.write(writer),
121                         &Message::TxAbort(ref msg) => msg.write(writer),
122                         &Message::ChannelReady(ref msg) => msg.write(writer),
123                         &Message::Shutdown(ref msg) => msg.write(writer),
124                         &Message::ClosingSigned(ref msg) => msg.write(writer),
125                         &Message::OnionMessage(ref msg) => msg.write(writer),
126                         &Message::UpdateAddHTLC(ref msg) => msg.write(writer),
127                         &Message::UpdateFulfillHTLC(ref msg) => msg.write(writer),
128                         &Message::UpdateFailHTLC(ref msg) => msg.write(writer),
129                         &Message::UpdateFailMalformedHTLC(ref msg) => msg.write(writer),
130                         &Message::CommitmentSigned(ref msg) => msg.write(writer),
131                         &Message::RevokeAndACK(ref msg) => msg.write(writer),
132                         &Message::UpdateFee(ref msg) => msg.write(writer),
133                         &Message::ChannelReestablish(ref msg) => msg.write(writer),
134                         &Message::AnnouncementSignatures(ref msg) => msg.write(writer),
135                         &Message::ChannelAnnouncement(ref msg) => msg.write(writer),
136                         &Message::NodeAnnouncement(ref msg) => msg.write(writer),
137                         &Message::ChannelUpdate(ref msg) => msg.write(writer),
138                         &Message::QueryShortChannelIds(ref msg) => msg.write(writer),
139                         &Message::ReplyShortChannelIdsEnd(ref msg) => msg.write(writer),
140                         &Message::QueryChannelRange(ref msg) => msg.write(writer),
141                         &Message::ReplyChannelRange(ref msg) => msg.write(writer),
142                         &Message::GossipTimestampFilter(ref msg) => msg.write(writer),
143                         &Message::Unknown(_) => { Ok(()) },
144                         &Message::Custom(ref msg) => msg.write(writer),
145                 }
146         }
147 }
148
149 impl<T> Type for Message<T> where T: core::fmt::Debug + Type + TestEq {
150         /// Returns the type that was used to decode the message payload.
151         fn type_id(&self) -> u16 {
152                 match self {
153                         &Message::Init(ref msg) => msg.type_id(),
154                         &Message::Error(ref msg) => msg.type_id(),
155                         &Message::Warning(ref msg) => msg.type_id(),
156                         &Message::Ping(ref msg) => msg.type_id(),
157                         &Message::Pong(ref msg) => msg.type_id(),
158                         &Message::OpenChannel(ref msg) => msg.type_id(),
159                         &Message::OpenChannelV2(ref msg) => msg.type_id(),
160                         &Message::AcceptChannel(ref msg) => msg.type_id(),
161                         &Message::AcceptChannelV2(ref msg) => msg.type_id(),
162                         &Message::FundingCreated(ref msg) => msg.type_id(),
163                         &Message::FundingSigned(ref msg) => msg.type_id(),
164                         &Message::TxAddInput(ref msg) => msg.type_id(),
165                         &Message::TxAddOutput(ref msg) => msg.type_id(),
166                         &Message::TxRemoveInput(ref msg) => msg.type_id(),
167                         &Message::TxRemoveOutput(ref msg) => msg.type_id(),
168                         &Message::TxComplete(ref msg) => msg.type_id(),
169                         &Message::TxSignatures(ref msg) => msg.type_id(),
170                         &Message::TxInitRbf(ref msg) => msg.type_id(),
171                         &Message::TxAckRbf(ref msg) => msg.type_id(),
172                         &Message::TxAbort(ref msg) => msg.type_id(),
173                         &Message::ChannelReady(ref msg) => msg.type_id(),
174                         &Message::Shutdown(ref msg) => msg.type_id(),
175                         &Message::ClosingSigned(ref msg) => msg.type_id(),
176                         &Message::OnionMessage(ref msg) => msg.type_id(),
177                         &Message::UpdateAddHTLC(ref msg) => msg.type_id(),
178                         &Message::UpdateFulfillHTLC(ref msg) => msg.type_id(),
179                         &Message::UpdateFailHTLC(ref msg) => msg.type_id(),
180                         &Message::UpdateFailMalformedHTLC(ref msg) => msg.type_id(),
181                         &Message::CommitmentSigned(ref msg) => msg.type_id(),
182                         &Message::RevokeAndACK(ref msg) => msg.type_id(),
183                         &Message::UpdateFee(ref msg) => msg.type_id(),
184                         &Message::ChannelReestablish(ref msg) => msg.type_id(),
185                         &Message::AnnouncementSignatures(ref msg) => msg.type_id(),
186                         &Message::ChannelAnnouncement(ref msg) => msg.type_id(),
187                         &Message::NodeAnnouncement(ref msg) => msg.type_id(),
188                         &Message::ChannelUpdate(ref msg) => msg.type_id(),
189                         &Message::QueryShortChannelIds(ref msg) => msg.type_id(),
190                         &Message::ReplyShortChannelIdsEnd(ref msg) => msg.type_id(),
191                         &Message::QueryChannelRange(ref msg) => msg.type_id(),
192                         &Message::ReplyChannelRange(ref msg) => msg.type_id(),
193                         &Message::GossipTimestampFilter(ref msg) => msg.type_id(),
194                         &Message::Unknown(type_id) => type_id,
195                         &Message::Custom(ref msg) => msg.type_id(),
196                 }
197         }
198 }
199
200 impl<T> Message<T> where T: core::fmt::Debug + Type + TestEq {
201         /// Returns whether the message's type is even, indicating both endpoints must support it.
202         pub fn is_even(&self) -> bool {
203                 (self.type_id() & 1) == 0
204         }
205 }
206
207 /// Reads a message from the data buffer consisting of a 2-byte big-endian type and a
208 /// variable-length payload conforming to the type.
209 ///
210 /// # Errors
211 ///
212 /// Returns an error if the message payload could not be decoded as the specified type.
213 pub(crate) fn read<R: io::Read, T, H: core::ops::Deref>(buffer: &mut R, custom_reader: H)
214 -> Result<Message<T>, (msgs::DecodeError, Option<u16>)> where
215         T: core::fmt::Debug + Type + Writeable,
216         H::Target: CustomMessageReader<CustomMessage = T>,
217 {
218         let message_type = <u16 as Readable>::read(buffer).map_err(|e| (e, None))?;
219         do_read(buffer, message_type, custom_reader).map_err(|e| (e, Some(message_type)))
220 }
221
222 fn do_read<R: io::Read, T, H: core::ops::Deref>(buffer: &mut R, message_type: u16, custom_reader: H)
223 -> Result<Message<T>, msgs::DecodeError> where
224         T: core::fmt::Debug + Type + Writeable,
225         H::Target: CustomMessageReader<CustomMessage = T>,
226 {
227         match message_type {
228                 msgs::Init::TYPE => {
229                         Ok(Message::Init(Readable::read(buffer)?))
230                 },
231                 msgs::ErrorMessage::TYPE => {
232                         Ok(Message::Error(Readable::read(buffer)?))
233                 },
234                 msgs::WarningMessage::TYPE => {
235                         Ok(Message::Warning(Readable::read(buffer)?))
236                 },
237                 msgs::Ping::TYPE => {
238                         Ok(Message::Ping(Readable::read(buffer)?))
239                 },
240                 msgs::Pong::TYPE => {
241                         Ok(Message::Pong(Readable::read(buffer)?))
242                 },
243                 msgs::OpenChannel::TYPE => {
244                         Ok(Message::OpenChannel(Readable::read(buffer)?))
245                 },
246                 msgs::OpenChannelV2::TYPE => {
247                         Ok(Message::OpenChannelV2(Readable::read(buffer)?))
248                 },
249                 msgs::AcceptChannel::TYPE => {
250                         Ok(Message::AcceptChannel(Readable::read(buffer)?))
251                 },
252                 msgs::AcceptChannelV2::TYPE => {
253                         Ok(Message::AcceptChannelV2(Readable::read(buffer)?))
254                 },
255                 msgs::FundingCreated::TYPE => {
256                         Ok(Message::FundingCreated(Readable::read(buffer)?))
257                 },
258                 msgs::FundingSigned::TYPE => {
259                         Ok(Message::FundingSigned(Readable::read(buffer)?))
260                 },
261                 msgs::TxAddInput::TYPE => {
262                         Ok(Message::TxAddInput(Readable::read(buffer)?))
263                 },
264                 msgs::TxAddOutput::TYPE => {
265                         Ok(Message::TxAddOutput(Readable::read(buffer)?))
266                 },
267                 msgs::TxRemoveInput::TYPE => {
268                         Ok(Message::TxRemoveInput(Readable::read(buffer)?))
269                 },
270                 msgs::TxRemoveOutput::TYPE => {
271                         Ok(Message::TxRemoveOutput(Readable::read(buffer)?))
272                 },
273                 msgs::TxComplete::TYPE => {
274                         Ok(Message::TxComplete(Readable::read(buffer)?))
275                 },
276                 msgs::TxSignatures::TYPE => {
277                         Ok(Message::TxSignatures(Readable::read(buffer)?))
278                 },
279                 msgs::TxInitRbf::TYPE => {
280                         Ok(Message::TxInitRbf(Readable::read(buffer)?))
281                 },
282                 msgs::TxAckRbf::TYPE => {
283                         Ok(Message::TxAckRbf(Readable::read(buffer)?))
284                 },
285                 msgs::TxAbort::TYPE => {
286                         Ok(Message::TxAbort(Readable::read(buffer)?))
287                 },
288                 msgs::ChannelReady::TYPE => {
289                         Ok(Message::ChannelReady(Readable::read(buffer)?))
290                 },
291                 msgs::Shutdown::TYPE => {
292                         Ok(Message::Shutdown(Readable::read(buffer)?))
293                 },
294                 msgs::ClosingSigned::TYPE => {
295                         Ok(Message::ClosingSigned(Readable::read(buffer)?))
296                 },
297                 msgs::OnionMessage::TYPE => {
298                         Ok(Message::OnionMessage(Readable::read(buffer)?))
299                 },
300                 msgs::UpdateAddHTLC::TYPE => {
301                         Ok(Message::UpdateAddHTLC(Readable::read(buffer)?))
302                 },
303                 msgs::UpdateFulfillHTLC::TYPE => {
304                         Ok(Message::UpdateFulfillHTLC(Readable::read(buffer)?))
305                 },
306                 msgs::UpdateFailHTLC::TYPE => {
307                         Ok(Message::UpdateFailHTLC(Readable::read(buffer)?))
308                 },
309                 msgs::UpdateFailMalformedHTLC::TYPE => {
310                         Ok(Message::UpdateFailMalformedHTLC(Readable::read(buffer)?))
311                 },
312                 msgs::CommitmentSigned::TYPE => {
313                         Ok(Message::CommitmentSigned(Readable::read(buffer)?))
314                 },
315                 msgs::RevokeAndACK::TYPE => {
316                         Ok(Message::RevokeAndACK(Readable::read(buffer)?))
317                 },
318                 msgs::UpdateFee::TYPE => {
319                         Ok(Message::UpdateFee(Readable::read(buffer)?))
320                 },
321                 msgs::ChannelReestablish::TYPE => {
322                         Ok(Message::ChannelReestablish(Readable::read(buffer)?))
323                 },
324                 msgs::AnnouncementSignatures::TYPE => {
325                         Ok(Message::AnnouncementSignatures(Readable::read(buffer)?))
326                 },
327                 msgs::ChannelAnnouncement::TYPE => {
328                         Ok(Message::ChannelAnnouncement(Readable::read(buffer)?))
329                 },
330                 msgs::NodeAnnouncement::TYPE => {
331                         Ok(Message::NodeAnnouncement(Readable::read(buffer)?))
332                 },
333                 msgs::ChannelUpdate::TYPE => {
334                         Ok(Message::ChannelUpdate(Readable::read(buffer)?))
335                 },
336                 msgs::QueryShortChannelIds::TYPE => {
337                         Ok(Message::QueryShortChannelIds(Readable::read(buffer)?))
338                 },
339                 msgs::ReplyShortChannelIdsEnd::TYPE => {
340                         Ok(Message::ReplyShortChannelIdsEnd(Readable::read(buffer)?))
341                 },
342                 msgs::QueryChannelRange::TYPE => {
343                         Ok(Message::QueryChannelRange(Readable::read(buffer)?))
344                 },
345                 msgs::ReplyChannelRange::TYPE => {
346                         Ok(Message::ReplyChannelRange(Readable::read(buffer)?))
347                 }
348                 msgs::GossipTimestampFilter::TYPE => {
349                         Ok(Message::GossipTimestampFilter(Readable::read(buffer)?))
350                 },
351                 _ => {
352                         if let Some(custom) = custom_reader.read(message_type, buffer)? {
353                                 Ok(Message::Custom(custom))
354                         } else {
355                                 Ok(Message::Unknown(message_type))
356                         }
357                 },
358         }
359 }
360
361 /// Writes a message to the data buffer encoded as a 2-byte big-endian type and a variable-length
362 /// payload.
363 ///
364 /// # Errors
365 ///
366 /// Returns an I/O error if the write could not be completed.
367 pub(crate) fn write<M: Type + Writeable, W: Writer>(message: &M, buffer: &mut W) -> Result<(), io::Error> {
368         message.type_id().write(buffer)?;
369         message.write(buffer)
370 }
371
372 mod encode {
373         /// Defines a constant type identifier for reading messages from the wire.
374         pub trait Encode {
375                 /// The type identifying the message payload.
376                 const TYPE: u16;
377         }
378 }
379
380 pub(crate) use self::encode::Encode;
381
382 #[cfg(not(test))]
383 /// Defines a type identifier for sending messages over the wire.
384 ///
385 /// Messages implementing this trait specify a type and must be [`Writeable`].
386 pub trait Type: core::fmt::Debug + Writeable {
387         /// Returns the type identifying the message payload.
388         fn type_id(&self) -> u16;
389 }
390
391 #[cfg(test)]
392 pub trait Type: core::fmt::Debug + Writeable + PartialEq {
393         fn type_id(&self) -> u16;
394 }
395
396 #[cfg(any(feature = "_test_utils", fuzzing, test))]
397 impl Type for () {
398         fn type_id(&self) -> u16 { unreachable!(); }
399 }
400
401 #[cfg(test)]
402 impl<T: core::fmt::Debug + Writeable + PartialEq> Type for T where T: Encode {
403         fn type_id(&self) -> u16 { T::TYPE }
404 }
405
406 #[cfg(not(test))]
407 impl<T: core::fmt::Debug + Writeable> Type for T where T: Encode {
408         fn type_id(&self) -> u16 { T::TYPE }
409 }
410
411 impl Encode for msgs::Init {
412         const TYPE: u16 = 16;
413 }
414
415 impl Encode for msgs::ErrorMessage {
416         const TYPE: u16 = 17;
417 }
418
419 impl Encode for msgs::WarningMessage {
420         const TYPE: u16 = 1;
421 }
422
423 impl Encode for msgs::Ping {
424         const TYPE: u16 = 18;
425 }
426
427 impl Encode for msgs::Pong {
428         const TYPE: u16 = 19;
429 }
430
431 impl Encode for msgs::OpenChannel {
432         const TYPE: u16 = 32;
433 }
434
435 impl Encode for msgs::AcceptChannel {
436         const TYPE: u16 = 33;
437 }
438
439 impl Encode for msgs::FundingCreated {
440         const TYPE: u16 = 34;
441 }
442
443 impl Encode for msgs::FundingSigned {
444         const TYPE: u16 = 35;
445 }
446
447 impl Encode for msgs::ChannelReady {
448         const TYPE: u16 = 36;
449 }
450
451 impl Encode for msgs::Shutdown {
452         const TYPE: u16 = 38;
453 }
454
455 impl Encode for msgs::ClosingSigned {
456         const TYPE: u16 = 39;
457 }
458
459 impl Encode for msgs::OpenChannelV2 {
460         const TYPE: u16 = 64;
461 }
462
463 impl Encode for msgs::AcceptChannelV2 {
464         const TYPE: u16 = 65;
465 }
466
467 impl Encode for msgs::TxAddInput {
468         const TYPE: u16 = 66;
469 }
470
471 impl Encode for msgs::TxAddOutput {
472         const TYPE: u16 = 67;
473 }
474
475 impl Encode for msgs::TxRemoveInput {
476         const TYPE: u16 = 68;
477 }
478
479 impl Encode for msgs::TxRemoveOutput {
480         const TYPE: u16 = 69;
481 }
482
483 impl Encode for msgs::TxComplete {
484         const TYPE: u16 = 70;
485 }
486
487 impl Encode for msgs::TxSignatures {
488         const TYPE: u16 = 71;
489 }
490
491 impl Encode for msgs::TxInitRbf {
492         const TYPE: u16 = 72;
493 }
494
495 impl Encode for msgs::TxAckRbf {
496         const TYPE: u16 = 73;
497 }
498
499 impl Encode for msgs::TxAbort {
500         const TYPE: u16 = 74;
501 }
502
503 impl Encode for msgs::OnionMessage {
504         const TYPE: u16 = 513;
505 }
506
507 impl Encode for msgs::UpdateAddHTLC {
508         const TYPE: u16 = 128;
509 }
510
511 impl Encode for msgs::UpdateFulfillHTLC {
512         const TYPE: u16 = 130;
513 }
514
515 impl Encode for msgs::UpdateFailHTLC {
516         const TYPE: u16 = 131;
517 }
518
519 impl Encode for msgs::UpdateFailMalformedHTLC {
520         const TYPE: u16 = 135;
521 }
522
523 impl Encode for msgs::CommitmentSigned {
524         const TYPE: u16 = 132;
525 }
526
527 impl Encode for msgs::RevokeAndACK {
528         const TYPE: u16 = 133;
529 }
530
531 impl Encode for msgs::UpdateFee {
532         const TYPE: u16 = 134;
533 }
534
535 impl Encode for msgs::ChannelReestablish {
536         const TYPE: u16 = 136;
537 }
538
539 impl Encode for msgs::AnnouncementSignatures {
540         const TYPE: u16 = 259;
541 }
542
543 impl Encode for msgs::ChannelAnnouncement {
544         const TYPE: u16 = 256;
545 }
546
547 impl Encode for msgs::NodeAnnouncement {
548         const TYPE: u16 = 257;
549 }
550
551 impl Encode for msgs::ChannelUpdate {
552         const TYPE: u16 = 258;
553 }
554
555 impl Encode for msgs::QueryShortChannelIds {
556         const TYPE: u16 = 261;
557 }
558
559 impl Encode for msgs::ReplyShortChannelIdsEnd {
560         const TYPE: u16 = 262;
561 }
562
563 impl Encode for msgs::QueryChannelRange {
564         const TYPE: u16 = 263;
565 }
566
567 impl Encode for msgs::ReplyChannelRange {
568         const TYPE: u16 = 264;
569 }
570
571 impl Encode for msgs::GossipTimestampFilter {
572         const TYPE: u16 = 265;
573 }
574
575 #[cfg(test)]
576 mod tests {
577         use super::*;
578         use crate::prelude::*;
579         use core::convert::TryInto;
580         use crate::ln::peer_handler::IgnoringMessageHandler;
581
582         // Big-endian wire encoding of Pong message (type = 19, byteslen = 2).
583         const ENCODED_PONG: [u8; 6] = [0u8, 19u8, 0u8, 2u8, 0u8, 0u8];
584
585         #[test]
586         fn read_empty_buffer() {
587                 let buffer = [];
588                 let mut reader = io::Cursor::new(buffer);
589                 assert!(read(&mut reader, &IgnoringMessageHandler{}).is_err());
590         }
591
592         #[test]
593         fn read_incomplete_type() {
594                 let buffer = &ENCODED_PONG[..1];
595                 let mut reader = io::Cursor::new(buffer);
596                 assert!(read(&mut reader, &IgnoringMessageHandler{}).is_err());
597         }
598
599         #[test]
600         fn read_empty_payload() {
601                 let buffer = &ENCODED_PONG[..2];
602                 let mut reader = io::Cursor::new(buffer);
603                 assert!(read(&mut reader, &IgnoringMessageHandler{}).is_err());
604         }
605
606         #[test]
607         fn read_invalid_message() {
608                 let buffer = &ENCODED_PONG[..4];
609                 let mut reader = io::Cursor::new(buffer);
610                 assert!(read(&mut reader, &IgnoringMessageHandler{}).is_err());
611         }
612
613         #[test]
614         fn read_known_message() {
615                 let buffer = &ENCODED_PONG[..];
616                 let mut reader = io::Cursor::new(buffer);
617                 let message = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
618                 match message {
619                         Message::Pong(_) => (),
620                         _ => panic!("Expected pong message; found message type: {}", message.type_id()),
621                 }
622         }
623
624         #[test]
625         fn read_unknown_message() {
626                 let buffer = &::core::u16::MAX.to_be_bytes();
627                 let mut reader = io::Cursor::new(buffer);
628                 let message = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
629                 match message {
630                         Message::Unknown(::core::u16::MAX) => (),
631                         _ => panic!("Expected message type {}; found: {}", ::core::u16::MAX, message.type_id()),
632                 }
633         }
634
635         #[test]
636         fn write_message_with_type() {
637                 let message = msgs::Pong { byteslen: 2u16 };
638                 let mut buffer = Vec::new();
639                 assert!(write(&message, &mut buffer).is_ok());
640
641                 let type_length = ::core::mem::size_of::<u16>();
642                 let (type_bytes, payload_bytes) = buffer.split_at(type_length);
643                 assert_eq!(u16::from_be_bytes(type_bytes.try_into().unwrap()), msgs::Pong::TYPE);
644                 assert_eq!(payload_bytes, &ENCODED_PONG[type_length..]);
645         }
646
647         #[test]
648         fn read_message_encoded_with_write() {
649                 let message = msgs::Pong { byteslen: 2u16 };
650                 let mut buffer = Vec::new();
651                 assert!(write(&message, &mut buffer).is_ok());
652
653                 let mut reader = io::Cursor::new(buffer);
654                 let decoded_message = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
655                 match decoded_message {
656                         Message::Pong(msgs::Pong { byteslen: 2u16 }) => (),
657                         Message::Pong(msgs::Pong { byteslen }) => {
658                                 panic!("Expected byteslen {}; found: {}", message.byteslen, byteslen);
659                         },
660                         _ => panic!("Expected pong message; found message type: {}", decoded_message.type_id()),
661                 }
662         }
663
664         #[test]
665         fn is_even_message_type() {
666                 let message = Message::<()>::Unknown(42);
667                 assert!(message.is_even());
668         }
669
670         #[test]
671         fn is_odd_message_type() {
672                 let message = Message::<()>::Unknown(43);
673                 assert!(!message.is_even());
674         }
675
676         #[test]
677         fn read_lnd_init_msg() {
678                 // Taken from lnd v0.9.0-beta.
679                 let buffer = vec![0, 16, 0, 2, 34, 0, 0, 3, 2, 162, 161];
680                 check_init_msg(buffer, false);
681         }
682
683         #[test]
684         fn read_clightning_init_msg() {
685                 // Taken from c-lightning v0.8.0.
686                 let buffer = vec![0, 16, 0, 2, 34, 0, 0, 3, 2, 170, 162, 1, 32, 6, 34, 110, 70, 17, 26, 11, 89, 202, 175, 18, 96, 67, 235, 91, 191, 40, 195, 79, 58, 94, 51, 42, 31, 199, 178, 183, 60, 241, 136, 145, 15];
687                 check_init_msg(buffer, true);
688         }
689
690         fn check_init_msg(buffer: Vec<u8>, expect_unknown: bool) {
691                 let mut reader = io::Cursor::new(buffer);
692                 let decoded_msg = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
693                 match decoded_msg {
694                         Message::Init(msgs::Init { features, .. }) => {
695                                 assert!(features.supports_variable_length_onion());
696                                 assert!(features.supports_upfront_shutdown_script());
697                                 assert!(features.supports_gossip_queries());
698                                 assert_eq!(expect_unknown, features.supports_unknown_bits());
699                                 assert!(!features.requires_unknown_bits());
700                                 assert!(!features.initial_routing_sync());
701                         },
702                         _ => panic!("Expected init message, found message type: {}", decoded_msg.type_id())
703                 }
704         }
705
706         #[test]
707         fn read_lnd_node_announcement() {
708                 // Taken from lnd v0.9.0-beta.
709                 let buffer = vec![1, 1, 91, 164, 146, 213, 213, 165, 21, 227, 102, 33, 105, 179, 214, 21, 221, 175, 228, 93, 57, 177, 191, 127, 107, 229, 31, 50, 21, 81, 179, 71, 39, 18, 35, 2, 89, 224, 110, 123, 66, 39, 148, 246, 177, 85, 12, 19, 70, 226, 173, 132, 156, 26, 122, 146, 71, 213, 247, 48, 93, 190, 185, 177, 12, 172, 0, 3, 2, 162, 161, 94, 103, 195, 37, 2, 37, 242, 97, 140, 2, 111, 69, 85, 39, 118, 30, 221, 99, 254, 120, 49, 103, 22, 170, 227, 111, 172, 164, 160, 49, 68, 138, 116, 16, 22, 206, 107, 51, 153, 255, 97, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 172, 21, 0, 2, 38, 7];
710                 let mut reader = io::Cursor::new(buffer);
711                 let decoded_msg = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
712                 match decoded_msg {
713                         Message::NodeAnnouncement(msgs::NodeAnnouncement { contents: msgs::UnsignedNodeAnnouncement { features, ..}, ..}) => {
714                                 assert!(features.supports_variable_length_onion());
715                                 assert!(features.supports_upfront_shutdown_script());
716                                 assert!(features.supports_gossip_queries());
717                                 assert!(!features.requires_unknown_bits());
718                         },
719                         _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
720                 }
721         }
722
723         #[test]
724         fn read_lnd_chan_announcement() {
725                 // Taken from lnd v0.9.0-beta.
726                 let buffer = vec![1, 0, 82, 238, 153, 33, 128, 87, 215, 2, 28, 241, 140, 250, 98, 255, 56, 5, 79, 240, 214, 231, 172, 35, 240, 171, 44, 9, 78, 91, 8, 193, 102, 5, 17, 178, 142, 106, 180, 183, 46, 38, 217, 212, 25, 236, 69, 47, 92, 217, 181, 221, 161, 205, 121, 201, 99, 38, 158, 216, 186, 193, 230, 86, 222, 6, 206, 67, 22, 255, 137, 212, 141, 161, 62, 134, 76, 48, 241, 54, 50, 167, 187, 247, 73, 27, 74, 1, 129, 185, 197, 153, 38, 90, 255, 138, 39, 161, 102, 172, 213, 74, 107, 88, 150, 90, 0, 49, 104, 7, 182, 184, 194, 219, 181, 172, 8, 245, 65, 226, 19, 228, 101, 145, 25, 159, 52, 31, 58, 93, 53, 59, 218, 91, 37, 84, 103, 17, 74, 133, 33, 35, 2, 203, 101, 73, 19, 94, 175, 122, 46, 224, 47, 168, 128, 128, 25, 26, 25, 214, 52, 247, 43, 241, 117, 52, 206, 94, 135, 156, 52, 164, 143, 234, 58, 185, 50, 185, 140, 198, 174, 71, 65, 18, 105, 70, 131, 172, 137, 0, 164, 51, 215, 143, 117, 119, 217, 241, 197, 177, 227, 227, 170, 199, 114, 7, 218, 12, 107, 30, 191, 236, 203, 21, 61, 242, 48, 192, 90, 233, 200, 199, 111, 162, 68, 234, 54, 219, 1, 233, 66, 5, 82, 74, 84, 211, 95, 199, 245, 202, 89, 223, 102, 124, 62, 166, 253, 253, 90, 180, 118, 21, 61, 110, 37, 5, 96, 167, 0, 0, 6, 34, 110, 70, 17, 26, 11, 89, 202, 175, 18, 96, 67, 235, 91, 191, 40, 195, 79, 58, 94, 51, 42, 31, 199, 178, 183, 60, 241, 136, 145, 15, 0, 2, 65, 0, 0, 1, 0, 0, 2, 37, 242, 97, 140, 2, 111, 69, 85, 39, 118, 30, 221, 99, 254, 120, 49, 103, 22, 170, 227, 111, 172, 164, 160, 49, 68, 138, 116, 16, 22, 206, 107, 3, 54, 61, 144, 88, 171, 247, 136, 208, 99, 9, 135, 37, 201, 178, 253, 136, 0, 185, 235, 68, 160, 106, 110, 12, 46, 21, 125, 204, 18, 75, 234, 16, 3, 42, 171, 28, 52, 224, 11, 30, 30, 253, 156, 148, 175, 203, 121, 250, 111, 122, 195, 84, 122, 77, 183, 56, 135, 101, 88, 41, 60, 191, 99, 232, 85, 2, 36, 17, 156, 11, 8, 12, 189, 177, 68, 88, 28, 15, 207, 21, 179, 151, 56, 226, 158, 148, 3, 120, 113, 177, 243, 184, 17, 173, 37, 46, 222, 16];
727                 let mut reader = io::Cursor::new(buffer);
728                 let decoded_msg = read(&mut reader, &IgnoringMessageHandler{}).unwrap();
729                 match decoded_msg {
730                         Message::ChannelAnnouncement(msgs::ChannelAnnouncement { contents: msgs::UnsignedChannelAnnouncement { features, ..}, ..}) => {
731                                 assert!(!features.requires_unknown_bits());
732                         },
733                         _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
734                 }
735         }
736
737         #[derive(Eq, PartialEq, Debug)]
738         struct TestCustomMessage {}
739
740         const CUSTOM_MESSAGE_TYPE : u16 = 9000;
741
742         impl Type for TestCustomMessage {
743                 fn type_id(&self) -> u16 {
744                         CUSTOM_MESSAGE_TYPE
745                 }
746         }
747
748         impl Writeable for TestCustomMessage {
749                 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
750                         Ok(())
751                 }
752         }
753
754         struct TestCustomMessageReader {}
755
756         impl CustomMessageReader for TestCustomMessageReader {
757                 type CustomMessage = TestCustomMessage;
758                 fn read<R: io::Read>(
759                         &self,
760                         message_type: u16,
761                         _: &mut R
762                 ) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
763                         if message_type == CUSTOM_MESSAGE_TYPE {
764                                 return Ok(Some(TestCustomMessage{}));
765                         }
766
767                         Ok(None)
768                 }
769         }
770
771         #[test]
772         fn read_custom_message() {
773                 let buffer = vec![35, 40];
774                 let mut reader = io::Cursor::new(buffer);
775                 let decoded_msg = read(&mut reader, &TestCustomMessageReader{}).unwrap();
776                 match decoded_msg {
777                         Message::Custom(custom) => {
778                                 assert_eq!(custom.type_id(), CUSTOM_MESSAGE_TYPE);
779                                 assert_eq!(custom, TestCustomMessage {});
780                         },
781                         _ => panic!("Expected custom message, found message type: {}", decoded_msg.type_id()),
782                 }
783         }
784
785         #[test]
786         fn read_with_custom_reader_unknown_message_type() {
787                 let buffer = vec![35, 42];
788                 let mut reader = io::Cursor::new(buffer);
789                 let decoded_msg = read(&mut reader, &TestCustomMessageReader{}).unwrap();
790                 match decoded_msg {
791                         Message::Unknown(_) => {},
792                         _ => panic!("Expected unknown message, found message type: {}", decoded_msg.type_id()),
793                 }
794         }
795
796         #[test]
797         fn custom_reader_unknown_message_type() {
798                 let buffer = Vec::new();
799                 let mut reader = io::Cursor::new(buffer);
800                 let res = TestCustomMessageReader{}.read(CUSTOM_MESSAGE_TYPE + 1, &mut reader).unwrap();
801                 assert!(res.is_none());
802         }
803 }