lightning_types/
features.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//! Feature flag definitions for the Lightning protocol according to [BOLT #9].
11//!
12//! Lightning nodes advertise a supported set of operation through feature flags. Features are
13//! applicable for a specific context. [`Features`] encapsulates behavior for specifying and
14//! checking feature flags for a particular context. Each feature is defined internally by a trait
15//! specifying the corresponding flags (i.e., even and odd bits).
16//!
17//! Whether a feature is considered "known" or "unknown" is relative to the implementation, whereas
18//! the term "supports" is used in reference to a particular set of [`Features`]. That is, a node
19//! supports a feature if it advertises the feature (as either required or optional) to its peers.
20//! And the implementation can interpret a feature if the feature is known to it.
21//!
22//! The following features are currently required in the LDK:
23//! - `VariableLengthOnion` - requires/supports variable-length routing onion payloads
24//!     (see [BOLT-4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md) for more information).
25//! - `StaticRemoteKey` - requires/supports static key for remote output
26//!     (see [BOLT-3](https://github.com/lightning/bolts/blob/master/03-transactions.md) for more information).
27//!
28//! The following features are currently supported in the LDK:
29//! - `DataLossProtect` - requires/supports that a node which has somehow fallen behind, e.g., has been restored from an old backup,
30//!     can detect that it has fallen behind
31//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
32//! - `InitialRoutingSync` - requires/supports that the sending node needs a complete routing information dump
33//!     (see [BOLT-7](https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#initial-sync) for more information).
34//! - `UpfrontShutdownScript` - commits to a shutdown scriptpubkey when opening a channel
35//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message) for more information).
36//! - `GossipQueries` - requires/supports more sophisticated gossip control
37//!     (see [BOLT-7](https://github.com/lightning/bolts/blob/master/07-routing-gossip.md) for more information).
38//! - `PaymentSecret` - requires/supports that a node supports payment_secret field
39//!     (see [BOLT-4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md) for more information).
40//! - `BasicMPP` - requires/supports that a node can receive basic multi-part payments
41//!     (see [BOLT-4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md#basic-multi-part-payments) for more information).
42//! - `Wumbo` - requires/supports that a node create large channels. Called `option_support_large_channel` in the spec.
43//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message) for more information).
44//! - `AnchorsZeroFeeHtlcTx` - requires/supports that commitment transactions include anchor outputs
45//!     and HTLC transactions are pre-signed with zero fee (see
46//!     [BOLT-3](https://github.com/lightning/bolts/blob/master/03-transactions.md) for more
47//!     information).
48//! - `RouteBlinding` - requires/supports that a node can relay payments over blinded paths
49//!     (see [BOLT-4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md#route-blinding) for more information).
50//! - `ShutdownAnySegwit` - requires/supports that future segwit versions are allowed in `shutdown`
51//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
52//! - `DualFund` - requires/supports V2 channel establishment
53//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#channel-establishment-v2) for more information).
54//! - `OnionMessages` - requires/supports forwarding onion messages
55//!     (see [BOLT-7](https://github.com/lightning/bolts/pull/759/files) for more information).
56//     TODO: update link
57//! - `ChannelType` - node supports the channel_type field in open/accept
58//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
59//! - `SCIDPrivacy` - supply channel aliases for routing
60//!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
61//! - `PaymentMetadata` - include additional data in invoices which is passed to recipients in the
62//!      onion.
63//!      (see [BOLT-11](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md) for
64//!      more).
65//! - `ZeroConf` - supports accepting HTLCs and using channels prior to funding confirmation
66//!      (see
67//!      [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message)
68//!      for more info).
69//! - `Keysend` - send funds to a node without an invoice
70//!     (see the [`Keysend` feature assignment proposal](https://github.com/lightning/bolts/issues/605#issuecomment-606679798) for more information).
71//! - `Trampoline` - supports receiving and forwarding Trampoline payments
72//!     (see the [`Trampoline` feature proposal](https://github.com/lightning/bolts/pull/836) for more information).
73//! - `DnsResolver` - supports resolving DNS names to TXT DNSSEC proofs for BIP 353 payments
74//!     (see [bLIP 32](https://github.com/lightning/blips/blob/master/blip-0032.md) for more information).
75//!
76//! LDK knows about the following features, but does not support them:
77//! - `AnchorsNonzeroFeeHtlcTx` - the initial version of anchor outputs, which was later found to be
78//!     vulnerable (see this
79//!     [mailing list post](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-September/002796.html)
80//!     for more information).
81//!
82//! [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
83
84use core::borrow::Borrow;
85use core::hash::{Hash, Hasher};
86use core::marker::PhantomData;
87use core::{cmp, fmt};
88
89use alloc::vec::Vec;
90
91mod sealed {
92	use super::Features;
93
94	use alloc::vec::Vec;
95
96	/// The context in which [`Features`] are applicable. Defines which features are known to the
97	/// implementation, though specification of them as required or optional is up to the code
98	/// constructing a features object.
99	pub trait Context {
100		/// Bitmask for selecting features that are known to the implementation.
101		const KNOWN_FEATURE_MASK: &'static [u8];
102	}
103
104	/// Defines a [`Context`] by stating which features it requires and which are optional. Features
105	/// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
106	/// feature identifiers.
107	macro_rules! define_context {
108		($context: ident, [$( $( $known_feature: ident )|*, )*]) => {
109			#[derive(Eq, PartialEq)]
110			pub struct $context {}
111
112			impl Context for $context {
113				const KNOWN_FEATURE_MASK: &'static [u8] = &[
114					$(
115						0b00_00_00_00 $(|
116							<Self as $known_feature>::REQUIRED_MASK |
117							<Self as $known_feature>::OPTIONAL_MASK)*,
118					)*
119				];
120			}
121
122			impl alloc::fmt::Display for Features<$context> {
123				fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
124					$(
125						$(
126							fmt.write_fmt(format_args!("{}: {}, ", stringify!($known_feature),
127								if <$context as $known_feature>::requires_feature(&self.flags) { "required" }
128								else if <$context as $known_feature>::supports_feature(&self.flags) { "supported" }
129								else { "not supported" }))?;
130						)*
131						{} // Rust gets mad if we only have a $()* block here, so add a dummy {}
132					)*
133					fmt.write_fmt(format_args!("unknown flags: {}",
134						if self.requires_unknown_bits() { "required" }
135						else if self.supports_unknown_bits() { "supported" } else { "none" }))
136				}
137			}
138		};
139	}
140
141	define_context!(
142		InitContext,
143		[
144			// Byte 0
145			DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
146			// Byte 1
147			VariableLengthOnion | StaticRemoteKey | PaymentSecret,
148			// Byte 2
149			BasicMPP | Wumbo | AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
150			// Byte 3
151			RouteBlinding | ShutdownAnySegwit | DualFund | Taproot,
152			// Byte 4
153			OnionMessages,
154			// Byte 5
155			ChannelType | SCIDPrivacy,
156			// Byte 6
157			ZeroConf,
158			// Byte 7
159			Trampoline,
160		]
161	);
162	define_context!(
163		NodeContext,
164		[
165			// Byte 0
166			DataLossProtect | UpfrontShutdownScript | GossipQueries,
167			// Byte 1
168			VariableLengthOnion | StaticRemoteKey | PaymentSecret,
169			// Byte 2
170			BasicMPP | Wumbo | AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
171			// Byte 3
172			RouteBlinding | ShutdownAnySegwit | DualFund | Taproot,
173			// Byte 4
174			OnionMessages,
175			// Byte 5
176			ChannelType | SCIDPrivacy,
177			// Byte 6
178			ZeroConf | Keysend,
179			// Byte 7
180			Trampoline,
181			// Byte 8 - 31
182			,,,,,,,,,,,,,,,,,,,,,,,,
183			// Byte 32
184			DnsResolver,
185		]
186	);
187	define_context!(ChannelContext, []);
188	define_context!(Bolt11InvoiceContext, [
189		// Byte 0
190		,
191		// Byte 1
192		VariableLengthOnion | PaymentSecret,
193		// Byte 2
194		BasicMPP,
195		// Byte 3
196		,
197		// Byte 4
198		,
199		// Byte 5
200		,
201		// Byte 6
202		PaymentMetadata,
203		// Byte 7
204		Trampoline,
205	]);
206	define_context!(OfferContext, []);
207	define_context!(InvoiceRequestContext, []);
208	define_context!(Bolt12InvoiceContext, [
209		// Byte 0
210		,
211		// Byte 1
212		,
213		// Byte 2
214		BasicMPP,
215		// Byte 3
216		,
217		// Byte 4
218		,
219		// Byte 5
220		,
221		// Byte 6
222		,
223		// Byte 7
224		Trampoline,
225	]);
226	define_context!(BlindedHopContext, []);
227	// This isn't a "real" feature context, and is only used in the channel_type field in an
228	// `OpenChannel` message.
229	define_context!(ChannelTypeContext, [
230		// Byte 0
231		,
232		// Byte 1
233		StaticRemoteKey,
234		// Byte 2
235		AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
236		// Byte 3
237		Taproot,
238		// Byte 4
239		,
240		// Byte 5
241		SCIDPrivacy,
242		// Byte 6
243		ZeroConf,
244	]);
245
246	/// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
247	/// useful for manipulating feature flags.
248	macro_rules! define_feature {
249		($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
250		 $required_setter: ident, $supported_getter: ident) => {
251			#[doc = $doc]
252			///
253			/// See [BOLT #9] for details.
254			///
255			/// [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
256			pub trait $feature: Context {
257				/// The bit used to signify that the feature is required.
258				const EVEN_BIT: usize = $odd_bit - 1;
259
260				/// The bit used to signify that the feature is optional.
261				const ODD_BIT: usize = $odd_bit;
262
263				/// Assertion that [`EVEN_BIT`] is actually even.
264				///
265				/// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
266				const ASSERT_EVEN_BIT_PARITY: usize;
267
268				/// Assertion that [`ODD_BIT`] is actually odd.
269				///
270				/// [`ODD_BIT`]: #associatedconstant.ODD_BIT
271				const ASSERT_ODD_BIT_PARITY: usize;
272
273				/// Assertion that the bits are set in the context's [`KNOWN_FEATURE_MASK`].
274				///
275				/// [`KNOWN_FEATURE_MASK`]: Context::KNOWN_FEATURE_MASK
276				#[cfg(not(any(test, feature = "_test_utils")))] // We violate this constraint with `UnknownFeature`
277				const ASSERT_BITS_IN_MASK: u8;
278
279				/// The byte where the feature is set.
280				const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
281
282				/// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
283				///
284				/// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
285				const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
286
287				/// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
288				///
289				/// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
290				const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
291
292				/// Returns whether the feature is required by the given flags.
293				#[inline]
294				fn requires_feature(flags: &Vec<u8>) -> bool {
295					flags.len() > Self::BYTE_OFFSET &&
296						(flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
297				}
298
299				/// Returns whether the feature is supported by the given flags.
300				#[inline]
301				fn supports_feature(flags: &Vec<u8>) -> bool {
302					flags.len() > Self::BYTE_OFFSET &&
303						(flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
304				}
305
306				/// Sets the feature's required (even) bit in the given flags.
307				#[inline]
308				fn set_required_bit(flags: &mut Vec<u8>) {
309					if flags.len() <= Self::BYTE_OFFSET {
310						flags.resize(Self::BYTE_OFFSET + 1, 0u8);
311					}
312
313					flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
314					flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
315				}
316
317				/// Sets the feature's optional (odd) bit in the given flags.
318				#[inline]
319				fn set_optional_bit(flags: &mut Vec<u8>) {
320					if flags.len() <= Self::BYTE_OFFSET {
321						flags.resize(Self::BYTE_OFFSET + 1, 0u8);
322					}
323
324					flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
325				}
326
327				/// Clears the feature's required (even) and optional (odd) bits from the given
328				/// flags.
329				#[inline]
330				fn clear_bits(flags: &mut Vec<u8>) {
331					if flags.len() > Self::BYTE_OFFSET {
332						flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
333						flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
334					}
335
336					let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
337					let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
338					flags.resize(size, 0u8);
339				}
340			}
341
342			impl <T: $feature> Features<T> {
343				/// Set this feature as optional.
344				pub fn $optional_setter(&mut self) {
345					<T as $feature>::set_optional_bit(&mut self.flags);
346				}
347
348				/// Set this feature as required.
349				pub fn $required_setter(&mut self) {
350					<T as $feature>::set_required_bit(&mut self.flags);
351				}
352
353				/// Checks if this feature is supported.
354				pub fn $supported_getter(&self) -> bool {
355					<T as $feature>::supports_feature(&self.flags)
356				}
357			}
358
359			$(
360				impl $feature for $context {
361					// EVEN_BIT % 2 == 0
362					const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
363
364					// ODD_BIT % 2 == 1
365					const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
366
367					// (byte & (REQUIRED_MASK | OPTIONAL_MASK)) >> (EVEN_BIT % 8) == 3
368					#[cfg(not(any(test, feature = "_test_utils")))] // We violate this constraint with `UnknownFeature`
369					const ASSERT_BITS_IN_MASK: u8 =
370						((<$context>::KNOWN_FEATURE_MASK[<Self as $feature>::BYTE_OFFSET] & (<Self as $feature>::REQUIRED_MASK | <Self as $feature>::OPTIONAL_MASK))
371						 >> (<Self as $feature>::EVEN_BIT % 8)) - 3;
372				}
373			)*
374		};
375		($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
376		 $required_setter: ident, $supported_getter: ident, $required_getter: ident) => {
377			define_feature!($odd_bit, $feature, [$($context),+], $doc, $optional_setter, $required_setter, $supported_getter);
378			impl <T: $feature> Features<T> {
379				/// Checks if this feature is required.
380				pub fn $required_getter(&self) -> bool {
381					<T as $feature>::requires_feature(&self.flags)
382				}
383			}
384		}
385	}
386
387	define_feature!(
388		1,
389		DataLossProtect,
390		[InitContext, NodeContext],
391		"Feature flags for `option_data_loss_protect`.",
392		set_data_loss_protect_optional,
393		set_data_loss_protect_required,
394		supports_data_loss_protect,
395		requires_data_loss_protect
396	);
397	// NOTE: Per Bolt #9, initial_routing_sync has no even bit.
398	define_feature!(
399		3,
400		InitialRoutingSync,
401		[InitContext],
402		"Feature flags for `initial_routing_sync`.",
403		set_initial_routing_sync_optional,
404		set_initial_routing_sync_required,
405		initial_routing_sync
406	);
407	define_feature!(
408		5,
409		UpfrontShutdownScript,
410		[InitContext, NodeContext],
411		"Feature flags for `option_upfront_shutdown_script`.",
412		set_upfront_shutdown_script_optional,
413		set_upfront_shutdown_script_required,
414		supports_upfront_shutdown_script,
415		requires_upfront_shutdown_script
416	);
417	define_feature!(
418		7,
419		GossipQueries,
420		[InitContext, NodeContext],
421		"Feature flags for `gossip_queries`.",
422		set_gossip_queries_optional,
423		set_gossip_queries_required,
424		supports_gossip_queries,
425		requires_gossip_queries
426	);
427	define_feature!(
428		9,
429		VariableLengthOnion,
430		[InitContext, NodeContext, Bolt11InvoiceContext],
431		"Feature flags for `var_onion_optin`.",
432		set_variable_length_onion_optional,
433		set_variable_length_onion_required,
434		supports_variable_length_onion,
435		requires_variable_length_onion
436	);
437	define_feature!(
438		13,
439		StaticRemoteKey,
440		[InitContext, NodeContext, ChannelTypeContext],
441		"Feature flags for `option_static_remotekey`.",
442		set_static_remote_key_optional,
443		set_static_remote_key_required,
444		supports_static_remote_key,
445		requires_static_remote_key
446	);
447	define_feature!(
448		15,
449		PaymentSecret,
450		[InitContext, NodeContext, Bolt11InvoiceContext],
451		"Feature flags for `payment_secret`.",
452		set_payment_secret_optional,
453		set_payment_secret_required,
454		supports_payment_secret,
455		requires_payment_secret
456	);
457	define_feature!(
458		17,
459		BasicMPP,
460		[InitContext, NodeContext, Bolt11InvoiceContext, Bolt12InvoiceContext],
461		"Feature flags for `basic_mpp`.",
462		set_basic_mpp_optional,
463		set_basic_mpp_required,
464		supports_basic_mpp,
465		requires_basic_mpp
466	);
467	define_feature!(
468		19,
469		Wumbo,
470		[InitContext, NodeContext],
471		"Feature flags for `option_support_large_channel` (aka wumbo channels).",
472		set_wumbo_optional,
473		set_wumbo_required,
474		supports_wumbo,
475		requires_wumbo
476	);
477	define_feature!(
478		21,
479		AnchorsNonzeroFeeHtlcTx,
480		[InitContext, NodeContext, ChannelTypeContext],
481		"Feature flags for `option_anchors_nonzero_fee_htlc_tx`.",
482		set_anchors_nonzero_fee_htlc_tx_optional,
483		set_anchors_nonzero_fee_htlc_tx_required,
484		supports_anchors_nonzero_fee_htlc_tx,
485		requires_anchors_nonzero_fee_htlc_tx
486	);
487	define_feature!(
488		23,
489		AnchorsZeroFeeHtlcTx,
490		[InitContext, NodeContext, ChannelTypeContext],
491		"Feature flags for `option_anchors_zero_fee_htlc_tx`.",
492		set_anchors_zero_fee_htlc_tx_optional,
493		set_anchors_zero_fee_htlc_tx_required,
494		supports_anchors_zero_fee_htlc_tx,
495		requires_anchors_zero_fee_htlc_tx
496	);
497	define_feature!(
498		25,
499		RouteBlinding,
500		[InitContext, NodeContext],
501		"Feature flags for `option_route_blinding`.",
502		set_route_blinding_optional,
503		set_route_blinding_required,
504		supports_route_blinding,
505		requires_route_blinding
506	);
507	define_feature!(
508		27,
509		ShutdownAnySegwit,
510		[InitContext, NodeContext],
511		"Feature flags for `opt_shutdown_anysegwit`.",
512		set_shutdown_any_segwit_optional,
513		set_shutdown_any_segwit_required,
514		supports_shutdown_anysegwit,
515		requires_shutdown_anysegwit
516	);
517	define_feature!(
518		29,
519		DualFund,
520		[InitContext, NodeContext],
521		"Feature flags for `option_dual_fund`.",
522		set_dual_fund_optional,
523		set_dual_fund_required,
524		supports_dual_fund,
525		requires_dual_fund
526	);
527	define_feature!(
528		31,
529		Taproot,
530		[InitContext, NodeContext, ChannelTypeContext],
531		"Feature flags for `option_taproot`.",
532		set_taproot_optional,
533		set_taproot_required,
534		supports_taproot,
535		requires_taproot
536	);
537	define_feature!(
538		39,
539		OnionMessages,
540		[InitContext, NodeContext],
541		"Feature flags for `option_onion_messages`.",
542		set_onion_messages_optional,
543		set_onion_messages_required,
544		supports_onion_messages,
545		requires_onion_messages
546	);
547	define_feature!(
548		45,
549		ChannelType,
550		[InitContext, NodeContext],
551		"Feature flags for `option_channel_type`.",
552		set_channel_type_optional,
553		set_channel_type_required,
554		supports_channel_type,
555		requires_channel_type
556	);
557	define_feature!(47, SCIDPrivacy, [InitContext, NodeContext, ChannelTypeContext],
558		"Feature flags for only forwarding with SCID aliasing. Called `option_scid_alias` in the BOLTs",
559		set_scid_privacy_optional, set_scid_privacy_required, supports_scid_privacy, requires_scid_privacy);
560	define_feature!(
561		49,
562		PaymentMetadata,
563		[Bolt11InvoiceContext],
564		"Feature flags for payment metadata in invoices.",
565		set_payment_metadata_optional,
566		set_payment_metadata_required,
567		supports_payment_metadata,
568		requires_payment_metadata
569	);
570	define_feature!(51, ZeroConf, [InitContext, NodeContext, ChannelTypeContext],
571		"Feature flags for accepting channels with zero confirmations. Called `option_zeroconf` in the BOLTs",
572		set_zero_conf_optional, set_zero_conf_required, supports_zero_conf, requires_zero_conf);
573	define_feature!(
574		55,
575		Keysend,
576		[NodeContext],
577		"Feature flags for keysend payments.",
578		set_keysend_optional,
579		set_keysend_required,
580		supports_keysend,
581		requires_keysend
582	);
583	define_feature!(
584		57,
585		Trampoline,
586		[InitContext, NodeContext, Bolt11InvoiceContext, Bolt12InvoiceContext],
587		"Feature flags for Trampoline routing.",
588		set_trampoline_routing_optional,
589		set_trampoline_routing_required,
590		supports_trampoline_routing,
591		requires_trampoline_routing
592	);
593	define_feature!(
594		259,
595		DnsResolver,
596		[NodeContext],
597		"Feature flags for DNS resolving.",
598		set_dns_resolution_optional,
599		set_dns_resolution_required,
600		supports_dns_resolution,
601		requires_dns_resolution
602	);
603
604	// Note: update the module-level docs when a new feature bit is added!
605
606	#[cfg(any(test, feature = "_test_utils"))]
607	define_feature!(
608		12345,
609		UnknownFeature,
610		[
611			NodeContext,
612			ChannelContext,
613			Bolt11InvoiceContext,
614			OfferContext,
615			InvoiceRequestContext,
616			Bolt12InvoiceContext,
617			BlindedHopContext
618		],
619		"Feature flags for an unknown feature used in testing.",
620		set_unknown_feature_optional,
621		set_unknown_feature_required,
622		supports_unknown_test_feature,
623		requires_unknown_test_feature
624	);
625}
626
627const ANY_REQUIRED_FEATURES_MASK: u8 = 0b01_01_01_01;
628const ANY_OPTIONAL_FEATURES_MASK: u8 = 0b10_10_10_10;
629
630/// Tracks the set of features which a node implements, templated by the context in which it
631/// appears.
632///
633/// This is not exported to bindings users as we map the concrete feature types below directly instead
634#[derive(Eq)]
635pub struct Features<T: sealed::Context> {
636	/// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
637	flags: Vec<u8>,
638	mark: PhantomData<T>,
639}
640
641impl<T: sealed::Context, Rhs: Borrow<Self>> core::ops::BitOrAssign<Rhs> for Features<T> {
642	fn bitor_assign(&mut self, rhs: Rhs) {
643		let total_feature_len = cmp::max(self.flags.len(), rhs.borrow().flags.len());
644		self.flags.resize(total_feature_len, 0u8);
645		for (byte, rhs_byte) in self.flags.iter_mut().zip(rhs.borrow().flags.iter()) {
646			*byte |= *rhs_byte;
647		}
648	}
649}
650
651impl<T: sealed::Context> core::ops::BitOr for Features<T> {
652	type Output = Self;
653
654	fn bitor(mut self, o: Self) -> Self {
655		self |= o;
656		self
657	}
658}
659
660impl<T: sealed::Context> Clone for Features<T> {
661	fn clone(&self) -> Self {
662		Self { flags: self.flags.clone(), mark: PhantomData }
663	}
664}
665impl<T: sealed::Context> Hash for Features<T> {
666	fn hash<H: Hasher>(&self, hasher: &mut H) {
667		let mut nonzero_flags = &self.flags[..];
668		while nonzero_flags.last() == Some(&0) {
669			nonzero_flags = &nonzero_flags[..nonzero_flags.len() - 1];
670		}
671		nonzero_flags.hash(hasher);
672	}
673}
674impl<T: sealed::Context> PartialEq for Features<T> {
675	fn eq(&self, o: &Self) -> bool {
676		let mut o_iter = o.flags.iter();
677		let mut self_iter = self.flags.iter();
678		loop {
679			match (o_iter.next(), self_iter.next()) {
680				(Some(o), Some(us)) => {
681					if o != us {
682						return false;
683					}
684				},
685				(Some(b), None) | (None, Some(b)) => {
686					if *b != 0 {
687						return false;
688					}
689				},
690				(None, None) => return true,
691			}
692		}
693	}
694}
695impl<T: sealed::Context> PartialOrd for Features<T> {
696	fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
697		self.flags.partial_cmp(&other.flags)
698	}
699}
700impl<T: sealed::Context + Eq> Ord for Features<T> {
701	fn cmp(&self, other: &Self) -> cmp::Ordering {
702		self.flags.cmp(&other.flags)
703	}
704}
705impl<T: sealed::Context> fmt::Debug for Features<T> {
706	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
707		self.flags.fmt(fmt)
708	}
709}
710
711/// Features used within an `init` message.
712pub type InitFeatures = Features<sealed::InitContext>;
713/// Features used within a `node_announcement` message.
714pub type NodeFeatures = Features<sealed::NodeContext>;
715/// Features used within a `channel_announcement` message.
716pub type ChannelFeatures = Features<sealed::ChannelContext>;
717/// Features used within an invoice.
718pub type Bolt11InvoiceFeatures = Features<sealed::Bolt11InvoiceContext>;
719/// Features used within an `offer`.
720pub type OfferFeatures = Features<sealed::OfferContext>;
721/// Features used within an `invoice_request`.
722pub type InvoiceRequestFeatures = Features<sealed::InvoiceRequestContext>;
723/// Features used within an `invoice`.
724pub type Bolt12InvoiceFeatures = Features<sealed::Bolt12InvoiceContext>;
725/// Features used within BOLT 4 encrypted_data_tlv and BOLT 12 blinded_payinfo
726pub type BlindedHopFeatures = Features<sealed::BlindedHopContext>;
727
728/// Features used within the channel_type field in an OpenChannel message.
729///
730/// A channel is always of some known "type", describing the transaction formats used and the exact
731/// semantics of our interaction with our peer.
732///
733/// Note that because a channel is a specific type which is proposed by the opener and accepted by
734/// the counterparty, only required features are allowed here.
735///
736/// This is serialized differently from other feature types - it is not prefixed by a length, and
737/// thus must only appear inside a TLV where its length is known in advance.
738pub type ChannelTypeFeatures = Features<sealed::ChannelTypeContext>;
739
740impl InitFeatures {
741	#[doc(hidden)]
742	/// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
743	/// are included in the result.
744	///
745	/// This is not exported to bindings users as it shouldn't be used outside of LDK
746	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
747		self.to_context_internal()
748	}
749}
750
751impl Bolt11InvoiceFeatures {
752	#[doc(hidden)]
753	/// Converts `Bolt11InvoiceFeatures` to `Features<C>`. Only known `Bolt11InvoiceFeatures` relevant to
754	/// context `C` are included in the result.
755	///
756	/// This is not exported to bindings users as it shouldn't be used outside of LDK
757	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
758		self.to_context_internal()
759	}
760
761	/// Getting a route for a keysend payment to a private node requires providing the payee's
762	/// features (since they were not announced in a node announcement). However, keysend payments
763	/// don't have an invoice to pull the payee's features from, so this method is provided for use
764	/// when a [`Bolt11InvoiceFeatures`] is required in a route.
765	///
766	/// MPP keysend is not widely supported yet, so we parameterize support to allow the user to
767	/// choose whether their router should find multi-part routes.
768	pub fn for_keysend(allow_mpp: bool) -> Bolt11InvoiceFeatures {
769		let mut res = Bolt11InvoiceFeatures::empty();
770		res.set_variable_length_onion_optional();
771		if allow_mpp {
772			res.set_basic_mpp_optional();
773		}
774		res
775	}
776}
777
778impl Bolt12InvoiceFeatures {
779	#[doc(hidden)]
780	/// Converts [`Bolt12InvoiceFeatures`] to [`Features<C>`]. Only known [`Bolt12InvoiceFeatures`]
781	/// relevant to context `C` are included in the result.
782	///
783	/// This is not exported to bindings users as it shouldn't be used outside of LDK
784	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
785		self.to_context_internal()
786	}
787}
788
789impl ChannelTypeFeatures {
790	#[doc(hidden)]
791	/// Maps the relevant `InitFeatures` to `ChannelTypeFeatures`. Any unknown features to
792	/// `ChannelTypeFeatures` are not included in the result.
793	///
794	/// This is not exported to bindings users as it shouldn't be used outside of LDK
795	pub fn from_init(init: &InitFeatures) -> Self {
796		let mut ret = init.to_context_internal();
797		// ChannelTypeFeatures must only contain required bits, so we OR the required forms of all
798		// optional bits and then AND out the optional ones.
799		for byte in ret.flags.iter_mut() {
800			*byte |= (*byte & ANY_OPTIONAL_FEATURES_MASK) >> 1;
801			*byte &= ANY_REQUIRED_FEATURES_MASK;
802		}
803		ret
804	}
805
806	/// Constructs a ChannelTypeFeatures with only static_remotekey set
807	pub fn only_static_remote_key() -> Self {
808		let mut ret = Self::empty();
809		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret.flags);
810		ret
811	}
812
813	/// Constructs a ChannelTypeFeatures with anchors support
814	pub fn anchors_zero_htlc_fee_and_dependencies() -> Self {
815		let mut ret = Self::empty();
816		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret.flags);
817		<sealed::ChannelTypeContext as sealed::AnchorsZeroFeeHtlcTx>::set_required_bit(
818			&mut ret.flags,
819		);
820		ret
821	}
822}
823
824impl<T: sealed::Context> Features<T> {
825	/// Create a blank Features with no features set
826	pub fn empty() -> Self {
827		Features { flags: Vec::new(), mark: PhantomData }
828	}
829
830	/// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
831	/// included in the result.
832	fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
833		let from_byte_count = T::KNOWN_FEATURE_MASK.len();
834		let to_byte_count = C::KNOWN_FEATURE_MASK.len();
835		let mut flags = Vec::new();
836		for (i, byte) in self.flags.iter().enumerate() {
837			if i < from_byte_count && i < to_byte_count {
838				let from_known_features = T::KNOWN_FEATURE_MASK[i];
839				let to_known_features = C::KNOWN_FEATURE_MASK[i];
840				flags.push(byte & from_known_features & to_known_features);
841			}
842		}
843		Features::<C> { flags, mark: PhantomData }
844	}
845
846	/// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
847	/// most on-the-wire encodings.
848	///
849	/// This is not exported to bindings users as we don't support export across multiple T
850	pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
851		Features { flags, mark: PhantomData }
852	}
853
854	/// Returns the feature set as a list of bytes, in little-endian. This is in reverse byte order
855	/// from most on-the-wire encodings.
856	pub fn le_flags(&self) -> &[u8] {
857		&self.flags
858	}
859
860	/// Create a [`Features`] given a set of flags, in big-endian. This is in byte order from
861	/// most on-the-wire encodings.
862	///
863	/// This is not exported to bindings users as we don't support export across multiple T
864	pub fn from_be_bytes(mut flags: Vec<u8>) -> Features<T> {
865		flags.reverse(); // Swap to little-endian
866		Self { flags, mark: PhantomData }
867	}
868
869	/// Returns true if this `Features` has any optional flags set
870	pub fn supports_any_optional_bits(&self) -> bool {
871		self.flags.iter().any(|&byte| (byte & ANY_OPTIONAL_FEATURES_MASK) != 0)
872	}
873
874	/// Returns true if this `Features` object contains required features unknown by `other`.
875	pub fn requires_unknown_bits_from(&self, other: &Self) -> bool {
876		// Bitwise AND-ing with all even bits set except for known features will select required
877		// unknown features.
878		self.flags.iter().enumerate().any(|(i, &byte)| {
879			let unknown_features = unset_features_mask_at_position(other, i);
880			(byte & (ANY_REQUIRED_FEATURES_MASK & unknown_features)) != 0
881		})
882	}
883
884	/// Returns the set of required features unknown by `other`, as their bit position.
885	pub fn required_unknown_bits_from(&self, other: &Self) -> Vec<u64> {
886		let mut unknown_bits = Vec::new();
887
888		// Bitwise AND-ing with all even bits set except for known features will select required
889		// unknown features.
890		self.flags.iter().enumerate().for_each(|(i, &byte)| {
891			let unknown_features = unset_features_mask_at_position(other, i);
892			if byte & unknown_features != 0 {
893				for bit in (0..8).step_by(2) {
894					if ((byte & unknown_features) >> bit) & 1 == 1 {
895						unknown_bits.push((i as u64) * 8 + bit);
896					}
897				}
898			}
899		});
900
901		unknown_bits
902	}
903
904	/// Returns true if this `Features` object contains unknown feature flags which are set as
905	/// "required".
906	pub fn requires_unknown_bits(&self) -> bool {
907		// Bitwise AND-ing with all even bits set except for known features will select required
908		// unknown features.
909		let mut known_chunks = T::KNOWN_FEATURE_MASK.chunks(8);
910		for chunk in self.flags.chunks(8) {
911			let mut flag_bytes = [0; 8];
912			flag_bytes[..chunk.len()].copy_from_slice(&chunk);
913			let flag_int = u64::from_le_bytes(flag_bytes);
914
915			let known_chunk = known_chunks.next().unwrap_or(&[0; 0]);
916			let mut known_bytes = [0; 8];
917			known_bytes[..known_chunk.len()].copy_from_slice(&known_chunk);
918			let known_int = u64::from_le_bytes(known_bytes);
919
920			const REQ_MASK: u64 = u64::from_le_bytes([ANY_REQUIRED_FEATURES_MASK; 8]);
921			if flag_int & (REQ_MASK & !known_int) != 0 {
922				return true;
923			}
924		}
925		false
926	}
927
928	/// Returns true if this `Features` supports any bits which we do not know of
929	pub fn supports_unknown_bits(&self) -> bool {
930		// Bitwise AND-ing with all even and odd bits set except for known features will select
931		// both required and optional unknown features.
932		let byte_count = T::KNOWN_FEATURE_MASK.len();
933		self.flags.iter().enumerate().any(|(i, &byte)| {
934			let unknown_features =
935				if i < byte_count { !T::KNOWN_FEATURE_MASK[i] } else { 0b11_11_11_11 };
936			(byte & unknown_features) != 0
937		})
938	}
939
940	/// Sets a required feature bit. Errors if `bit` is outside the feature range as defined
941	/// by [BOLT 9].
942	///
943	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
944	/// be set instead (i.e., `bit - 1`).
945	///
946	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
947	pub fn set_required_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
948		self.set_feature_bit(bit - (bit % 2))
949	}
950
951	/// Sets an optional feature bit. Errors if `bit` is outside the feature range as defined
952	/// by [BOLT 9].
953	///
954	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
955	/// set instead (i.e., `bit + 1`).
956	///
957	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
958	pub fn set_optional_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
959		self.set_feature_bit(bit + (1 - (bit % 2)))
960	}
961
962	fn set_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
963		if bit > 255 {
964			return Err(());
965		}
966		self.set_bit(bit, false)
967	}
968
969	/// Sets a required custom feature bit. Errors if `bit` is outside the custom range as defined
970	/// by [bLIP 2] or if it is a known `T` feature.
971	///
972	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
973	/// be set instead (i.e., `bit - 1`).
974	///
975	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
976	pub fn set_required_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
977		self.set_custom_bit(bit - (bit % 2))
978	}
979
980	/// Sets an optional custom feature bit. Errors if `bit` is outside the custom range as defined
981	/// by [bLIP 2] or if it is a known `T` feature.
982	///
983	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
984	/// set instead (i.e., `bit + 1`).
985	///
986	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
987	pub fn set_optional_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
988		self.set_custom_bit(bit + (1 - (bit % 2)))
989	}
990
991	fn set_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
992		if bit < 256 {
993			return Err(());
994		}
995		self.set_bit(bit, true)
996	}
997
998	fn set_bit(&mut self, bit: usize, custom: bool) -> Result<(), ()> {
999		let byte_offset = bit / 8;
1000		let mask = 1 << (bit - 8 * byte_offset);
1001		if byte_offset < T::KNOWN_FEATURE_MASK.len() && custom {
1002			if (T::KNOWN_FEATURE_MASK[byte_offset] & mask) != 0 {
1003				return Err(());
1004			}
1005		}
1006
1007		if self.flags.len() <= byte_offset {
1008			self.flags.resize(byte_offset + 1, 0u8);
1009		}
1010
1011		self.flags[byte_offset] |= mask;
1012
1013		Ok(())
1014	}
1015}
1016
1017impl<T: sealed::UpfrontShutdownScript> Features<T> {
1018	/// Unsets the `upfront_shutdown_script` feature
1019	pub fn clear_upfront_shutdown_script(mut self) -> Self {
1020		<T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
1021		self
1022	}
1023}
1024
1025impl<T: sealed::ShutdownAnySegwit> Features<T> {
1026	/// Unsets the `shutdown_anysegwit` feature
1027	pub fn clear_shutdown_anysegwit(mut self) -> Self {
1028		<T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
1029		self
1030	}
1031}
1032
1033impl<T: sealed::Wumbo> Features<T> {
1034	/// Unsets the `wumbo` feature
1035	pub fn clear_wumbo(mut self) -> Self {
1036		<T as sealed::Wumbo>::clear_bits(&mut self.flags);
1037		self
1038	}
1039}
1040
1041impl<T: sealed::SCIDPrivacy> Features<T> {
1042	/// Unsets the `scid_privacy` feature
1043	pub fn clear_scid_privacy(&mut self) {
1044		<T as sealed::SCIDPrivacy>::clear_bits(&mut self.flags);
1045	}
1046}
1047
1048impl<T: sealed::AnchorsZeroFeeHtlcTx> Features<T> {
1049	/// Unsets the `anchors_zero_fee_htlc_tx` feature
1050	pub fn clear_anchors_zero_fee_htlc_tx(&mut self) {
1051		<T as sealed::AnchorsZeroFeeHtlcTx>::clear_bits(&mut self.flags);
1052	}
1053}
1054
1055impl<T: sealed::RouteBlinding> Features<T> {
1056	/// Unsets the `route_blinding` feature
1057	pub fn clear_route_blinding(&mut self) {
1058		<T as sealed::RouteBlinding>::clear_bits(&mut self.flags);
1059	}
1060}
1061
1062#[cfg(any(test, feature = "_test_utils"))]
1063impl<T: sealed::UnknownFeature> Features<T> {
1064	/// Sets an unknown feature for testing
1065	pub fn unknown() -> Self {
1066		let mut features = Self::empty();
1067		features.set_unknown_feature_required();
1068		features
1069	}
1070}
1071
1072pub(crate) fn unset_features_mask_at_position<T: sealed::Context>(
1073	other: &Features<T>, index: usize,
1074) -> u8 {
1075	if index < other.flags.len() {
1076		// Form a mask similar to !T::KNOWN_FEATURE_MASK only for `other`
1077		!(other.flags[index]
1078			| ((other.flags[index] >> 1) & ANY_REQUIRED_FEATURES_MASK)
1079			| ((other.flags[index] << 1) & ANY_OPTIONAL_FEATURES_MASK))
1080	} else {
1081		0b11_11_11_11
1082	}
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087	use super::*;
1088
1089	#[test]
1090	fn sanity_test_unknown_bits() {
1091		let features = ChannelFeatures::empty();
1092		assert!(!features.requires_unknown_bits());
1093		assert!(!features.supports_unknown_bits());
1094
1095		let mut features = ChannelFeatures::empty();
1096		features.set_unknown_feature_required();
1097		assert!(features.requires_unknown_bits());
1098		assert!(features.supports_unknown_bits());
1099		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![12344]);
1100
1101		let mut features = ChannelFeatures::empty();
1102		features.set_unknown_feature_optional();
1103		assert!(!features.requires_unknown_bits());
1104		assert!(features.supports_unknown_bits());
1105		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![]);
1106
1107		let mut features = ChannelFeatures::empty();
1108		features.set_unknown_feature_required();
1109		features.set_custom_bit(12346).unwrap();
1110		assert!(features.requires_unknown_bits());
1111		assert!(features.supports_unknown_bits());
1112		assert_eq!(
1113			features.required_unknown_bits_from(&ChannelFeatures::empty()),
1114			vec![12344, 12346]
1115		);
1116
1117		let mut limiter = ChannelFeatures::empty();
1118		limiter.set_unknown_feature_optional();
1119		assert_eq!(features.required_unknown_bits_from(&limiter), vec![12346]);
1120	}
1121
1122	#[test]
1123	fn requires_unknown_bits_from() {
1124		let mut features1 = InitFeatures::empty();
1125		let mut features2 = InitFeatures::empty();
1126		assert!(!features1.requires_unknown_bits_from(&features2));
1127		assert!(!features2.requires_unknown_bits_from(&features1));
1128
1129		features1.set_data_loss_protect_required();
1130		assert!(features1.requires_unknown_bits_from(&features2));
1131		assert!(!features2.requires_unknown_bits_from(&features1));
1132
1133		features2.set_data_loss_protect_optional();
1134		assert!(!features1.requires_unknown_bits_from(&features2));
1135		assert!(!features2.requires_unknown_bits_from(&features1));
1136
1137		features2.set_gossip_queries_required();
1138		assert!(!features1.requires_unknown_bits_from(&features2));
1139		assert!(features2.requires_unknown_bits_from(&features1));
1140
1141		features1.set_gossip_queries_optional();
1142		assert!(!features1.requires_unknown_bits_from(&features2));
1143		assert!(!features2.requires_unknown_bits_from(&features1));
1144
1145		features1.set_variable_length_onion_required();
1146		assert!(features1.requires_unknown_bits_from(&features2));
1147		assert!(!features2.requires_unknown_bits_from(&features1));
1148
1149		features2.set_variable_length_onion_optional();
1150		assert!(!features1.requires_unknown_bits_from(&features2));
1151		assert!(!features2.requires_unknown_bits_from(&features1));
1152
1153		features1.set_basic_mpp_required();
1154		features2.set_wumbo_required();
1155		assert!(features1.requires_unknown_bits_from(&features2));
1156		assert!(features2.requires_unknown_bits_from(&features1));
1157	}
1158
1159	#[test]
1160	fn convert_to_context_with_relevant_flags() {
1161		let mut init_features = InitFeatures::empty();
1162		// Set a bunch of features we use, plus initial_routing_sync_required (which shouldn't get
1163		// converted as it's only relevant in an init context).
1164		init_features.set_initial_routing_sync_required();
1165		init_features.set_data_loss_protect_required();
1166		init_features.set_variable_length_onion_required();
1167		init_features.set_static_remote_key_required();
1168		init_features.set_payment_secret_required();
1169		init_features.set_basic_mpp_optional();
1170		init_features.set_wumbo_optional();
1171		init_features.set_anchors_zero_fee_htlc_tx_optional();
1172		init_features.set_route_blinding_optional();
1173		init_features.set_shutdown_any_segwit_optional();
1174		init_features.set_onion_messages_optional();
1175		init_features.set_channel_type_optional();
1176		init_features.set_scid_privacy_optional();
1177		init_features.set_zero_conf_optional();
1178
1179		assert!(init_features.initial_routing_sync());
1180		assert!(!init_features.supports_upfront_shutdown_script());
1181		assert!(!init_features.supports_gossip_queries());
1182
1183		let node_features: NodeFeatures = init_features.to_context();
1184		{
1185			// Check that the flags are as expected:
1186			// - option_data_loss_protect (req)
1187			// - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
1188			// - basic_mpp | wumbo | option_anchors_zero_fee_htlc_tx
1189			// - option_route_blinding | opt_shutdown_anysegwit
1190			// - onion_messages
1191			// - option_channel_type | option_scid_alias
1192			// - option_zeroconf
1193			assert_eq!(node_features.flags.len(), 7);
1194			assert_eq!(node_features.flags[0], 0b00000001);
1195			assert_eq!(node_features.flags[1], 0b01010001);
1196			assert_eq!(node_features.flags[2], 0b10001010);
1197			assert_eq!(node_features.flags[3], 0b00001010);
1198			assert_eq!(node_features.flags[4], 0b10000000);
1199			assert_eq!(node_features.flags[5], 0b10100000);
1200			assert_eq!(node_features.flags[6], 0b00001000);
1201		}
1202
1203		// Check that cleared flags are kept blank when converting back:
1204		// - initial_routing_sync was not applicable to NodeContext
1205		// - upfront_shutdown_script was cleared before converting
1206		// - gossip_queries was cleared before converting
1207		let features: InitFeatures = node_features.to_context_internal();
1208		assert!(!features.initial_routing_sync());
1209		assert!(!features.supports_upfront_shutdown_script());
1210		assert!(!init_features.supports_gossip_queries());
1211	}
1212
1213	#[test]
1214	fn convert_to_context_with_unknown_flags() {
1215		// Ensure the `from` context has fewer known feature bytes than the `to` context.
1216		assert!(
1217			<sealed::ChannelContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1218				< <sealed::Bolt11InvoiceContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1219		);
1220		let mut channel_features = ChannelFeatures::empty();
1221		channel_features.set_unknown_feature_optional();
1222		assert!(channel_features.supports_unknown_bits());
1223		let invoice_features: Bolt11InvoiceFeatures = channel_features.to_context_internal();
1224		assert!(!invoice_features.supports_unknown_bits());
1225	}
1226
1227	#[test]
1228	fn set_feature_bits() {
1229		let mut features = Bolt11InvoiceFeatures::empty();
1230		features.set_basic_mpp_optional();
1231		features.set_payment_secret_required();
1232		assert!(features.supports_basic_mpp());
1233		assert!(!features.requires_basic_mpp());
1234		assert!(features.requires_payment_secret());
1235		assert!(features.supports_payment_secret());
1236
1237		// Set flags manually
1238		let mut features = NodeFeatures::empty();
1239		assert!(features.set_optional_feature_bit(55).is_ok());
1240		assert!(features.supports_keysend());
1241		assert!(features.set_optional_feature_bit(255).is_ok());
1242		assert!(features.set_required_feature_bit(256).is_err());
1243	}
1244
1245	#[test]
1246	fn set_custom_bits() {
1247		let mut features = Bolt11InvoiceFeatures::empty();
1248		features.set_variable_length_onion_optional();
1249		assert_eq!(features.flags[1], 0b00000010);
1250
1251		assert!(features.set_optional_custom_bit(255).is_err());
1252		assert!(features.set_required_custom_bit(256).is_ok());
1253		assert!(features.set_required_custom_bit(258).is_ok());
1254		assert_eq!(features.flags[31], 0b00000000);
1255		assert_eq!(features.flags[32], 0b00000101);
1256
1257		let known_bit = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::EVEN_BIT;
1258		let byte_offset = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::BYTE_OFFSET;
1259		assert_eq!(byte_offset, 1);
1260		assert_eq!(features.flags[byte_offset], 0b00000010);
1261		assert!(features.set_required_custom_bit(known_bit).is_err());
1262		assert_eq!(features.flags[byte_offset], 0b00000010);
1263
1264		let mut features = Bolt11InvoiceFeatures::empty();
1265		assert!(features.set_optional_custom_bit(256).is_ok());
1266		assert!(features.set_optional_custom_bit(259).is_ok());
1267		assert_eq!(features.flags[32], 0b00001010);
1268
1269		let mut features = Bolt11InvoiceFeatures::empty();
1270		assert!(features.set_required_custom_bit(257).is_ok());
1271		assert!(features.set_required_custom_bit(258).is_ok());
1272		assert_eq!(features.flags[32], 0b00000101);
1273	}
1274
1275	#[test]
1276	fn test_channel_type_mapping() {
1277		// If we map an Bolt11InvoiceFeatures with StaticRemoteKey optional, it should map into a
1278		// required-StaticRemoteKey ChannelTypeFeatures.
1279		let mut init_features = InitFeatures::empty();
1280		init_features.set_static_remote_key_optional();
1281		let converted_features = ChannelTypeFeatures::from_init(&init_features);
1282		assert_eq!(converted_features, ChannelTypeFeatures::only_static_remote_key());
1283		assert!(!converted_features.supports_any_optional_bits());
1284		assert!(converted_features.requires_static_remote_key());
1285	}
1286
1287	#[test]
1288	fn test_excess_zero_bytes_ignored() {
1289		// Checks that `Hash` and `PartialEq` ignore excess zero bytes, which may appear due to
1290		// feature conversion or because a peer serialized their feature poorly.
1291		use std::collections::hash_map::DefaultHasher;
1292		use std::hash::{Hash, Hasher};
1293
1294		let mut zerod_features = InitFeatures::empty();
1295		zerod_features.flags = vec![0];
1296		let empty_features = InitFeatures::empty();
1297		assert!(empty_features.flags.is_empty());
1298
1299		assert_eq!(zerod_features, empty_features);
1300
1301		let mut zerod_hash = DefaultHasher::new();
1302		zerod_features.hash(&mut zerod_hash);
1303		let mut empty_hash = DefaultHasher::new();
1304		empty_features.hash(&mut empty_hash);
1305		assert_eq!(zerod_hash.finish(), empty_hash.finish());
1306	}
1307}