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