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].
12 //! Messages known by this module can be read from the wire using [`read()`].
13 //! The [`Message`] enum returned by [`read()`] wraps the decoded message or the message type (if
14 //! unknown) to use with pattern matching.
16 //! Messages implementing the [`Encode`] trait define a message type and can be sent over the wire
17 //! using [`write()`].
19 //! [BOLT #1]: https://github.com/lightningnetwork/lightning-rfc/blob/master/01-messaging.md
22 use util::ser::{Readable, Writeable, Writer};
24 /// A Lightning message returned by [`read()`] when decoding bytes received over the wire. Each
25 /// variant contains a message from [`msgs`] or otherwise the message type if unknown.
26 #[allow(missing_docs)]
29 Error(msgs::ErrorMessage),
32 OpenChannel(msgs::OpenChannel),
33 AcceptChannel(msgs::AcceptChannel),
34 FundingCreated(msgs::FundingCreated),
35 FundingSigned(msgs::FundingSigned),
36 FundingLocked(msgs::FundingLocked),
37 Shutdown(msgs::Shutdown),
38 ClosingSigned(msgs::ClosingSigned),
39 UpdateAddHTLC(msgs::UpdateAddHTLC),
40 UpdateFulfillHTLC(msgs::UpdateFulfillHTLC),
41 UpdateFailHTLC(msgs::UpdateFailHTLC),
42 UpdateFailMalformedHTLC(msgs::UpdateFailMalformedHTLC),
43 CommitmentSigned(msgs::CommitmentSigned),
44 RevokeAndACK(msgs::RevokeAndACK),
45 UpdateFee(msgs::UpdateFee),
46 ChannelReestablish(msgs::ChannelReestablish),
47 AnnouncementSignatures(msgs::AnnouncementSignatures),
48 ChannelAnnouncement(msgs::ChannelAnnouncement),
49 NodeAnnouncement(msgs::NodeAnnouncement),
50 ChannelUpdate(msgs::ChannelUpdate),
51 QueryShortChannelIds(msgs::QueryShortChannelIds),
52 ReplyShortChannelIdsEnd(msgs::ReplyShortChannelIdsEnd),
53 QueryChannelRange(msgs::QueryChannelRange),
54 ReplyChannelRange(msgs::ReplyChannelRange),
55 GossipTimestampFilter(msgs::GossipTimestampFilter),
56 /// A message that could not be decoded because its type is unknown.
60 /// A number identifying a message to determine how it is encoded on the wire.
61 #[derive(Clone, Copy)]
62 pub struct MessageType(u16);
65 /// Returns the type that was used to decode the message payload.
66 pub fn type_id(&self) -> MessageType {
68 &Message::Init(ref msg) => msg.type_id(),
69 &Message::Error(ref msg) => msg.type_id(),
70 &Message::Ping(ref msg) => msg.type_id(),
71 &Message::Pong(ref msg) => msg.type_id(),
72 &Message::OpenChannel(ref msg) => msg.type_id(),
73 &Message::AcceptChannel(ref msg) => msg.type_id(),
74 &Message::FundingCreated(ref msg) => msg.type_id(),
75 &Message::FundingSigned(ref msg) => msg.type_id(),
76 &Message::FundingLocked(ref msg) => msg.type_id(),
77 &Message::Shutdown(ref msg) => msg.type_id(),
78 &Message::ClosingSigned(ref msg) => msg.type_id(),
79 &Message::UpdateAddHTLC(ref msg) => msg.type_id(),
80 &Message::UpdateFulfillHTLC(ref msg) => msg.type_id(),
81 &Message::UpdateFailHTLC(ref msg) => msg.type_id(),
82 &Message::UpdateFailMalformedHTLC(ref msg) => msg.type_id(),
83 &Message::CommitmentSigned(ref msg) => msg.type_id(),
84 &Message::RevokeAndACK(ref msg) => msg.type_id(),
85 &Message::UpdateFee(ref msg) => msg.type_id(),
86 &Message::ChannelReestablish(ref msg) => msg.type_id(),
87 &Message::AnnouncementSignatures(ref msg) => msg.type_id(),
88 &Message::ChannelAnnouncement(ref msg) => msg.type_id(),
89 &Message::NodeAnnouncement(ref msg) => msg.type_id(),
90 &Message::ChannelUpdate(ref msg) => msg.type_id(),
91 &Message::QueryShortChannelIds(ref msg) => msg.type_id(),
92 &Message::ReplyShortChannelIdsEnd(ref msg) => msg.type_id(),
93 &Message::QueryChannelRange(ref msg) => msg.type_id(),
94 &Message::ReplyChannelRange(ref msg) => msg.type_id(),
95 &Message::GossipTimestampFilter(ref msg) => msg.type_id(),
96 &Message::Unknown(type_id) => type_id,
102 /// Returns whether the message type is even, indicating both endpoints must support it.
103 pub fn is_even(&self) -> bool {
108 impl ::std::fmt::Display for MessageType {
109 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
110 write!(f, "{}", self.0)
114 /// Reads a message from the data buffer consisting of a 2-byte big-endian type and a
115 /// variable-length payload conforming to the type.
119 /// Returns an error if the message payload code not be decoded as the specified type.
120 pub fn read<R: ::std::io::Read>(buffer: &mut R) -> Result<Message, msgs::DecodeError> {
121 let message_type = <u16 as Readable>::read(buffer)?;
123 msgs::Init::TYPE => {
124 Ok(Message::Init(Readable::read(buffer)?))
126 msgs::ErrorMessage::TYPE => {
127 Ok(Message::Error(Readable::read(buffer)?))
129 msgs::Ping::TYPE => {
130 Ok(Message::Ping(Readable::read(buffer)?))
132 msgs::Pong::TYPE => {
133 Ok(Message::Pong(Readable::read(buffer)?))
135 msgs::OpenChannel::TYPE => {
136 Ok(Message::OpenChannel(Readable::read(buffer)?))
138 msgs::AcceptChannel::TYPE => {
139 Ok(Message::AcceptChannel(Readable::read(buffer)?))
141 msgs::FundingCreated::TYPE => {
142 Ok(Message::FundingCreated(Readable::read(buffer)?))
144 msgs::FundingSigned::TYPE => {
145 Ok(Message::FundingSigned(Readable::read(buffer)?))
147 msgs::FundingLocked::TYPE => {
148 Ok(Message::FundingLocked(Readable::read(buffer)?))
150 msgs::Shutdown::TYPE => {
151 Ok(Message::Shutdown(Readable::read(buffer)?))
153 msgs::ClosingSigned::TYPE => {
154 Ok(Message::ClosingSigned(Readable::read(buffer)?))
156 msgs::UpdateAddHTLC::TYPE => {
157 Ok(Message::UpdateAddHTLC(Readable::read(buffer)?))
159 msgs::UpdateFulfillHTLC::TYPE => {
160 Ok(Message::UpdateFulfillHTLC(Readable::read(buffer)?))
162 msgs::UpdateFailHTLC::TYPE => {
163 Ok(Message::UpdateFailHTLC(Readable::read(buffer)?))
165 msgs::UpdateFailMalformedHTLC::TYPE => {
166 Ok(Message::UpdateFailMalformedHTLC(Readable::read(buffer)?))
168 msgs::CommitmentSigned::TYPE => {
169 Ok(Message::CommitmentSigned(Readable::read(buffer)?))
171 msgs::RevokeAndACK::TYPE => {
172 Ok(Message::RevokeAndACK(Readable::read(buffer)?))
174 msgs::UpdateFee::TYPE => {
175 Ok(Message::UpdateFee(Readable::read(buffer)?))
177 msgs::ChannelReestablish::TYPE => {
178 Ok(Message::ChannelReestablish(Readable::read(buffer)?))
180 msgs::AnnouncementSignatures::TYPE => {
181 Ok(Message::AnnouncementSignatures(Readable::read(buffer)?))
183 msgs::ChannelAnnouncement::TYPE => {
184 Ok(Message::ChannelAnnouncement(Readable::read(buffer)?))
186 msgs::NodeAnnouncement::TYPE => {
187 Ok(Message::NodeAnnouncement(Readable::read(buffer)?))
189 msgs::ChannelUpdate::TYPE => {
190 Ok(Message::ChannelUpdate(Readable::read(buffer)?))
192 msgs::QueryShortChannelIds::TYPE => {
193 Ok(Message::QueryShortChannelIds(Readable::read(buffer)?))
195 msgs::ReplyShortChannelIdsEnd::TYPE => {
196 Ok(Message::ReplyShortChannelIdsEnd(Readable::read(buffer)?))
198 msgs::QueryChannelRange::TYPE => {
199 Ok(Message::QueryChannelRange(Readable::read(buffer)?))
201 msgs::ReplyChannelRange::TYPE => {
202 Ok(Message::ReplyChannelRange(Readable::read(buffer)?))
204 msgs::GossipTimestampFilter::TYPE => {
205 Ok(Message::GossipTimestampFilter(Readable::read(buffer)?))
208 Ok(Message::Unknown(MessageType(message_type)))
213 /// Writes a message to the data buffer encoded as a 2-byte big-endian type and a variable-length
218 /// Returns an I/O error if the write could not be completed.
219 pub fn write<M: Encode + Writeable, W: Writer>(message: &M, buffer: &mut W) -> Result<(), ::std::io::Error> {
220 M::TYPE.write(buffer)?;
221 message.write(buffer)
224 /// Defines a type-identified encoding for sending messages over the wire.
226 /// Messages implementing this trait specify a type and must be [`Writeable`] to use with [`write()`].
228 /// The type identifying the message payload.
231 /// Returns the type identifying the message payload. Convenience method for accessing
233 fn type_id(&self) -> MessageType {
234 MessageType(Self::TYPE)
238 impl Encode for msgs::Init {
239 const TYPE: u16 = 16;
242 impl Encode for msgs::ErrorMessage {
243 const TYPE: u16 = 17;
246 impl Encode for msgs::Ping {
247 const TYPE: u16 = 18;
250 impl Encode for msgs::Pong {
251 const TYPE: u16 = 19;
254 impl Encode for msgs::OpenChannel {
255 const TYPE: u16 = 32;
258 impl Encode for msgs::AcceptChannel {
259 const TYPE: u16 = 33;
262 impl Encode for msgs::FundingCreated {
263 const TYPE: u16 = 34;
266 impl Encode for msgs::FundingSigned {
267 const TYPE: u16 = 35;
270 impl Encode for msgs::FundingLocked {
271 const TYPE: u16 = 36;
274 impl Encode for msgs::Shutdown {
275 const TYPE: u16 = 38;
278 impl Encode for msgs::ClosingSigned {
279 const TYPE: u16 = 39;
282 impl Encode for msgs::UpdateAddHTLC {
283 const TYPE: u16 = 128;
286 impl Encode for msgs::UpdateFulfillHTLC {
287 const TYPE: u16 = 130;
290 impl Encode for msgs::UpdateFailHTLC {
291 const TYPE: u16 = 131;
294 impl Encode for msgs::UpdateFailMalformedHTLC {
295 const TYPE: u16 = 135;
298 impl Encode for msgs::CommitmentSigned {
299 const TYPE: u16 = 132;
302 impl Encode for msgs::RevokeAndACK {
303 const TYPE: u16 = 133;
306 impl Encode for msgs::UpdateFee {
307 const TYPE: u16 = 134;
310 impl Encode for msgs::ChannelReestablish {
311 const TYPE: u16 = 136;
314 impl Encode for msgs::AnnouncementSignatures {
315 const TYPE: u16 = 259;
318 impl Encode for msgs::ChannelAnnouncement {
319 const TYPE: u16 = 256;
322 impl Encode for msgs::NodeAnnouncement {
323 const TYPE: u16 = 257;
326 impl Encode for msgs::ChannelUpdate {
327 const TYPE: u16 = 258;
330 impl Encode for msgs::QueryShortChannelIds {
331 const TYPE: u16 = 261;
334 impl Encode for msgs::ReplyShortChannelIdsEnd {
335 const TYPE: u16 = 262;
338 impl Encode for msgs::QueryChannelRange {
339 const TYPE: u16 = 263;
342 impl Encode for msgs::ReplyChannelRange {
343 const TYPE: u16 = 264;
346 impl Encode for msgs::GossipTimestampFilter {
347 const TYPE: u16 = 265;
353 use util::byte_utils;
355 // Big-endian wire encoding of Pong message (type = 19, byteslen = 2).
356 const ENCODED_PONG: [u8; 6] = [0u8, 19u8, 0u8, 2u8, 0u8, 0u8];
359 fn read_empty_buffer() {
361 let mut reader = ::std::io::Cursor::new(buffer);
362 assert!(read(&mut reader).is_err());
366 fn read_incomplete_type() {
367 let buffer = &ENCODED_PONG[..1];
368 let mut reader = ::std::io::Cursor::new(buffer);
369 assert!(read(&mut reader).is_err());
373 fn read_empty_payload() {
374 let buffer = &ENCODED_PONG[..2];
375 let mut reader = ::std::io::Cursor::new(buffer);
376 assert!(read(&mut reader).is_err());
380 fn read_invalid_message() {
381 let buffer = &ENCODED_PONG[..4];
382 let mut reader = ::std::io::Cursor::new(buffer);
383 assert!(read(&mut reader).is_err());
387 fn read_known_message() {
388 let buffer = &ENCODED_PONG[..];
389 let mut reader = ::std::io::Cursor::new(buffer);
390 let message = read(&mut reader).unwrap();
392 Message::Pong(_) => (),
393 _ => panic!("Expected pong message; found message type: {}", message.type_id()),
398 fn read_unknown_message() {
399 let buffer = &byte_utils::be16_to_array(::std::u16::MAX);
400 let mut reader = ::std::io::Cursor::new(buffer);
401 let message = read(&mut reader).unwrap();
403 Message::Unknown(MessageType(::std::u16::MAX)) => (),
404 _ => panic!("Expected message type {}; found: {}", ::std::u16::MAX, message.type_id()),
409 fn write_message_with_type() {
410 let message = msgs::Pong { byteslen: 2u16 };
411 let mut buffer = Vec::new();
412 assert!(write(&message, &mut buffer).is_ok());
414 let type_length = ::std::mem::size_of::<u16>();
415 let (type_bytes, payload_bytes) = buffer.split_at(type_length);
416 assert_eq!(byte_utils::slice_to_be16(type_bytes), msgs::Pong::TYPE);
417 assert_eq!(payload_bytes, &ENCODED_PONG[type_length..]);
421 fn read_message_encoded_with_write() {
422 let message = msgs::Pong { byteslen: 2u16 };
423 let mut buffer = Vec::new();
424 assert!(write(&message, &mut buffer).is_ok());
426 let mut reader = ::std::io::Cursor::new(buffer);
427 let decoded_message = read(&mut reader).unwrap();
428 match decoded_message {
429 Message::Pong(msgs::Pong { byteslen: 2u16 }) => (),
430 Message::Pong(msgs::Pong { byteslen }) => {
431 panic!("Expected byteslen {}; found: {}", message.byteslen, byteslen);
433 _ => panic!("Expected pong message; found message type: {}", decoded_message.type_id()),
438 fn is_even_message_type() {
439 let message = Message::Unknown(MessageType(42));
440 assert!(message.type_id().is_even());
444 fn is_odd_message_type() {
445 let message = Message::Unknown(MessageType(43));
446 assert!(!message.type_id().is_even());
450 fn read_lnd_init_msg() {
451 // Taken from lnd v0.9.0-beta.
452 let buffer = vec![0, 16, 0, 2, 34, 0, 0, 3, 2, 162, 161];
453 check_init_msg(buffer, false);
457 fn read_clightning_init_msg() {
458 // Taken from c-lightning v0.8.0.
459 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];
460 check_init_msg(buffer, true);
463 fn check_init_msg(buffer: Vec<u8>, expect_unknown: bool) {
464 let mut reader = ::std::io::Cursor::new(buffer);
465 let decoded_msg = read(&mut reader).unwrap();
467 Message::Init(msgs::Init { features }) => {
468 assert!(features.supports_variable_length_onion());
469 assert!(features.supports_upfront_shutdown_script());
470 assert!(features.supports_gossip_queries());
471 assert_eq!(expect_unknown, features.supports_unknown_bits());
472 assert!(!features.requires_unknown_bits());
473 assert!(!features.initial_routing_sync());
475 _ => panic!("Expected init message, found message type: {}", decoded_msg.type_id())
480 fn read_lnd_node_announcement() {
481 // Taken from lnd v0.9.0-beta.
482 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];
483 let mut reader = ::std::io::Cursor::new(buffer);
484 let decoded_msg = read(&mut reader).unwrap();
486 Message::NodeAnnouncement(msgs::NodeAnnouncement { contents: msgs::UnsignedNodeAnnouncement { features, ..}, ..}) => {
487 assert!(features.supports_variable_length_onion());
488 assert!(features.supports_upfront_shutdown_script());
489 assert!(features.supports_gossip_queries());
490 assert!(!features.requires_unknown_bits());
492 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
497 fn read_lnd_chan_announcement() {
498 // Taken from lnd v0.9.0-beta.
499 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];
500 let mut reader = ::std::io::Cursor::new(buffer);
501 let decoded_msg = read(&mut reader).unwrap();
503 Message::ChannelAnnouncement(msgs::ChannelAnnouncement { contents: msgs::UnsignedChannelAnnouncement { features, ..}, ..}) => {
504 assert!(!features.requires_unknown_bits());
506 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())