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
23 use util::ser::{Readable, Writeable, Writer};
25 /// A Lightning message returned by [`read()`] when decoding bytes received over the wire. Each
26 /// variant contains a message from [`msgs`] or otherwise the message type if unknown.
27 #[allow(missing_docs)]
31 Error(msgs::ErrorMessage),
34 OpenChannel(msgs::OpenChannel),
35 AcceptChannel(msgs::AcceptChannel),
36 FundingCreated(msgs::FundingCreated),
37 FundingSigned(msgs::FundingSigned),
38 FundingLocked(msgs::FundingLocked),
39 Shutdown(msgs::Shutdown),
40 ClosingSigned(msgs::ClosingSigned),
41 UpdateAddHTLC(msgs::UpdateAddHTLC),
42 UpdateFulfillHTLC(msgs::UpdateFulfillHTLC),
43 UpdateFailHTLC(msgs::UpdateFailHTLC),
44 UpdateFailMalformedHTLC(msgs::UpdateFailMalformedHTLC),
45 CommitmentSigned(msgs::CommitmentSigned),
46 RevokeAndACK(msgs::RevokeAndACK),
47 UpdateFee(msgs::UpdateFee),
48 ChannelReestablish(msgs::ChannelReestablish),
49 AnnouncementSignatures(msgs::AnnouncementSignatures),
50 ChannelAnnouncement(msgs::ChannelAnnouncement),
51 NodeAnnouncement(msgs::NodeAnnouncement),
52 ChannelUpdate(msgs::ChannelUpdate),
53 QueryShortChannelIds(msgs::QueryShortChannelIds),
54 ReplyShortChannelIdsEnd(msgs::ReplyShortChannelIdsEnd),
55 QueryChannelRange(msgs::QueryChannelRange),
56 ReplyChannelRange(msgs::ReplyChannelRange),
57 GossipTimestampFilter(msgs::GossipTimestampFilter),
58 /// A message that could not be decoded because its type is unknown.
62 /// A number identifying a message to determine how it is encoded on the wire.
63 #[derive(Clone, Copy, Debug)]
64 pub struct MessageType(u16);
67 #[allow(dead_code)] // This method is only used in tests
68 /// Returns the type that was used to decode the message payload.
69 pub fn type_id(&self) -> MessageType {
71 &Message::Init(ref msg) => msg.type_id(),
72 &Message::Error(ref msg) => msg.type_id(),
73 &Message::Ping(ref msg) => msg.type_id(),
74 &Message::Pong(ref msg) => msg.type_id(),
75 &Message::OpenChannel(ref msg) => msg.type_id(),
76 &Message::AcceptChannel(ref msg) => msg.type_id(),
77 &Message::FundingCreated(ref msg) => msg.type_id(),
78 &Message::FundingSigned(ref msg) => msg.type_id(),
79 &Message::FundingLocked(ref msg) => msg.type_id(),
80 &Message::Shutdown(ref msg) => msg.type_id(),
81 &Message::ClosingSigned(ref msg) => msg.type_id(),
82 &Message::UpdateAddHTLC(ref msg) => msg.type_id(),
83 &Message::UpdateFulfillHTLC(ref msg) => msg.type_id(),
84 &Message::UpdateFailHTLC(ref msg) => msg.type_id(),
85 &Message::UpdateFailMalformedHTLC(ref msg) => msg.type_id(),
86 &Message::CommitmentSigned(ref msg) => msg.type_id(),
87 &Message::RevokeAndACK(ref msg) => msg.type_id(),
88 &Message::UpdateFee(ref msg) => msg.type_id(),
89 &Message::ChannelReestablish(ref msg) => msg.type_id(),
90 &Message::AnnouncementSignatures(ref msg) => msg.type_id(),
91 &Message::ChannelAnnouncement(ref msg) => msg.type_id(),
92 &Message::NodeAnnouncement(ref msg) => msg.type_id(),
93 &Message::ChannelUpdate(ref msg) => msg.type_id(),
94 &Message::QueryShortChannelIds(ref msg) => msg.type_id(),
95 &Message::ReplyShortChannelIdsEnd(ref msg) => msg.type_id(),
96 &Message::QueryChannelRange(ref msg) => msg.type_id(),
97 &Message::ReplyChannelRange(ref msg) => msg.type_id(),
98 &Message::GossipTimestampFilter(ref msg) => msg.type_id(),
99 &Message::Unknown(type_id) => type_id,
105 /// Returns whether the message type is even, indicating both endpoints must support it.
106 pub fn is_even(&self) -> bool {
111 impl ::core::fmt::Display for MessageType {
112 fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
113 write!(f, "{}", self.0)
117 /// Reads a message from the data buffer consisting of a 2-byte big-endian type and a
118 /// variable-length payload conforming to the type.
122 /// Returns an error if the message payload code not be decoded as the specified type.
123 pub fn read<R: io::Read>(buffer: &mut R) -> Result<Message, msgs::DecodeError> {
124 let message_type = <u16 as Readable>::read(buffer)?;
126 msgs::Init::TYPE => {
127 Ok(Message::Init(Readable::read(buffer)?))
129 msgs::ErrorMessage::TYPE => {
130 Ok(Message::Error(Readable::read(buffer)?))
132 msgs::Ping::TYPE => {
133 Ok(Message::Ping(Readable::read(buffer)?))
135 msgs::Pong::TYPE => {
136 Ok(Message::Pong(Readable::read(buffer)?))
138 msgs::OpenChannel::TYPE => {
139 Ok(Message::OpenChannel(Readable::read(buffer)?))
141 msgs::AcceptChannel::TYPE => {
142 Ok(Message::AcceptChannel(Readable::read(buffer)?))
144 msgs::FundingCreated::TYPE => {
145 Ok(Message::FundingCreated(Readable::read(buffer)?))
147 msgs::FundingSigned::TYPE => {
148 Ok(Message::FundingSigned(Readable::read(buffer)?))
150 msgs::FundingLocked::TYPE => {
151 Ok(Message::FundingLocked(Readable::read(buffer)?))
153 msgs::Shutdown::TYPE => {
154 Ok(Message::Shutdown(Readable::read(buffer)?))
156 msgs::ClosingSigned::TYPE => {
157 Ok(Message::ClosingSigned(Readable::read(buffer)?))
159 msgs::UpdateAddHTLC::TYPE => {
160 Ok(Message::UpdateAddHTLC(Readable::read(buffer)?))
162 msgs::UpdateFulfillHTLC::TYPE => {
163 Ok(Message::UpdateFulfillHTLC(Readable::read(buffer)?))
165 msgs::UpdateFailHTLC::TYPE => {
166 Ok(Message::UpdateFailHTLC(Readable::read(buffer)?))
168 msgs::UpdateFailMalformedHTLC::TYPE => {
169 Ok(Message::UpdateFailMalformedHTLC(Readable::read(buffer)?))
171 msgs::CommitmentSigned::TYPE => {
172 Ok(Message::CommitmentSigned(Readable::read(buffer)?))
174 msgs::RevokeAndACK::TYPE => {
175 Ok(Message::RevokeAndACK(Readable::read(buffer)?))
177 msgs::UpdateFee::TYPE => {
178 Ok(Message::UpdateFee(Readable::read(buffer)?))
180 msgs::ChannelReestablish::TYPE => {
181 Ok(Message::ChannelReestablish(Readable::read(buffer)?))
183 msgs::AnnouncementSignatures::TYPE => {
184 Ok(Message::AnnouncementSignatures(Readable::read(buffer)?))
186 msgs::ChannelAnnouncement::TYPE => {
187 Ok(Message::ChannelAnnouncement(Readable::read(buffer)?))
189 msgs::NodeAnnouncement::TYPE => {
190 Ok(Message::NodeAnnouncement(Readable::read(buffer)?))
192 msgs::ChannelUpdate::TYPE => {
193 Ok(Message::ChannelUpdate(Readable::read(buffer)?))
195 msgs::QueryShortChannelIds::TYPE => {
196 Ok(Message::QueryShortChannelIds(Readable::read(buffer)?))
198 msgs::ReplyShortChannelIdsEnd::TYPE => {
199 Ok(Message::ReplyShortChannelIdsEnd(Readable::read(buffer)?))
201 msgs::QueryChannelRange::TYPE => {
202 Ok(Message::QueryChannelRange(Readable::read(buffer)?))
204 msgs::ReplyChannelRange::TYPE => {
205 Ok(Message::ReplyChannelRange(Readable::read(buffer)?))
207 msgs::GossipTimestampFilter::TYPE => {
208 Ok(Message::GossipTimestampFilter(Readable::read(buffer)?))
211 Ok(Message::Unknown(MessageType(message_type)))
216 /// Writes a message to the data buffer encoded as a 2-byte big-endian type and a variable-length
221 /// Returns an I/O error if the write could not be completed.
222 pub fn write<M: Encode + Writeable, W: Writer>(message: &M, buffer: &mut W) -> Result<(), io::Error> {
223 M::TYPE.write(buffer)?;
224 message.write(buffer)
227 /// Defines a type-identified encoding for sending messages over the wire.
229 /// Messages implementing this trait specify a type and must be [`Writeable`] to use with [`write()`].
231 /// The type identifying the message payload.
234 /// Returns the type identifying the message payload. Convenience method for accessing
236 fn type_id(&self) -> MessageType {
237 MessageType(Self::TYPE)
241 impl Encode for msgs::Init {
242 const TYPE: u16 = 16;
245 impl Encode for msgs::ErrorMessage {
246 const TYPE: u16 = 17;
249 impl Encode for msgs::Ping {
250 const TYPE: u16 = 18;
253 impl Encode for msgs::Pong {
254 const TYPE: u16 = 19;
257 impl Encode for msgs::OpenChannel {
258 const TYPE: u16 = 32;
261 impl Encode for msgs::AcceptChannel {
262 const TYPE: u16 = 33;
265 impl Encode for msgs::FundingCreated {
266 const TYPE: u16 = 34;
269 impl Encode for msgs::FundingSigned {
270 const TYPE: u16 = 35;
273 impl Encode for msgs::FundingLocked {
274 const TYPE: u16 = 36;
277 impl Encode for msgs::Shutdown {
278 const TYPE: u16 = 38;
281 impl Encode for msgs::ClosingSigned {
282 const TYPE: u16 = 39;
285 impl Encode for msgs::UpdateAddHTLC {
286 const TYPE: u16 = 128;
289 impl Encode for msgs::UpdateFulfillHTLC {
290 const TYPE: u16 = 130;
293 impl Encode for msgs::UpdateFailHTLC {
294 const TYPE: u16 = 131;
297 impl Encode for msgs::UpdateFailMalformedHTLC {
298 const TYPE: u16 = 135;
301 impl Encode for msgs::CommitmentSigned {
302 const TYPE: u16 = 132;
305 impl Encode for msgs::RevokeAndACK {
306 const TYPE: u16 = 133;
309 impl Encode for msgs::UpdateFee {
310 const TYPE: u16 = 134;
313 impl Encode for msgs::ChannelReestablish {
314 const TYPE: u16 = 136;
317 impl Encode for msgs::AnnouncementSignatures {
318 const TYPE: u16 = 259;
321 impl Encode for msgs::ChannelAnnouncement {
322 const TYPE: u16 = 256;
325 impl Encode for msgs::NodeAnnouncement {
326 const TYPE: u16 = 257;
329 impl Encode for msgs::ChannelUpdate {
330 const TYPE: u16 = 258;
333 impl Encode for msgs::QueryShortChannelIds {
334 const TYPE: u16 = 261;
337 impl Encode for msgs::ReplyShortChannelIdsEnd {
338 const TYPE: u16 = 262;
341 impl Encode for msgs::QueryChannelRange {
342 const TYPE: u16 = 263;
345 impl Encode for msgs::ReplyChannelRange {
346 const TYPE: u16 = 264;
349 impl Encode for msgs::GossipTimestampFilter {
350 const TYPE: u16 = 265;
357 use core::convert::TryInto;
359 // Big-endian wire encoding of Pong message (type = 19, byteslen = 2).
360 const ENCODED_PONG: [u8; 6] = [0u8, 19u8, 0u8, 2u8, 0u8, 0u8];
363 fn read_empty_buffer() {
365 let mut reader = io::Cursor::new(buffer);
366 assert!(read(&mut reader).is_err());
370 fn read_incomplete_type() {
371 let buffer = &ENCODED_PONG[..1];
372 let mut reader = io::Cursor::new(buffer);
373 assert!(read(&mut reader).is_err());
377 fn read_empty_payload() {
378 let buffer = &ENCODED_PONG[..2];
379 let mut reader = io::Cursor::new(buffer);
380 assert!(read(&mut reader).is_err());
384 fn read_invalid_message() {
385 let buffer = &ENCODED_PONG[..4];
386 let mut reader = io::Cursor::new(buffer);
387 assert!(read(&mut reader).is_err());
391 fn read_known_message() {
392 let buffer = &ENCODED_PONG[..];
393 let mut reader = io::Cursor::new(buffer);
394 let message = read(&mut reader).unwrap();
396 Message::Pong(_) => (),
397 _ => panic!("Expected pong message; found message type: {}", message.type_id()),
402 fn read_unknown_message() {
403 let buffer = &::core::u16::MAX.to_be_bytes();
404 let mut reader = io::Cursor::new(buffer);
405 let message = read(&mut reader).unwrap();
407 Message::Unknown(MessageType(::core::u16::MAX)) => (),
408 _ => panic!("Expected message type {}; found: {}", ::core::u16::MAX, message.type_id()),
413 fn write_message_with_type() {
414 let message = msgs::Pong { byteslen: 2u16 };
415 let mut buffer = Vec::new();
416 assert!(write(&message, &mut buffer).is_ok());
418 let type_length = ::core::mem::size_of::<u16>();
419 let (type_bytes, payload_bytes) = buffer.split_at(type_length);
420 assert_eq!(u16::from_be_bytes(type_bytes.try_into().unwrap()), msgs::Pong::TYPE);
421 assert_eq!(payload_bytes, &ENCODED_PONG[type_length..]);
425 fn read_message_encoded_with_write() {
426 let message = msgs::Pong { byteslen: 2u16 };
427 let mut buffer = Vec::new();
428 assert!(write(&message, &mut buffer).is_ok());
430 let mut reader = io::Cursor::new(buffer);
431 let decoded_message = read(&mut reader).unwrap();
432 match decoded_message {
433 Message::Pong(msgs::Pong { byteslen: 2u16 }) => (),
434 Message::Pong(msgs::Pong { byteslen }) => {
435 panic!("Expected byteslen {}; found: {}", message.byteslen, byteslen);
437 _ => panic!("Expected pong message; found message type: {}", decoded_message.type_id()),
442 fn is_even_message_type() {
443 let message = Message::Unknown(MessageType(42));
444 assert!(message.type_id().is_even());
448 fn is_odd_message_type() {
449 let message = Message::Unknown(MessageType(43));
450 assert!(!message.type_id().is_even());
454 fn read_lnd_init_msg() {
455 // Taken from lnd v0.9.0-beta.
456 let buffer = vec![0, 16, 0, 2, 34, 0, 0, 3, 2, 162, 161];
457 check_init_msg(buffer, false);
461 fn read_clightning_init_msg() {
462 // Taken from c-lightning v0.8.0.
463 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];
464 check_init_msg(buffer, true);
467 fn check_init_msg(buffer: Vec<u8>, expect_unknown: bool) {
468 let mut reader = io::Cursor::new(buffer);
469 let decoded_msg = read(&mut reader).unwrap();
471 Message::Init(msgs::Init { features }) => {
472 assert!(features.supports_variable_length_onion());
473 assert!(features.supports_upfront_shutdown_script());
474 assert!(features.supports_gossip_queries());
475 assert_eq!(expect_unknown, features.supports_unknown_bits());
476 assert!(!features.requires_unknown_bits());
477 assert!(!features.initial_routing_sync());
479 _ => panic!("Expected init message, found message type: {}", decoded_msg.type_id())
484 fn read_lnd_node_announcement() {
485 // Taken from lnd v0.9.0-beta.
486 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];
487 let mut reader = io::Cursor::new(buffer);
488 let decoded_msg = read(&mut reader).unwrap();
490 Message::NodeAnnouncement(msgs::NodeAnnouncement { contents: msgs::UnsignedNodeAnnouncement { features, ..}, ..}) => {
491 assert!(features.supports_variable_length_onion());
492 assert!(features.supports_upfront_shutdown_script());
493 assert!(features.supports_gossip_queries());
494 assert!(!features.requires_unknown_bits());
496 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())
501 fn read_lnd_chan_announcement() {
502 // Taken from lnd v0.9.0-beta.
503 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];
504 let mut reader = io::Cursor::new(buffer);
505 let decoded_msg = read(&mut reader).unwrap();
507 Message::ChannelAnnouncement(msgs::ChannelAnnouncement { contents: msgs::UnsignedChannelAnnouncement { features, ..}, ..}) => {
508 assert!(!features.requires_unknown_bits());
510 _ => panic!("Expected node announcement, found message type: {}", decoded_msg.type_id())