1 // This file is Copyright its original authors, visible in version control
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
10 //! Wire encoding/decoding for Lightning messages according to [BOLT #1], and for
11 //! custom message through the [`CustomMessageReader`] trait.
13 //! [BOLT #1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
17 use crate::util::ser::{Readable, Writeable, Writer};
19 /// Trait to be implemented by custom message (unrelated to the channel/gossip LN layers)
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>;
31 // TestEq is a dummy trait which requires PartialEq when built in testing, and otherwise is
32 // blanket-implemented for all types.
35 pub trait TestEq : PartialEq {}
37 impl<T: PartialEq> TestEq for T {}
40 pub(crate) trait TestEq {}
42 impl<T> TestEq for T {}
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)]
49 #[cfg_attr(test, derive(PartialEq))]
50 pub(crate) enum Message<T> where T: core::fmt::Debug + Type + TestEq {
52 Error(msgs::ErrorMessage),
53 Warning(msgs::WarningMessage),
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.
94 /// A message that was produced by a [`CustomMessageReader`] and is to be handled by a
95 /// [`crate::ln::peer_handler::CustomMessageHandler`].
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> {
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),
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 {
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(),
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
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.
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>,
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)))
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>,
228 msgs::Init::TYPE => {
229 Ok(Message::Init(Readable::read(buffer)?))
231 msgs::ErrorMessage::TYPE => {
232 Ok(Message::Error(Readable::read(buffer)?))
234 msgs::WarningMessage::TYPE => {
235 Ok(Message::Warning(Readable::read(buffer)?))
237 msgs::Ping::TYPE => {
238 Ok(Message::Ping(Readable::read(buffer)?))
240 msgs::Pong::TYPE => {
241 Ok(Message::Pong(Readable::read(buffer)?))
243 msgs::OpenChannel::TYPE => {
244 Ok(Message::OpenChannel(Readable::read(buffer)?))
246 msgs::OpenChannelV2::TYPE => {
247 Ok(Message::OpenChannelV2(Readable::read(buffer)?))
249 msgs::AcceptChannel::TYPE => {
250 Ok(Message::AcceptChannel(Readable::read(buffer)?))
252 msgs::AcceptChannelV2::TYPE => {
253 Ok(Message::AcceptChannelV2(Readable::read(buffer)?))
255 msgs::FundingCreated::TYPE => {
256 Ok(Message::FundingCreated(Readable::read(buffer)?))
258 msgs::FundingSigned::TYPE => {
259 Ok(Message::FundingSigned(Readable::read(buffer)?))
261 msgs::TxAddInput::TYPE => {
262 Ok(Message::TxAddInput(Readable::read(buffer)?))
264 msgs::TxAddOutput::TYPE => {
265 Ok(Message::TxAddOutput(Readable::read(buffer)?))
267 msgs::TxRemoveInput::TYPE => {
268 Ok(Message::TxRemoveInput(Readable::read(buffer)?))
270 msgs::TxRemoveOutput::TYPE => {
271 Ok(Message::TxRemoveOutput(Readable::read(buffer)?))
273 msgs::TxComplete::TYPE => {
274 Ok(Message::TxComplete(Readable::read(buffer)?))
276 msgs::TxSignatures::TYPE => {
277 Ok(Message::TxSignatures(Readable::read(buffer)?))
279 msgs::TxInitRbf::TYPE => {
280 Ok(Message::TxInitRbf(Readable::read(buffer)?))
282 msgs::TxAckRbf::TYPE => {
283 Ok(Message::TxAckRbf(Readable::read(buffer)?))
285 msgs::TxAbort::TYPE => {
286 Ok(Message::TxAbort(Readable::read(buffer)?))
288 msgs::ChannelReady::TYPE => {
289 Ok(Message::ChannelReady(Readable::read(buffer)?))
291 msgs::Shutdown::TYPE => {
292 Ok(Message::Shutdown(Readable::read(buffer)?))
294 msgs::ClosingSigned::TYPE => {
295 Ok(Message::ClosingSigned(Readable::read(buffer)?))
297 msgs::OnionMessage::TYPE => {
298 Ok(Message::OnionMessage(Readable::read(buffer)?))
300 msgs::UpdateAddHTLC::TYPE => {
301 Ok(Message::UpdateAddHTLC(Readable::read(buffer)?))
303 msgs::UpdateFulfillHTLC::TYPE => {
304 Ok(Message::UpdateFulfillHTLC(Readable::read(buffer)?))
306 msgs::UpdateFailHTLC::TYPE => {
307 Ok(Message::UpdateFailHTLC(Readable::read(buffer)?))
309 msgs::UpdateFailMalformedHTLC::TYPE => {
310 Ok(Message::UpdateFailMalformedHTLC(Readable::read(buffer)?))
312 msgs::CommitmentSigned::TYPE => {
313 Ok(Message::CommitmentSigned(Readable::read(buffer)?))
315 msgs::RevokeAndACK::TYPE => {
316 Ok(Message::RevokeAndACK(Readable::read(buffer)?))
318 msgs::UpdateFee::TYPE => {
319 Ok(Message::UpdateFee(Readable::read(buffer)?))
321 msgs::ChannelReestablish::TYPE => {
322 Ok(Message::ChannelReestablish(Readable::read(buffer)?))
324 msgs::AnnouncementSignatures::TYPE => {
325 Ok(Message::AnnouncementSignatures(Readable::read(buffer)?))
327 msgs::ChannelAnnouncement::TYPE => {
328 Ok(Message::ChannelAnnouncement(Readable::read(buffer)?))
330 msgs::NodeAnnouncement::TYPE => {
331 Ok(Message::NodeAnnouncement(Readable::read(buffer)?))
333 msgs::ChannelUpdate::TYPE => {
334 Ok(Message::ChannelUpdate(Readable::read(buffer)?))
336 msgs::QueryShortChannelIds::TYPE => {
337 Ok(Message::QueryShortChannelIds(Readable::read(buffer)?))
339 msgs::ReplyShortChannelIdsEnd::TYPE => {
340 Ok(Message::ReplyShortChannelIdsEnd(Readable::read(buffer)?))
342 msgs::QueryChannelRange::TYPE => {
343 Ok(Message::QueryChannelRange(Readable::read(buffer)?))
345 msgs::ReplyChannelRange::TYPE => {
346 Ok(Message::ReplyChannelRange(Readable::read(buffer)?))
348 msgs::GossipTimestampFilter::TYPE => {
349 Ok(Message::GossipTimestampFilter(Readable::read(buffer)?))
352 if let Some(custom) = custom_reader.read(message_type, buffer)? {
353 Ok(Message::Custom(custom))
355 Ok(Message::Unknown(message_type))
361 /// Writes a message to the data buffer encoded as a 2-byte big-endian type and a variable-length
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)
373 /// Defines a constant type identifier for reading messages from the wire.
375 /// The type identifying the message payload.
380 pub(crate) use self::encode::Encode;
383 /// Defines a type identifier for sending messages over the wire.
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;
392 pub trait Type: core::fmt::Debug + Writeable + PartialEq {
393 fn type_id(&self) -> u16;
396 #[cfg(any(feature = "_test_utils", fuzzing, test))]
398 fn type_id(&self) -> u16 { unreachable!(); }
402 impl<T: core::fmt::Debug + Writeable + PartialEq> Type for T where T: Encode {
403 fn type_id(&self) -> u16 { T::TYPE }
407 impl<T: core::fmt::Debug + Writeable> Type for T where T: Encode {
408 fn type_id(&self) -> u16 { T::TYPE }
411 impl Encode for msgs::Init {
412 const TYPE: u16 = 16;
415 impl Encode for msgs::ErrorMessage {
416 const TYPE: u16 = 17;
419 impl Encode for msgs::WarningMessage {
423 impl Encode for msgs::Ping {
424 const TYPE: u16 = 18;
427 impl Encode for msgs::Pong {
428 const TYPE: u16 = 19;
431 impl Encode for msgs::OpenChannel {
432 const TYPE: u16 = 32;
435 impl Encode for msgs::AcceptChannel {
436 const TYPE: u16 = 33;
439 impl Encode for msgs::FundingCreated {
440 const TYPE: u16 = 34;
443 impl Encode for msgs::FundingSigned {
444 const TYPE: u16 = 35;
447 impl Encode for msgs::ChannelReady {
448 const TYPE: u16 = 36;
451 impl Encode for msgs::Shutdown {
452 const TYPE: u16 = 38;
455 impl Encode for msgs::ClosingSigned {
456 const TYPE: u16 = 39;
459 impl Encode for msgs::OpenChannelV2 {
460 const TYPE: u16 = 64;
463 impl Encode for msgs::AcceptChannelV2 {
464 const TYPE: u16 = 65;
467 impl Encode for msgs::TxAddInput {
468 const TYPE: u16 = 66;
471 impl Encode for msgs::TxAddOutput {
472 const TYPE: u16 = 67;
475 impl Encode for msgs::TxRemoveInput {
476 const TYPE: u16 = 68;
479 impl Encode for msgs::TxRemoveOutput {
480 const TYPE: u16 = 69;
483 impl Encode for msgs::TxComplete {
484 const TYPE: u16 = 70;
487 impl Encode for msgs::TxSignatures {
488 const TYPE: u16 = 71;
491 impl Encode for msgs::TxInitRbf {
492 const TYPE: u16 = 72;
495 impl Encode for msgs::TxAckRbf {
496 const TYPE: u16 = 73;
499 impl Encode for msgs::TxAbort {
500 const TYPE: u16 = 74;
503 impl Encode for msgs::OnionMessage {
504 const TYPE: u16 = 513;
507 impl Encode for msgs::UpdateAddHTLC {
508 const TYPE: u16 = 128;
511 impl Encode for msgs::UpdateFulfillHTLC {
512 const TYPE: u16 = 130;
515 impl Encode for msgs::UpdateFailHTLC {
516 const TYPE: u16 = 131;
519 impl Encode for msgs::UpdateFailMalformedHTLC {
520 const TYPE: u16 = 135;
523 impl Encode for msgs::CommitmentSigned {
524 const TYPE: u16 = 132;
527 impl Encode for msgs::RevokeAndACK {
528 const TYPE: u16 = 133;
531 impl Encode for msgs::UpdateFee {
532 const TYPE: u16 = 134;
535 impl Encode for msgs::ChannelReestablish {
536 const TYPE: u16 = 136;
539 impl Encode for msgs::AnnouncementSignatures {
540 const TYPE: u16 = 259;
543 impl Encode for msgs::ChannelAnnouncement {
544 const TYPE: u16 = 256;
547 impl Encode for msgs::NodeAnnouncement {
548 const TYPE: u16 = 257;
551 impl Encode for msgs::ChannelUpdate {
552 const TYPE: u16 = 258;
555 impl Encode for msgs::QueryShortChannelIds {
556 const TYPE: u16 = 261;
559 impl Encode for msgs::ReplyShortChannelIdsEnd {
560 const TYPE: u16 = 262;
563 impl Encode for msgs::QueryChannelRange {
564 const TYPE: u16 = 263;
567 impl Encode for msgs::ReplyChannelRange {
568 const TYPE: u16 = 264;
571 impl Encode for msgs::GossipTimestampFilter {
572 const TYPE: u16 = 265;
578 use crate::prelude::*;
579 use core::convert::TryInto;
580 use crate::ln::peer_handler::IgnoringMessageHandler;
582 // Big-endian wire encoding of Pong message (type = 19, byteslen = 2).
583 const ENCODED_PONG: [u8; 6] = [0u8, 19u8, 0u8, 2u8, 0u8, 0u8];
586 fn read_empty_buffer() {
588 let mut reader = io::Cursor::new(buffer);
589 assert!(read(&mut reader, &IgnoringMessageHandler{}).is_err());
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());
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());
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());
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();
619 Message::Pong(_) => (),
620 _ => panic!("Expected pong message; found message type: {}", message.type_id()),
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();
630 Message::Unknown(::core::u16::MAX) => (),
631 _ => panic!("Expected message type {}; found: {}", ::core::u16::MAX, message.type_id()),
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());
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..]);
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());
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);
660 _ => panic!("Expected pong message; found message type: {}", decoded_message.type_id()),
665 fn is_even_message_type() {
666 let message = Message::<()>::Unknown(42);
667 assert!(message.is_even());
671 fn is_odd_message_type() {
672 let message = Message::<()>::Unknown(43);
673 assert!(!message.is_even());
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);
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);
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();
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());
702 _ => panic!("Expected init message, found message type: {}", decoded_msg.type_id())
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();
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());
719 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
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();
730 Message::ChannelAnnouncement(msgs::ChannelAnnouncement { contents: msgs::UnsignedChannelAnnouncement { features, ..}, ..}) => {
731 assert!(!features.requires_unknown_bits());
733 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
737 #[derive(Eq, PartialEq, Debug)]
738 struct TestCustomMessage {}
740 const CUSTOM_MESSAGE_TYPE : u16 = 9000;
742 impl Type for TestCustomMessage {
743 fn type_id(&self) -> u16 {
748 impl Writeable for TestCustomMessage {
749 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
754 struct TestCustomMessageReader {}
756 impl CustomMessageReader for TestCustomMessageReader {
757 type CustomMessage = TestCustomMessage;
758 fn read<R: io::Read>(
762 ) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
763 if message_type == CUSTOM_MESSAGE_TYPE {
764 return Ok(Some(TestCustomMessage{}));
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();
777 Message::Custom(custom) => {
778 assert_eq!(custom.type_id(), CUSTOM_MESSAGE_TYPE);
779 assert_eq!(custom, TestCustomMessage {});
781 _ => panic!("Expected custom message, found message type: {}", decoded_msg.type_id()),
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();
791 Message::Unknown(_) => {},
792 _ => panic!("Expected unknown message, found message type: {}", decoded_msg.type_id()),
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());