lightning-custom-message 0.2.3

Utilities for supporting custom peer-to-peer messages in LDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Utilities for supporting custom peer-to-peer messages in LDK.
//!
//! [BOLT 1] specifies a custom message type range for use with experimental or application-specific
//! messages. While a [`CustomMessageHandler`] can be defined to support more than one message type,
//! defining such a handler requires a significant amount of boilerplate and can be error prone.
//!
//! This crate provides the [`composite_custom_message_handler`] macro for easily composing
//! pre-defined custom message handlers into one handler. The resulting handler can be further
//! composed with other custom message handlers using the same macro.
//!
//! The following example demonstrates defining a `FooBarHandler` to compose separate handlers for
//! `Foo` and `Bar` messages, and further composing it with a handler for `Baz` messages.
//!
//!```
//! # fn main() {} // Avoid #[macro_export] generating an in-function warning
//! # extern crate bitcoin;
//! extern crate lightning;
//! #[macro_use]
//! extern crate lightning_custom_message;
//!
//! # use bitcoin::secp256k1::PublicKey;
//! # use lightning::io;
//! # use lightning::ln::msgs::{DecodeError, Init, LightningError};
//! use lightning::ln::peer_handler::CustomMessageHandler;
//! use lightning::ln::wire::{CustomMessageReader, self};
//! # use lightning::types::features::{InitFeatures, NodeFeatures};
//! use lightning::util::ser::{LengthLimitedRead, Writeable};
//! # use lightning::util::ser::Writer;
//!
//! // Assume that `FooHandler` and `BarHandler` are defined in one crate and `BazHandler` is
//! // defined in another crate, handling messages `Foo`, `Bar`, and `Baz`, respectively.
//!
//! #[derive(Debug)]
//! pub struct Foo;
//!
//! macro_rules! foo_type_id {
//!     () => { 32768 }
//! }
//!
//! impl wire::Type for Foo {
//!     fn type_id(&self) -> u16 { foo_type_id!() }
//! }
//! impl Writeable for Foo {
//!     // ...
//! #     fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
//! #         unimplemented!()
//! #     }
//! }
//!
//! pub struct FooHandler;
//!
//! impl CustomMessageReader for FooHandler {
//!     // ...
//! #     type CustomMessage = Foo;
//! #     fn read<R: LengthLimitedRead>(
//! #         &self, _message_type: u16, _buffer: &mut R
//! #     ) -> Result<Option<Self::CustomMessage>, DecodeError> {
//! #         unimplemented!()
//! #     }
//! }
//! impl CustomMessageHandler for FooHandler {
//!     // ...
//! #     fn handle_custom_message(
//! #         &self, _msg: Self::CustomMessage, _sender_node_id: PublicKey
//! #     ) -> Result<(), LightningError> {
//! #         unimplemented!()
//! #     }
//! #     fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> {
//! #         unimplemented!()
//! #     }
//! #     fn peer_disconnected(&self, _their_node_id: PublicKey) {
//! #         unimplemented!()
//! #     }
//! #     fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> {
//! #         unimplemented!()
//! #     }
//! #     fn provided_node_features(&self) -> NodeFeatures {
//! #         unimplemented!()
//! #     }
//! #     fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures {
//! #         unimplemented!()
//! #     }
//! }
//!
//! #[derive(Debug)]
//! pub struct Bar;
//!
//! macro_rules! bar_type_id {
//!     () => { 32769 }
//! }
//!
//! impl wire::Type for Bar {
//!     fn type_id(&self) -> u16 { bar_type_id!() }
//! }
//! impl Writeable for Bar {
//!     // ...
//! #     fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
//! #         unimplemented!()
//! #     }
//! }
//!
//! pub struct BarHandler;
//!
//! impl CustomMessageReader for BarHandler {
//!     // ...
//! #     type CustomMessage = Bar;
//! #     fn read<R: LengthLimitedRead>(
//! #         &self, _message_type: u16, _buffer: &mut R
//! #     ) -> Result<Option<Self::CustomMessage>, DecodeError> {
//! #         unimplemented!()
//! #     }
//! }
//! impl CustomMessageHandler for BarHandler {
//!     // ...
//! #     fn handle_custom_message(
//! #         &self, _msg: Self::CustomMessage, _sender_node_id: PublicKey
//! #     ) -> Result<(), LightningError> {
//! #         unimplemented!()
//! #     }
//! #     fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> {
//! #         unimplemented!()
//! #     }
//! #     fn peer_disconnected(&self, _their_node_id: PublicKey) {
//! #         unimplemented!()
//! #     }
//! #     fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> {
//! #         unimplemented!()
//! #     }
//! #     fn provided_node_features(&self) -> NodeFeatures {
//! #         unimplemented!()
//! #     }
//! #     fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures {
//! #         unimplemented!()
//! #     }
//! }
//!
//! #[derive(Debug)]
//! pub struct Baz;
//!
//! macro_rules! baz_type_id {
//!     () => { 32770 }
//! }
//!
//! impl wire::Type for Baz {
//!     fn type_id(&self) -> u16 { baz_type_id!() }
//! }
//! impl Writeable for Baz {
//!     // ...
//! #     fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
//! #         unimplemented!()
//! #     }
//! }
//!
//! pub struct BazHandler;
//!
//! impl CustomMessageReader for BazHandler {
//!     // ...
//! #     type CustomMessage = Baz;
//! #     fn read<R: LengthLimitedRead>(
//! #         &self, _message_type: u16, _buffer: &mut R
//! #     ) -> Result<Option<Self::CustomMessage>, DecodeError> {
//! #         unimplemented!()
//! #     }
//! }
//! impl CustomMessageHandler for BazHandler {
//!     // ...
//! #     fn handle_custom_message(
//! #         &self, _msg: Self::CustomMessage, _sender_node_id: PublicKey
//! #     ) -> Result<(), LightningError> {
//! #         unimplemented!()
//! #     }
//! #     fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> {
//! #         unimplemented!()
//! #     }
//! #     fn peer_disconnected(&self, _their_node_id: PublicKey) {
//! #         unimplemented!()
//! #     }
//! #     fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> {
//! #         unimplemented!()
//! #     }
//! #     fn provided_node_features(&self) -> NodeFeatures {
//! #         unimplemented!()
//! #     }
//! #     fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures {
//! #         unimplemented!()
//! #     }
//! }
//!
//! // The first crate may define a handler composing `FooHandler` and `BarHandler` and export the
//! // corresponding message type ids as a macro to use in further composition.
//!
//! composite_custom_message_handler!(
//!     pub struct FooBarHandler {
//!         foo: FooHandler,
//!         bar: BarHandler,
//!     }
//!
//!     pub enum FooBarMessage {
//!         Foo(foo_type_id!()),
//!         Bar(bar_type_id!()),
//!     }
//! );
//!
//! #[macro_export]
//! macro_rules! foo_bar_type_ids {
//!     () => { foo_type_id!() | bar_type_id!() }
//! }
//!
//! // Another crate can then define a handler further composing `FooBarHandler` with `BazHandler`
//! // and similarly export the composition of message type ids as a macro.
//!
//! composite_custom_message_handler!(
//!     pub struct FooBarBazHandler {
//!         foo_bar: FooBarHandler,
//!         baz: BazHandler,
//!     }
//!
//!     pub enum FooBarBazMessage {
//!         FooBar(foo_bar_type_ids!()),
//!         Baz(baz_type_id!()),
//!     }
//! );
//!
//! #[macro_export]
//! macro_rules! foo_bar_baz_type_ids {
//!     () => { foo_bar_type_ids!() | baz_type_id!() }
//! }
//!```
//!
//! [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
//! [`CustomMessageHandler`]: crate::lightning::ln::peer_handler::CustomMessageHandler

#![doc(test(no_crate_inject, attr(deny(warnings))))]

pub extern crate bitcoin;
pub extern crate lightning;

/// Defines a composite type implementing [`CustomMessageHandler`] (and therefore also implementing
/// [`CustomMessageReader`]), along with a corresponding enumerated custom message [`Type`], from
/// one or more previously defined custom message handlers.
///
/// Useful for parameterizing [`PeerManager`] with custom message handling for one or more sets of
/// custom messages. Message type ids may be given as a valid `match` pattern, including ranges,
/// though using OR-ed literal patterns is preferred in order to catch unreachable code for
/// conflicting handlers.
///
/// See [crate documentation] for example usage.
///
/// [`CustomMessageHandler`]: crate::lightning::ln::peer_handler::CustomMessageHandler
/// [`CustomMessageReader`]: crate::lightning::ln::wire::CustomMessageReader
/// [`Type`]: crate::lightning::ln::wire::Type
/// [`PeerManager`]: crate::lightning::ln::peer_handler::PeerManager
/// [crate documentation]: self
#[macro_export]
macro_rules! composite_custom_message_handler {
	(
		$handler_visibility:vis struct $handler:ident {
			$($field_visibility:vis $field:ident: $type:ty),* $(,)*
		}

		$message_visibility:vis enum $message:ident {
			$($variant:ident($pattern:pat)),* $(,)*
		}
	) => {
		#[allow(missing_docs)]
		$handler_visibility struct $handler {
			$(
				$field_visibility $field: $type,
			)*
		}

		#[allow(missing_docs)]
		#[derive(Debug)]
		$message_visibility enum $message {
			$(
				$variant(<$type as $crate::lightning::ln::wire::CustomMessageReader>::CustomMessage),
			)*
		}

		impl $crate::lightning::ln::peer_handler::CustomMessageHandler for $handler {
			fn handle_custom_message(
				&self, msg: Self::CustomMessage, sender_node_id: $crate::bitcoin::secp256k1::PublicKey
			) -> Result<(), $crate::lightning::ln::msgs::LightningError> {
				match msg {
					$(
						$message::$variant(message) => {
							$crate::lightning::ln::peer_handler::CustomMessageHandler::handle_custom_message(
								&self.$field, message, sender_node_id
							)
						},
					)*
				}
			}

			fn get_and_clear_pending_msg(&self) -> Vec<($crate::bitcoin::secp256k1::PublicKey, Self::CustomMessage)> {
				vec![].into_iter()
					$(
						.chain(
							self.$field
								.get_and_clear_pending_msg()
								.into_iter()
								.map(|(pubkey, message)| (pubkey, $message::$variant(message)))
						)
					)*
					.collect()
			}

			fn peer_disconnected(&self, their_node_id: $crate::bitcoin::secp256k1::PublicKey) {
				$(
					self.$field.peer_disconnected(their_node_id);
				)*
			}

			fn peer_connected(&self, their_node_id: $crate::bitcoin::secp256k1::PublicKey, msg: &$crate::lightning::ln::msgs::Init, inbound: bool) -> Result<(), ()> {
				// Per the `CustomMessageHandler::peer_connected` contract, `peer_disconnected`
				// will not be called by `PeerManager` if we return `Err`. To avoid leaking
				// per-peer state in sub-handlers that already returned `Ok` when a later one
				// errors, record each sub-handler's result and roll back the successful ones
				// ourselves before propagating the failure.
				$(
					let $field = self.$field.peer_connected(their_node_id, msg, inbound);
				)*
				let any_err = false $( || $field.is_err() )*;
				if any_err {
					$(
						if $field.is_ok() {
							self.$field.peer_disconnected(their_node_id);
						}
					)*
					Err(())
				} else {
					Ok(())
				}
			}

			fn provided_node_features(&self) -> $crate::lightning::types::features::NodeFeatures {
				$crate::lightning::types::features::NodeFeatures::empty()
					$(
						| self.$field.provided_node_features()
					)*
			}

			fn provided_init_features(
				&self, their_node_id: $crate::bitcoin::secp256k1::PublicKey
			) -> $crate::lightning::types::features::InitFeatures {
				$crate::lightning::types::features::InitFeatures::empty()
					$(
						| self.$field.provided_init_features(their_node_id)
					)*
			}
		}

		impl $crate::lightning::ln::wire::CustomMessageReader for $handler {
			type CustomMessage = $message;
			fn read<R: $crate::lightning::util::ser::LengthLimitedRead>(
				&self, message_type: u16, buffer: &mut R
			) -> Result<Option<Self::CustomMessage>, $crate::lightning::ln::msgs::DecodeError> {
				match message_type {
					$(
						$pattern => match <$type>::read(&self.$field, message_type, buffer)? {
							// A sub-handler returns `None` for a `message_type` it doesn't
							// recognize. The composite's pattern can be broader than the types
							// the sub-handler decodes (e.g. a range), and `message_type` is
							// peer-provided, so report the message as unknown rather than
							// treating this as unreachable and panicking.
							None => Ok(None),
							Some(message) => Ok(Some($message::$variant(message))),
						},
					)*
					_ => Ok(None),
				}
			}
		}

		impl $crate::lightning::ln::wire::Type for $message {
			fn type_id(&self) -> u16 {
				match self {
					$(
						Self::$variant(message) => message.type_id(),
					)*
				}
			}
		}

		impl $crate::lightning::util::ser::Writeable for $message {
			fn write<W: $crate::lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::lightning::io::Error> {
				match self {
					$(
						Self::$variant(message) => message.write(writer),
					)*
				}
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use bitcoin::secp256k1::PublicKey;
	use core::sync::atomic::{AtomicUsize, Ordering};
	use lightning::io;
	use lightning::ln::msgs::{DecodeError, Init, LightningError};
	use lightning::ln::peer_handler::CustomMessageHandler;
	use lightning::ln::wire::{CustomMessageReader, Type};
	use lightning::types::features::{InitFeatures, NodeFeatures};
	use lightning::util::ser::{LengthLimitedRead, Writeable, Writer};

	#[derive(Debug)]
	pub struct Foo;
	impl Type for Foo {
		fn type_id(&self) -> u16 {
			32768
		}
	}
	impl Writeable for Foo {
		fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
			Ok(())
		}
	}

	pub struct CountingHandler {
		pub connect_count: AtomicUsize,
	}
	impl CustomMessageReader for CountingHandler {
		type CustomMessage = Foo;
		fn read<R: LengthLimitedRead>(
			&self, _t: u16, _b: &mut R,
		) -> Result<Option<Foo>, DecodeError> {
			Ok(None)
		}
	}
	impl CustomMessageHandler for CountingHandler {
		fn handle_custom_message(&self, _msg: Foo, _: PublicKey) -> Result<(), LightningError> {
			Ok(())
		}
		fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Foo)> {
			vec![]
		}
		fn peer_disconnected(&self, _: PublicKey) {
			self.connect_count.fetch_sub(1, Ordering::SeqCst);
		}
		fn peer_connected(&self, _: PublicKey, _: &Init, _: bool) -> Result<(), ()> {
			self.connect_count.fetch_add(1, Ordering::SeqCst);
			Ok(())
		}
		fn provided_node_features(&self) -> NodeFeatures {
			NodeFeatures::empty()
		}
		fn provided_init_features(&self, _: PublicKey) -> InitFeatures {
			InitFeatures::empty()
		}
	}

	#[derive(Debug)]
	pub struct Bar;
	impl Type for Bar {
		fn type_id(&self) -> u16 {
			32769
		}
	}
	impl Writeable for Bar {
		fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
			Ok(())
		}
	}

	pub struct ErroringHandler;
	impl CustomMessageReader for ErroringHandler {
		type CustomMessage = Bar;
		fn read<R: LengthLimitedRead>(
			&self, _t: u16, _b: &mut R,
		) -> Result<Option<Bar>, DecodeError> {
			Ok(None)
		}
	}
	impl CustomMessageHandler for ErroringHandler {
		fn handle_custom_message(&self, _msg: Bar, _: PublicKey) -> Result<(), LightningError> {
			Ok(())
		}
		fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Bar)> {
			vec![]
		}
		fn peer_disconnected(&self, _: PublicKey) {
			debug_assert!(false);
		}
		fn peer_connected(&self, _: PublicKey, _: &Init, _: bool) -> Result<(), ()> {
			Err(())
		}
		fn provided_node_features(&self) -> NodeFeatures {
			NodeFeatures::empty()
		}
		fn provided_init_features(&self, _: PublicKey) -> InitFeatures {
			InitFeatures::empty()
		}
	}

	composite_custom_message_handler!(
		pub struct CompositeHandler {
			counting: CountingHandler,
			erroring: ErroringHandler,
		}

		pub enum CompositeMessage {
			Foo(32768),
			Bar(32769),
		}
	);

	struct ReservedBlockHandler;
	impl CustomMessageReader for ReservedBlockHandler {
		type CustomMessage = Foo;
		fn read<R: LengthLimitedRead>(
			&self, message_type: u16, _b: &mut R,
		) -> Result<Option<Foo>, DecodeError> {
			// This build defines only the message at 32768; the rest of the block its
			// protocol reserved (32768..=32777) is for types future versions may add.
			// A not-yet-defined type is unknown to this build, so per the
			// `CustomMessageReader` contract it returns `Ok(None)` -- a newer peer can
			// send one and this older node will treat it as an unknown message.
			match message_type {
				32768 => Ok(Some(Foo)),
				_ => Ok(None),
			}
		}
	}
	impl CustomMessageHandler for ReservedBlockHandler {
		fn handle_custom_message(&self, _msg: Foo, _: PublicKey) -> Result<(), LightningError> {
			Ok(())
		}
		fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Foo)> {
			vec![]
		}
		fn peer_disconnected(&self, _: PublicKey) {}
		fn peer_connected(&self, _: PublicKey, _: &Init, _: bool) -> Result<(), ()> {
			Ok(())
		}
		fn provided_node_features(&self) -> NodeFeatures {
			NodeFeatures::empty()
		}
		fn provided_init_features(&self, _: PublicKey) -> InitFeatures {
			InitFeatures::empty()
		}
	}

	composite_custom_message_handler!(
		struct ReservedBlockComposite {
			proto: ReservedBlockHandler,
		}

		enum ReservedBlockMessage {
			Proto(32768..=32777),
		}
	);

	#[test]
	fn read_treats_a_reserved_in_range_type_as_unknown() {
		// A sub-handler may own a block of type ids (declared here as a range) yet only
		// decode the subset its build defines, returning `Ok(None)` for reserved or
		// not-yet-defined types in the block -- exactly what a node does on receiving a
		// newer peer's message. `read` must surface that as an unknown message, not
		// panic.
		let composite = ReservedBlockComposite { proto: ReservedBlockHandler };
		let mut buffer: &[u8] = &[];
		// The message this build defines decodes to its variant.
		assert!(matches!(
			composite.read(32768, &mut buffer),
			Ok(Some(ReservedBlockMessage::Proto(_)))
		));
		// A reserved type from the same block is reported unknown, not panicked
		// (pre-fix the matched arm hit `unreachable!()`).
		assert!(matches!(composite.read(32770, &mut buffer), Ok(None)));
	}

	#[test]
	fn peer_connected_failure_does_not_leak_subhandler_state() {
		let composite = CompositeHandler {
			counting: CountingHandler { connect_count: AtomicUsize::new(0) },
			erroring: ErroringHandler,
		};
		let pk_bytes = [
			0x02, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE,
			0x87, 0x0B, 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81,
			0x5B, 0x16, 0xF8, 0x17, 0x98,
		];
		let pk = PublicKey::from_slice(&pk_bytes).unwrap();
		let init =
			Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };

		let result = composite.peer_connected(pk, &init, true);
		assert!(result.is_err(), "Composite must propagate the inner Err");

		let leaked = composite.counting.connect_count.load(Ordering::SeqCst);
		assert_eq!(
			leaked, 0,
			"CountingHandler tracked {leaked} connected peer(s) after the composite \
			 returned Err; this state will never be cleaned up because per the trait \
			 contract peer_disconnected won't be called when peer_connected returns Err.",
		);
	}
}