Skip to main content

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//! - `SimpleClose` - requires/supports simplified closing negotiation
55//!   (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_complete-and-closing_sig) for more information).
56//! - `OnionMessages` - requires/supports forwarding onion messages
57//!   (see [BOLT-4](https://github.com/lightning/bolts/blob/master/04-onion-routing.md#onion-messages) for more information).
58//! - `ChannelType` - node supports the channel_type field in open/accept
59//!   (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
60//! - `SCIDPrivacy` - supply channel aliases for routing
61//!   (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
62//! - `PaymentMetadata` - include additional data in invoices which is passed to recipients in the
63//!   onion.
64//!   (see [BOLT-11](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md) for
65//!   more).
66//! - `ZeroConf` - supports accepting HTLCs and using channels prior to funding confirmation
67//!   (see
68//!   [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message)
69//!   for more info).
70//! - `Keysend` - send funds to a node without an invoice
71//!   (see the [`Keysend` feature assignment proposal](https://github.com/lightning/bolts/issues/605#issuecomment-606679798) for more information).
72//! - `Trampoline` - supports receiving and forwarding Trampoline payments
73//!   (see the [`Trampoline` feature proposal](https://github.com/lightning/bolts/pull/836) for more information).
74//! - `DnsResolver` - supports resolving DNS names to TXT DNSSEC proofs for BIP 353 payments
75//!   (see [bLIP 32](https://github.com/lightning/blips/blob/master/blip-0032.md) for more information).
76//! - `ProvideStorage` - Indicates that we offer the capability to store data of our peers
77//!   (see [BOLT PR #1110](https://github.com/lightning/bolts/pull/1110) for more info).
78//! - `Quiescence` - protocol to quiesce a channel by indicating that "SomeThing Fundamental is Underway"
79//!   (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#channel-quiescence) for more information).
80//! - `ZeroFeeCommitments` - A channel type which always uses zero transaction fee on commitment transactions.
81//!   (see [BOLT PR #1228](https://github.com/lightning/bolts/pull/1228) for more info).
82//! - `Splice` - Allows replacing the currently-locked funding transaction with a new one
83//!   (see [BOLT PR #1160](https://github.com/lightning/bolts/pull/1160) for more information).
84//! - `HtlcHold` - requires/supports holding HTLCs and forwarding on receipt of an onion message
85//!   (see [BOLT-2](https://github.com/lightning/bolts/pull/989/files) for more information).
86//!
87//! LDK knows about the following features, but does not support them:
88//! - `AnchorsNonzeroFeeHtlcTx` - the initial version of anchor outputs, which was later found to be
89//!   vulnerable (see this
90//!   [mailing list post](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-September/002796.html)
91//!   for more information).
92//! - `AnchorZeroFeeCommitmentsStaging` - this is equivalent to `ZeroFeeCommitments` but was used
93//!   prior to spec finalization. New channels cannot be established with this feature but existing
94//!   channels of this type can be read and are silently converted to `ZeroFeeCommitments`.
95//!
96//! [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
97
98use core::borrow::Borrow;
99use core::hash::{Hash, Hasher};
100use core::marker::PhantomData;
101use core::ops::{Deref, DerefMut};
102use core::{cmp, fmt};
103
104use alloc::vec::Vec;
105
106mod sealed {
107	use super::Features;
108
109	/// The context in which [`Features`] are applicable. Defines which features are known to the
110	/// implementation, though specification of them as required or optional is up to the code
111	/// constructing a features object.
112	pub trait Context {
113		/// Bitmask for selecting features that are known to the implementation.
114		const KNOWN_FEATURE_MASK: &'static [u8];
115	}
116
117	/// Defines a [`Context`] by stating which features it requires and which are optional. Features
118	/// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
119	/// feature identifiers.
120	macro_rules! define_context {
121		($context: ident, [$( $( $known_feature: ident )|*, )*]) => {
122			#[derive(Eq, PartialEq)]
123			pub struct $context {}
124
125			impl Context for $context {
126				const KNOWN_FEATURE_MASK: &'static [u8] = &[
127					$(
128						0b00_00_00_00 $(|
129							<Self as $known_feature>::REQUIRED_MASK |
130							<Self as $known_feature>::OPTIONAL_MASK)*,
131					)*
132				];
133			}
134
135			impl alloc::fmt::Display for Features<$context> {
136				fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
137					$(
138						$(
139							fmt.write_fmt(format_args!("{}: {}, ", stringify!($known_feature),
140								if <$context as $known_feature>::requires_feature(&self.flags) { "required" }
141								else if <$context as $known_feature>::supports_feature(&self.flags) { "supported" }
142								else { "not supported" }))?;
143						)*
144						{} // Rust gets mad if we only have a $()* block here, so add a dummy {}
145					)*
146					fmt.write_fmt(format_args!("unknown flags: {}",
147						if self.requires_unknown_bits() { "required" }
148						else if self.supports_unknown_bits() { "supported" } else { "none" }))
149				}
150			}
151		};
152	}
153
154	define_context!(
155		InitContext,
156		[
157			// Byte 0
158			DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
159			// Byte 1
160			VariableLengthOnion | StaticRemoteKey | PaymentSecret,
161			// Byte 2
162			BasicMPP | Wumbo | AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
163			// Byte 3
164			RouteBlinding | ShutdownAnySegwit | DualFund | Taproot,
165			// Byte 4
166			Quiescence | OnionMessages,
167			// Byte 5
168			AnchorZeroFeeCommitments | ProvideStorage | ChannelType | SCIDPrivacy,
169			// Byte 6
170			ZeroConf,
171			// Byte 7
172			Trampoline | SimpleClose | Splice,
173			// Byte 8 - 18
174			,,,,,,,,,,,
175			// Byte 19
176			HtlcHold,
177		]
178	);
179	define_context!(
180		NodeContext,
181		[
182			// Byte 0
183			DataLossProtect | UpfrontShutdownScript | GossipQueries,
184			// Byte 1
185			VariableLengthOnion | StaticRemoteKey | PaymentSecret,
186			// Byte 2
187			BasicMPP | Wumbo | AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
188			// Byte 3
189			RouteBlinding | ShutdownAnySegwit | DualFund | Taproot,
190			// Byte 4
191			Quiescence | OnionMessages,
192			// Byte 5
193			AnchorZeroFeeCommitments | ProvideStorage | ChannelType | SCIDPrivacy,
194			// Byte 6
195			ZeroConf | Keysend,
196			// Byte 7
197			Trampoline | SimpleClose | Splice,
198			// Byte 8 - 18
199			,,,,,,,,,,,
200			// Byte 19
201			HtlcHold,
202			// Byte 20 - 31
203			,,,,,,,,,,,,
204			// Byte 32
205			DnsResolver,
206		]
207	);
208	define_context!(ChannelContext, []);
209	define_context!(Bolt11InvoiceContext, [
210		// Byte 0
211		,
212		// Byte 1
213		VariableLengthOnion | PaymentSecret,
214		// Byte 2
215		BasicMPP,
216		// Byte 3
217		,
218		// Byte 4
219		,
220		// Byte 5
221		,
222		// Byte 6
223		PaymentMetadata,
224		// Byte 7
225		Trampoline,
226	]);
227	define_context!(OfferContext, []);
228	define_context!(InvoiceRequestContext, []);
229	define_context!(Bolt12InvoiceContext, [
230		// Byte 0
231		,
232		// Byte 1
233		,
234		// Byte 2
235		BasicMPP,
236		// Byte 3
237		,
238		// Byte 4
239		,
240		// Byte 5
241		,
242		// Byte 6
243		,
244		// Byte 7
245		Trampoline,
246	]);
247	define_context!(BlindedHopContext, []);
248	// This isn't a "real" feature context, and is only used in the channel_type field in an
249	// `OpenChannel` message.
250	define_context!(ChannelTypeContext, [
251		// Byte 0
252		,
253		// Byte 1
254		StaticRemoteKey,
255		// Byte 2
256		AnchorsNonzeroFeeHtlcTx | AnchorsZeroFeeHtlcTx,
257		// Byte 3
258		Taproot,
259		// Byte 4
260		,
261		// Byte 5
262		AnchorZeroFeeCommitments | SCIDPrivacy,
263		// Byte 6
264		ZeroConf,
265		// Byte 7 - 16
266		,,,,,,,,,,
267		// Byte 17
268		AnchorZeroFeeCommitmentsStaging,
269	]);
270
271	/// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
272	/// useful for manipulating feature flags.
273	macro_rules! define_feature {
274		($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
275		 $required_setter: ident, $clear: ident, $supported_getter: ident) => {
276			#[doc = $doc]
277			///
278			/// See [BOLT #9] for details.
279			///
280			/// [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
281			pub trait $feature: Context {
282				/// The bit used to signify that the feature is required.
283				const EVEN_BIT: usize = $odd_bit - 1;
284
285				/// The bit used to signify that the feature is optional.
286				const ODD_BIT: usize = $odd_bit;
287
288				/// Assertion that [`EVEN_BIT`] is actually even.
289				///
290				/// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
291				const ASSERT_EVEN_BIT_PARITY: usize;
292
293				/// Assertion that [`ODD_BIT`] is actually odd.
294				///
295				/// [`ODD_BIT`]: #associatedconstant.ODD_BIT
296				const ASSERT_ODD_BIT_PARITY: usize;
297
298				/// Assertion that the bits are set in the context's [`KNOWN_FEATURE_MASK`].
299				///
300				/// [`KNOWN_FEATURE_MASK`]: Context::KNOWN_FEATURE_MASK
301				#[cfg(not(any(test, feature = "_test_utils")))] // We violate this constraint with `UnknownFeature`
302				const ASSERT_BITS_IN_MASK: u8;
303
304				/// The byte where the feature is set.
305				const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
306
307				/// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
308				///
309				/// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
310				const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
311
312				/// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
313				///
314				/// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
315				const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
316
317				/// Returns whether the feature is required by the given flags.
318				#[inline]
319				fn requires_feature(flags: &[u8]) -> bool {
320					flags.len() > Self::BYTE_OFFSET &&
321						(flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
322				}
323
324				/// Returns whether the feature is supported by the given flags.
325				#[inline]
326				fn supports_feature(flags: &[u8]) -> bool {
327					flags.len() > Self::BYTE_OFFSET &&
328						(flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
329				}
330
331				/// Sets the feature's required (even) bit in the given flags.
332				#[inline]
333				fn set_required_bit(obj: &mut Features<Self>) {
334					if obj.flags.len() <= Self::BYTE_OFFSET {
335						obj.flags.resize(Self::BYTE_OFFSET + 1, 0u8);
336					}
337
338					obj.flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
339					obj.flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
340				}
341
342				/// Sets the feature's optional (odd) bit in the given flags.
343				#[inline]
344				fn set_optional_bit(obj: &mut Features<Self>) {
345					if obj.flags.len() <= Self::BYTE_OFFSET {
346						obj.flags.resize(Self::BYTE_OFFSET + 1, 0u8);
347					}
348
349					obj.flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
350				}
351
352				/// Clears the feature's required (even) and optional (odd) bits from the given
353				/// flags.
354				#[inline]
355				fn clear_bits(obj: &mut Features<Self>) {
356					if obj.flags.len() > Self::BYTE_OFFSET {
357						obj.flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
358						obj.flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
359					}
360
361					let last_non_zero_byte = obj.flags.iter().rposition(|&byte| byte != 0);
362					let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
363					obj.flags.resize(size, 0u8);
364				}
365			}
366
367			impl <T: $feature> Features<T> {
368				/// Set this feature as optional.
369				pub fn $optional_setter(&mut self) {
370					<T as $feature>::set_optional_bit(self);
371				}
372
373				/// Set this feature as required.
374				pub fn $required_setter(&mut self) {
375					<T as $feature>::set_required_bit(self);
376				}
377
378				/// Unsets this feature.
379				pub fn $clear(&mut self) {
380					<T as $feature>::clear_bits(self);
381				}
382
383				/// Checks if this feature is supported.
384				pub fn $supported_getter(&self) -> bool {
385					<T as $feature>::supports_feature(&self.flags)
386				}
387			}
388
389			$(
390				impl $feature for $context {
391					// EVEN_BIT % 2 == 0
392					const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
393
394					// ODD_BIT % 2 == 1
395					const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
396
397					// (byte & (REQUIRED_MASK | OPTIONAL_MASK)) >> (EVEN_BIT % 8) == 3
398					#[cfg(not(any(test, feature = "_test_utils")))] // We violate this constraint with `UnknownFeature`
399					const ASSERT_BITS_IN_MASK: u8 =
400						((<$context>::KNOWN_FEATURE_MASK[<Self as $feature>::BYTE_OFFSET] & (<Self as $feature>::REQUIRED_MASK | <Self as $feature>::OPTIONAL_MASK))
401						 >> (<Self as $feature>::EVEN_BIT % 8)) - 3;
402				}
403			)*
404		};
405		($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
406		 $required_setter: ident, $clear: ident, $supported_getter: ident, $required_getter: ident) => {
407			define_feature!($odd_bit, $feature, [$($context),+], $doc, $optional_setter, $required_setter, $clear, $supported_getter);
408			impl <T: $feature> Features<T> {
409				/// Checks if this feature is required.
410				pub fn $required_getter(&self) -> bool {
411					<T as $feature>::requires_feature(&self.flags)
412				}
413			}
414		}
415	}
416
417	define_feature!(
418		1,
419		DataLossProtect,
420		[InitContext, NodeContext],
421		"Feature flags for `option_data_loss_protect`.",
422		set_data_loss_protect_optional,
423		set_data_loss_protect_required,
424		clear_data_loss_protect,
425		supports_data_loss_protect,
426		requires_data_loss_protect
427	);
428	// NOTE: Per Bolt #9, initial_routing_sync has no even bit.
429	define_feature!(
430		3,
431		InitialRoutingSync,
432		[InitContext],
433		"Feature flags for `initial_routing_sync`.",
434		set_initial_routing_sync_optional,
435		set_initial_routing_sync_required,
436		clear_initial_routing_sync,
437		initial_routing_sync
438	);
439	define_feature!(
440		5,
441		UpfrontShutdownScript,
442		[InitContext, NodeContext],
443		"Feature flags for `option_upfront_shutdown_script`.",
444		set_upfront_shutdown_script_optional,
445		set_upfront_shutdown_script_required,
446		clear_upfront_shutdown_script,
447		supports_upfront_shutdown_script,
448		requires_upfront_shutdown_script
449	);
450	define_feature!(
451		7,
452		GossipQueries,
453		[InitContext, NodeContext],
454		"Feature flags for `gossip_queries`.",
455		set_gossip_queries_optional,
456		set_gossip_queries_required,
457		clear_gossip_queries,
458		supports_gossip_queries,
459		requires_gossip_queries
460	);
461	define_feature!(
462		9,
463		VariableLengthOnion,
464		[InitContext, NodeContext, Bolt11InvoiceContext],
465		"Feature flags for `var_onion_optin`.",
466		set_variable_length_onion_optional,
467		set_variable_length_onion_required,
468		clear_variable_length_onion,
469		supports_variable_length_onion,
470		requires_variable_length_onion
471	);
472	define_feature!(
473		13,
474		StaticRemoteKey,
475		[InitContext, NodeContext, ChannelTypeContext],
476		"Feature flags for `option_static_remotekey`.",
477		set_static_remote_key_optional,
478		set_static_remote_key_required,
479		clear_static_remote_key,
480		supports_static_remote_key,
481		requires_static_remote_key
482	);
483	define_feature!(
484		15,
485		PaymentSecret,
486		[InitContext, NodeContext, Bolt11InvoiceContext],
487		"Feature flags for `payment_secret`.",
488		set_payment_secret_optional,
489		set_payment_secret_required,
490		clear_payment_secret,
491		supports_payment_secret,
492		requires_payment_secret
493	);
494	define_feature!(
495		17,
496		BasicMPP,
497		[InitContext, NodeContext, Bolt11InvoiceContext, Bolt12InvoiceContext],
498		"Feature flags for `basic_mpp`.",
499		set_basic_mpp_optional,
500		set_basic_mpp_required,
501		clear_basic_mpp,
502		supports_basic_mpp,
503		requires_basic_mpp
504	);
505	define_feature!(
506		19,
507		Wumbo,
508		[InitContext, NodeContext],
509		"Feature flags for `option_support_large_channel` (aka wumbo channels).",
510		set_wumbo_optional,
511		set_wumbo_required,
512		clear_wumbo,
513		supports_wumbo,
514		requires_wumbo
515	);
516	define_feature!(
517		21,
518		AnchorsNonzeroFeeHtlcTx,
519		[InitContext, NodeContext, ChannelTypeContext],
520		"Feature flags for `option_anchors_nonzero_fee_htlc_tx`.",
521		set_anchors_nonzero_fee_htlc_tx_optional,
522		set_anchors_nonzero_fee_htlc_tx_required,
523		clear_anchors_nonzero_fee_htlc_tx,
524		supports_anchors_nonzero_fee_htlc_tx,
525		requires_anchors_nonzero_fee_htlc_tx
526	);
527	define_feature!(
528		23,
529		AnchorsZeroFeeHtlcTx,
530		[InitContext, NodeContext, ChannelTypeContext],
531		"Feature flags for `option_anchors_zero_fee_htlc_tx`.",
532		set_anchors_zero_fee_htlc_tx_optional,
533		set_anchors_zero_fee_htlc_tx_required,
534		clear_anchors_zero_fee_htlc_tx,
535		supports_anchors_zero_fee_htlc_tx,
536		requires_anchors_zero_fee_htlc_tx
537	);
538	define_feature!(
539		25,
540		RouteBlinding,
541		[InitContext, NodeContext],
542		"Feature flags for `option_route_blinding`.",
543		set_route_blinding_optional,
544		set_route_blinding_required,
545		clear_route_blinding,
546		supports_route_blinding,
547		requires_route_blinding
548	);
549	define_feature!(
550		27,
551		ShutdownAnySegwit,
552		[InitContext, NodeContext],
553		"Feature flags for `opt_shutdown_anysegwit`.",
554		set_shutdown_any_segwit_optional,
555		set_shutdown_any_segwit_required,
556		clear_shutdown_anysegwit,
557		supports_shutdown_anysegwit,
558		requires_shutdown_anysegwit
559	);
560	define_feature!(
561		29,
562		DualFund,
563		[InitContext, NodeContext],
564		"Feature flags for `option_dual_fund`.",
565		set_dual_fund_optional,
566		set_dual_fund_required,
567		clear_dual_fund,
568		supports_dual_fund,
569		requires_dual_fund
570	);
571	define_feature!(
572		31,
573		Taproot,
574		[InitContext, NodeContext, ChannelTypeContext],
575		"Feature flags for `option_taproot`.",
576		set_taproot_optional,
577		set_taproot_required,
578		clear_taproot,
579		supports_taproot,
580		requires_taproot
581	);
582	define_feature!(
583		35,
584		Quiescence,
585		[InitContext, NodeContext],
586		"Feature flags for `option_quiesce`.",
587		set_quiescence_optional,
588		set_quiescence_required,
589		clear_quiescence,
590		supports_quiescence,
591		requires_quiescence
592	);
593	define_feature!(
594		39,
595		OnionMessages,
596		[InitContext, NodeContext],
597		"Feature flags for `option_onion_messages`.",
598		set_onion_messages_optional,
599		set_onion_messages_required,
600		clear_onion_messages,
601		supports_onion_messages,
602		requires_onion_messages
603	);
604	define_feature!(
605		41,
606		AnchorZeroFeeCommitments,
607		[InitContext, NodeContext, ChannelTypeContext],
608		"Feature flags for `option_zero_fee_commitments`.",
609		set_anchor_zero_fee_commitments_optional,
610		set_anchor_zero_fee_commitments_required,
611		clear_anchor_zero_fee_commitments,
612		supports_anchor_zero_fee_commitments,
613		requires_anchor_zero_fee_commitments
614	);
615	define_feature!(
616		43,
617		ProvideStorage,
618		[InitContext, NodeContext],
619		"Feature flags for `option_provide_storage`.",
620		set_provide_storage_optional,
621		set_provide_storage_required,
622		clear_provide_storage,
623		supports_provide_storage,
624		requires_provide_storage
625	);
626	define_feature!(
627		45,
628		ChannelType,
629		[InitContext, NodeContext],
630		"Feature flags for `option_channel_type`.",
631		set_channel_type_optional,
632		set_channel_type_required,
633		clear_channel_type,
634		supports_channel_type,
635		requires_channel_type
636	);
637	define_feature!(47,
638		SCIDPrivacy,
639		[InitContext, NodeContext, ChannelTypeContext],
640		"Feature flags for only forwarding with SCID aliasing. Called `option_scid_alias` in the BOLTs",
641		set_scid_privacy_optional,
642		set_scid_privacy_required,
643		clear_scid_privacy,
644		supports_scid_privacy,
645		requires_scid_privacy
646	);
647	define_feature!(
648		49,
649		PaymentMetadata,
650		[Bolt11InvoiceContext],
651		"Feature flags for payment metadata in invoices.",
652		set_payment_metadata_optional,
653		set_payment_metadata_required,
654		clear_payment_metadata,
655		supports_payment_metadata,
656		requires_payment_metadata
657	);
658	define_feature!(
659		51,
660		ZeroConf,
661		[InitContext, NodeContext, ChannelTypeContext],
662		"Feature flags for accepting channels with zero confirmations. Called `option_zeroconf` in the BOLTs",
663		set_zero_conf_optional,
664		set_zero_conf_required,
665		clear_zero_conf,
666		supports_zero_conf,
667		requires_zero_conf
668	);
669	define_feature!(
670		55,
671		Keysend,
672		[NodeContext],
673		"Feature flags for keysend payments.",
674		set_keysend_optional,
675		set_keysend_required,
676		clear_keysend,
677		supports_keysend,
678		requires_keysend
679	);
680	define_feature!(
681		57,
682		Trampoline,
683		[InitContext, NodeContext, Bolt11InvoiceContext, Bolt12InvoiceContext],
684		"Feature flags for Trampoline routing.",
685		set_trampoline_routing_optional,
686		set_trampoline_routing_required,
687		clear_trampoline_routing,
688		supports_trampoline_routing,
689		requires_trampoline_routing
690	);
691	define_feature!(
692		61,
693		SimpleClose,
694		[InitContext, NodeContext],
695		"Feature flags for simplified closing negotiation.",
696		set_simple_close_optional,
697		set_simple_close_required,
698		clear_simple_close,
699		supports_simple_close,
700		requires_simple_close
701	);
702	define_feature!(
703		63,
704		Splice,
705		[InitContext, NodeContext],
706		"Feature flags for channel splicing.",
707		set_splicing_optional,
708		set_splicing_required,
709		clear_splicing,
710		supports_splicing,
711		requires_splicing
712	);
713	// By default, allocate enough bytes to cover up to Splice. Update this as new features are
714	// added which we expect to appear commonly across contexts.
715	pub(super) const MIN_FEATURES_ALLOCATION_BYTES: usize = 63_usize.div_ceil(8);
716	define_feature!(
717		141, // The BOLTs PR used feature bit 40/41, so this staging bit was assigned +100
718		AnchorZeroFeeCommitmentsStaging,
719		[ChannelTypeContext],
720		"A flag for `option_zero_fee_commitments` which was used prior to standardization. It is equivalent to `option_zero_fee_commitments`.",
721		set_anchor_zero_fee_commitments_staging_optional,
722		set_anchor_zero_fee_commitments_staging_required,
723		clear_anchor_zero_fee_commitments_staging,
724		supports_anchor_zero_fee_commitments_staging,
725		requires_anchor_zero_fee_commitments_staging
726	);
727	define_feature!(
728		153, // The BOLTs PR uses feature bit 52/53, so add +100 for the experimental bit
729		HtlcHold,
730		[InitContext, NodeContext],
731		"Feature flags for holding HTLCs and forwarding on receipt of an onion message",
732		set_htlc_hold_optional,
733		set_htlc_hold_required,
734		clear_htlc_hold,
735		supports_htlc_hold,
736		requires_htlc_hold
737	);
738	define_feature!(
739		259,
740		DnsResolver,
741		[NodeContext],
742		"Feature flags for DNS resolving.",
743		set_dns_resolution_optional,
744		set_dns_resolution_required,
745		clear_dns_resolution,
746		supports_dns_resolution,
747		requires_dns_resolution
748	);
749
750	// Note: update the module-level docs when a new feature bit is added!
751
752	#[cfg(any(test, feature = "_test_utils"))]
753	define_feature!(
754		12345,
755		UnknownFeature,
756		[
757			NodeContext,
758			ChannelContext,
759			Bolt11InvoiceContext,
760			OfferContext,
761			InvoiceRequestContext,
762			Bolt12InvoiceContext,
763			BlindedHopContext
764		],
765		"Feature flags for an unknown feature used in testing.",
766		set_unknown_feature_optional,
767		set_unknown_feature_required,
768		clear_unknown_feature,
769		supports_unknown_test_feature,
770		requires_unknown_test_feature
771	);
772}
773
774const ANY_REQUIRED_FEATURES_MASK: u8 = 0b01_01_01_01;
775const ANY_OPTIONAL_FEATURES_MASK: u8 = 0b10_10_10_10;
776
777// Vecs are always 3 pointers long, so `FeatureFlags` is never shorter than 24 bytes on 64-bit
778// platforms no matter what we do.
779//
780// Luckily, because `Vec` uses a `NonNull` pointer to its buffer, the two-variant enum is free
781// space-wise, but we only get the remaining 2 usizes in length available for our own stuff (as any
782// other value is interpreted as the `Heap` variant).
783//
784// Thus, as long as we never use more than 16 bytes (15 bytes for the data and one byte for the
785// length) for our Held variant `FeatureFlags` is the same length as a `Vec` in memory.
786const DIRECT_ALLOC_BYTES: usize = if sealed::MIN_FEATURES_ALLOCATION_BYTES > 8 * 2 - 1 {
787	sealed::MIN_FEATURES_ALLOCATION_BYTES
788} else {
789	8 * 2 - 1
790};
791const _ASSERT: () = assert!(DIRECT_ALLOC_BYTES <= u8::MAX as usize);
792
793#[cfg(fuzzing)]
794#[derive(Clone, PartialEq, Eq)]
795pub enum FeatureFlags {
796	Held { bytes: [u8; DIRECT_ALLOC_BYTES], len: u8 },
797	Heap(Vec<u8>),
798}
799
800#[cfg(not(fuzzing))]
801#[derive(Clone, PartialEq, Eq)]
802enum FeatureFlags {
803	Held { bytes: [u8; DIRECT_ALLOC_BYTES], len: u8 },
804	Heap(Vec<u8>),
805}
806
807impl FeatureFlags {
808	/// Constructs an empty [`FeatureFlags`]
809	pub fn empty() -> Self {
810		Self::Held { bytes: [0; DIRECT_ALLOC_BYTES], len: 0 }
811	}
812
813	/// Constructs a [`FeatureFlags`] from the given bytes
814	pub fn from(vec: Vec<u8>) -> Self {
815		if vec.len() <= DIRECT_ALLOC_BYTES {
816			let mut bytes = [0; DIRECT_ALLOC_BYTES];
817			bytes[..vec.len()].copy_from_slice(&vec);
818			Self::Held { bytes, len: vec.len() as u8 }
819		} else {
820			Self::Heap(vec)
821		}
822	}
823
824	/// Resizes a [`FeatureFlags`] to the given length, padding with `default` if required.
825	///
826	/// See [`Vec::resize`] for more info.
827	pub fn resize(&mut self, new_len: usize, default: u8) {
828		match self {
829			Self::Held { bytes, len } => {
830				let start_len = *len as usize;
831				if new_len <= DIRECT_ALLOC_BYTES {
832					bytes[start_len..].copy_from_slice(&[default; DIRECT_ALLOC_BYTES][start_len..]);
833					*len = new_len as u8;
834				} else {
835					let mut vec = Vec::new();
836					vec.resize(new_len, default);
837					vec[..start_len].copy_from_slice(&bytes[..start_len]);
838					*self = Self::Heap(vec);
839				}
840			},
841			Self::Heap(vec) => {
842				vec.resize(new_len, default);
843				if new_len <= DIRECT_ALLOC_BYTES {
844					let mut bytes = [0; DIRECT_ALLOC_BYTES];
845					bytes[..new_len].copy_from_slice(&vec[..new_len]);
846					*self = Self::Held { bytes, len: new_len as u8 };
847				}
848			},
849		}
850	}
851
852	/// Fetches the length of the [`FeatureFlags`], in bytes.
853	pub fn len(&self) -> usize {
854		self.deref().len()
855	}
856
857	/// Fetches an iterator over the bytes of this [`FeatureFlags`]
858	pub fn iter(
859		&self,
860	) -> impl Clone + ExactSizeIterator<Item = &u8> + DoubleEndedIterator<Item = &u8> {
861		let slice = self.deref();
862		slice.iter()
863	}
864
865	/// Fetches a mutable iterator over the bytes of this [`FeatureFlags`]
866	pub fn iter_mut(
867		&mut self,
868	) -> impl ExactSizeIterator<Item = &mut u8> + DoubleEndedIterator<Item = &mut u8> {
869		let slice = self.deref_mut();
870		slice.iter_mut()
871	}
872}
873
874impl Deref for FeatureFlags {
875	type Target = [u8];
876	fn deref(&self) -> &[u8] {
877		match self {
878			FeatureFlags::Held { bytes, len } => &bytes[..*len as usize],
879			FeatureFlags::Heap(vec) => &vec,
880		}
881	}
882}
883
884impl DerefMut for FeatureFlags {
885	fn deref_mut(&mut self) -> &mut [u8] {
886		match self {
887			FeatureFlags::Held { bytes, len } => &mut bytes[..*len as usize],
888			FeatureFlags::Heap(vec) => &mut vec[..],
889		}
890	}
891}
892
893impl PartialOrd for FeatureFlags {
894	fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
895		Some(self.cmp(other))
896	}
897}
898impl Ord for FeatureFlags {
899	fn cmp(&self, other: &Self) -> cmp::Ordering {
900		self.deref().cmp(other.deref())
901	}
902}
903impl fmt::Debug for FeatureFlags {
904	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
905		self.deref().fmt(fmt)
906	}
907}
908
909/// Tracks the set of features which a node implements, templated by the context in which it
910/// appears.
911///
912/// This is not exported to bindings users as we map the concrete feature types below directly instead
913#[derive(Eq)]
914pub struct Features<T: sealed::Context + ?Sized> {
915	/// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
916	flags: FeatureFlags,
917	mark: PhantomData<T>,
918}
919
920impl<T: sealed::Context, Rhs: Borrow<Self>> core::ops::BitOrAssign<Rhs> for Features<T> {
921	fn bitor_assign(&mut self, rhs: Rhs) {
922		let total_feature_len = cmp::max(self.flags.len(), rhs.borrow().flags.len());
923		self.flags.resize(total_feature_len, 0u8);
924		for (byte, rhs_byte) in self.flags.iter_mut().zip(rhs.borrow().flags.iter()) {
925			*byte |= *rhs_byte;
926		}
927	}
928}
929
930impl<T: sealed::Context> core::ops::BitOr for Features<T> {
931	type Output = Self;
932
933	fn bitor(mut self, o: Self) -> Self {
934		self |= o;
935		self
936	}
937}
938
939impl<T: sealed::Context> Clone for Features<T> {
940	fn clone(&self) -> Self {
941		Self { flags: self.flags.clone(), mark: PhantomData }
942	}
943}
944impl<T: sealed::Context> Hash for Features<T> {
945	fn hash<H: Hasher>(&self, hasher: &mut H) {
946		let mut nonzero_flags = &self.flags[..];
947		while nonzero_flags.last() == Some(&0) {
948			nonzero_flags = &nonzero_flags[..nonzero_flags.len() - 1];
949		}
950		nonzero_flags.hash(hasher);
951	}
952}
953impl<T: sealed::Context + ?Sized> PartialEq for Features<T> {
954	fn eq(&self, o: &Self) -> bool {
955		let mut o_iter = o.flags.iter();
956		let mut self_iter = self.flags.iter();
957		loop {
958			match (o_iter.next(), self_iter.next()) {
959				(Some(o), Some(us)) => {
960					if o != us {
961						return false;
962					}
963				},
964				(Some(b), None) | (None, Some(b)) => {
965					if *b != 0 {
966						return false;
967					}
968				},
969				(None, None) => return true,
970			}
971		}
972	}
973}
974impl<T: sealed::Context> PartialOrd for Features<T> {
975	fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
976		self.flags.partial_cmp(&other.flags)
977	}
978}
979impl<T: sealed::Context + Eq> Ord for Features<T> {
980	fn cmp(&self, other: &Self) -> cmp::Ordering {
981		self.flags.cmp(&other.flags)
982	}
983}
984impl<T: sealed::Context> fmt::Debug for Features<T> {
985	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
986		self.flags.fmt(fmt)
987	}
988}
989
990/// Features used within an `init` message.
991pub type InitFeatures = Features<sealed::InitContext>;
992/// Features used within a `node_announcement` message.
993pub type NodeFeatures = Features<sealed::NodeContext>;
994/// Features used within a `channel_announcement` message.
995pub type ChannelFeatures = Features<sealed::ChannelContext>;
996/// Features used within an invoice.
997pub type Bolt11InvoiceFeatures = Features<sealed::Bolt11InvoiceContext>;
998/// Features used within an `offer`.
999pub type OfferFeatures = Features<sealed::OfferContext>;
1000/// Features used within an `invoice_request`.
1001pub type InvoiceRequestFeatures = Features<sealed::InvoiceRequestContext>;
1002/// Features used within an `invoice`.
1003pub type Bolt12InvoiceFeatures = Features<sealed::Bolt12InvoiceContext>;
1004/// Features used within BOLT 4 encrypted_data_tlv and BOLT 12 blinded_payinfo
1005pub type BlindedHopFeatures = Features<sealed::BlindedHopContext>;
1006
1007/// Features used within the channel_type field in an OpenChannel message.
1008///
1009/// A channel is always of some known "type", describing the transaction formats used and the exact
1010/// semantics of our interaction with our peer.
1011///
1012/// Note that because a channel is a specific type which is proposed by the opener and accepted by
1013/// the counterparty, only required features are allowed here.
1014///
1015/// This is serialized differently from other feature types - it is not prefixed by a length, and
1016/// thus must only appear inside a TLV where its length is known in advance.
1017pub type ChannelTypeFeatures = Features<sealed::ChannelTypeContext>;
1018
1019impl InitFeatures {
1020	#[doc(hidden)]
1021	/// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
1022	/// are included in the result.
1023	///
1024	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1025	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1026		self.to_context_internal()
1027	}
1028}
1029
1030impl Bolt11InvoiceFeatures {
1031	#[doc(hidden)]
1032	/// Converts `Bolt11InvoiceFeatures` to `Features<C>`. Only known `Bolt11InvoiceFeatures` relevant to
1033	/// context `C` are included in the result.
1034	///
1035	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1036	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1037		self.to_context_internal()
1038	}
1039
1040	/// Getting a route for a keysend payment to a private node requires providing the payee's
1041	/// features (since they were not announced in a node announcement). However, keysend payments
1042	/// don't have an invoice to pull the payee's features from, so this method is provided for use
1043	/// when a [`Bolt11InvoiceFeatures`] is required in a route.
1044	///
1045	/// MPP keysend is not widely supported yet, so we parameterize support to allow the user to
1046	/// choose whether their router should find multi-part routes.
1047	pub fn for_keysend(allow_mpp: bool) -> Bolt11InvoiceFeatures {
1048		let mut res = Bolt11InvoiceFeatures::empty();
1049		res.set_variable_length_onion_optional();
1050		if allow_mpp {
1051			res.set_basic_mpp_optional();
1052		}
1053		res
1054	}
1055}
1056
1057impl Bolt12InvoiceFeatures {
1058	#[doc(hidden)]
1059	/// Converts [`Bolt12InvoiceFeatures`] to [`Features<C>`]. Only known [`Bolt12InvoiceFeatures`]
1060	/// relevant to context `C` are included in the result.
1061	///
1062	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1063	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1064		self.to_context_internal()
1065	}
1066}
1067
1068impl ChannelTypeFeatures {
1069	#[doc(hidden)]
1070	/// Maps the relevant `InitFeatures` to `ChannelTypeFeatures`. Any unknown features to
1071	/// `ChannelTypeFeatures` are not included in the result.
1072	///
1073	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1074	pub fn from_init(init: &InitFeatures) -> Self {
1075		let mut ret = init.to_context_internal();
1076		// ChannelTypeFeatures must only contain required bits, so we OR the required forms of all
1077		// optional bits and then AND out the optional ones.
1078		for byte in ret.flags.iter_mut() {
1079			*byte |= (*byte & ANY_OPTIONAL_FEATURES_MASK) >> 1;
1080			*byte &= ANY_REQUIRED_FEATURES_MASK;
1081		}
1082		ret
1083	}
1084
1085	/// Constructs a ChannelTypeFeatures with only static_remotekey set
1086	pub fn only_static_remote_key() -> Self {
1087		let mut ret = Self::empty();
1088		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret);
1089		ret
1090	}
1091
1092	/// Constructs a ChannelTypeFeatures with anchors support
1093	pub fn anchors_zero_htlc_fee_and_dependencies() -> Self {
1094		let mut ret = Self::empty();
1095		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret);
1096		<sealed::ChannelTypeContext as sealed::AnchorsZeroFeeHtlcTx>::set_required_bit(&mut ret);
1097		ret
1098	}
1099
1100	/// Constructs a ChannelTypeFeatures with zero fee commitment anchors support.
1101	pub fn anchors_zero_fee_commitments() -> Self {
1102		let mut ret = Self::empty();
1103		<sealed::ChannelTypeContext as sealed::AnchorZeroFeeCommitments>::set_required_bit(
1104			&mut ret,
1105		);
1106		ret
1107	}
1108}
1109
1110impl<T: sealed::Context> Features<T> {
1111	/// Create a blank Features with no features set
1112	pub fn empty() -> Self {
1113		Features { flags: FeatureFlags::empty(), mark: PhantomData }
1114	}
1115
1116	/// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
1117	/// included in the result.
1118	fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
1119		let flag_iter = self.flags.iter().enumerate().filter_map(|(i, byte)| {
1120			if i < T::KNOWN_FEATURE_MASK.len() && i < C::KNOWN_FEATURE_MASK.len() {
1121				Some((i, *byte & T::KNOWN_FEATURE_MASK[i] & C::KNOWN_FEATURE_MASK[i]))
1122			} else {
1123				None
1124			}
1125		});
1126		let mut flags = FeatureFlags::empty();
1127		flags.resize(flag_iter.clone().count(), 0);
1128		for (i, byte) in flag_iter {
1129			flags[i] = byte;
1130		}
1131		Features::<C> { flags, mark: PhantomData }
1132	}
1133
1134	/// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
1135	/// most on-the-wire encodings.
1136	///
1137	/// This is not exported to bindings users as we don't support export across multiple T
1138	pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
1139		Features { flags: FeatureFlags::from(flags), mark: PhantomData }
1140	}
1141
1142	/// Returns the feature set as a list of bytes, in little-endian. This is in reverse byte order
1143	/// from most on-the-wire encodings.
1144	pub fn le_flags(&self) -> &[u8] {
1145		&self.flags
1146	}
1147
1148	/// Create a [`Features`] given a set of flags, in big-endian. This is in byte order from
1149	/// most on-the-wire encodings.
1150	///
1151	/// This is not exported to bindings users as we don't support export across multiple T
1152	pub fn from_be_bytes(mut flags: Vec<u8>) -> Features<T> {
1153		flags.reverse(); // Swap to little-endian
1154		Self { flags: FeatureFlags::from(flags), mark: PhantomData }
1155	}
1156
1157	/// Returns true if this `Features` has any optional flags set
1158	pub fn supports_any_optional_bits(&self) -> bool {
1159		self.flags.iter().any(|&byte| (byte & ANY_OPTIONAL_FEATURES_MASK) != 0)
1160	}
1161
1162	/// Returns true if this `Features` object contains required features unknown by `other`.
1163	pub fn requires_unknown_bits_from(&self, other: &Self) -> bool {
1164		// Bitwise AND-ing with all even bits set except for known features will select required
1165		// unknown features.
1166		self.flags.iter().enumerate().any(|(i, &byte)| {
1167			let unknown_features = unset_features_mask_at_position(other, i);
1168			(byte & (ANY_REQUIRED_FEATURES_MASK & unknown_features)) != 0
1169		})
1170	}
1171
1172	/// Returns the set of required features unknown by `other`, as their bit position.
1173	pub fn required_unknown_bits_from(&self, other: &Self) -> Vec<u64> {
1174		let mut unknown_bits = Vec::new();
1175
1176		// Bitwise AND-ing with all even bits set except for known features will select required
1177		// unknown features.
1178		self.flags.iter().enumerate().for_each(|(i, &byte)| {
1179			let unknown_features = unset_features_mask_at_position(other, i);
1180			if byte & unknown_features != 0 {
1181				for bit in (0..8).step_by(2) {
1182					if ((byte & unknown_features) >> bit) & 1 == 1 {
1183						unknown_bits.push((i as u64) * 8 + bit);
1184					}
1185				}
1186			}
1187		});
1188
1189		unknown_bits
1190	}
1191
1192	/// Returns true if this `Features` object contains unknown feature flags which are set as
1193	/// "required".
1194	pub fn requires_unknown_bits(&self) -> bool {
1195		// Bitwise AND-ing with all even bits set except for known features will select required
1196		// unknown features.
1197		let mut known_chunks = T::KNOWN_FEATURE_MASK.chunks(8);
1198		for chunk in self.flags.chunks(8) {
1199			let mut flag_bytes = [0; 8];
1200			flag_bytes[..chunk.len()].copy_from_slice(&chunk);
1201			let flag_int = u64::from_le_bytes(flag_bytes);
1202
1203			let known_chunk = known_chunks.next().unwrap_or(&[0; 0]);
1204			let mut known_bytes = [0; 8];
1205			known_bytes[..known_chunk.len()].copy_from_slice(&known_chunk);
1206			let known_int = u64::from_le_bytes(known_bytes);
1207
1208			const REQ_MASK: u64 = u64::from_le_bytes([ANY_REQUIRED_FEATURES_MASK; 8]);
1209			if flag_int & (REQ_MASK & !known_int) != 0 {
1210				return true;
1211			}
1212		}
1213		false
1214	}
1215
1216	/// Returns true if this `Features` supports any bits which we do not know of
1217	pub fn supports_unknown_bits(&self) -> bool {
1218		// Bitwise AND-ing with all even and odd bits set except for known features will select
1219		// both required and optional unknown features.
1220		let byte_count = T::KNOWN_FEATURE_MASK.len();
1221		self.flags.iter().enumerate().any(|(i, &byte)| {
1222			let unknown_features =
1223				if i < byte_count { !T::KNOWN_FEATURE_MASK[i] } else { 0b11_11_11_11 };
1224			(byte & unknown_features) != 0
1225		})
1226	}
1227
1228	/// Sets a required feature bit. Errors if `bit` is outside the feature range as defined
1229	/// by [BOLT 9].
1230	///
1231	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
1232	/// be set instead (i.e., `bit - 1`).
1233	///
1234	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
1235	pub fn set_required_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1236		self.set_feature_bit(bit - (bit % 2))
1237	}
1238
1239	/// Sets an optional feature bit. Errors if `bit` is outside the feature range as defined
1240	/// by [BOLT 9].
1241	///
1242	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
1243	/// set instead (i.e., `bit + 1`).
1244	///
1245	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
1246	pub fn set_optional_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1247		self.set_feature_bit(bit + (1 - (bit % 2)))
1248	}
1249
1250	fn set_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1251		if bit > 255 {
1252			return Err(());
1253		}
1254		self.set_bit(bit, false)
1255	}
1256
1257	/// Sets a required custom feature bit. Errors if `bit` is outside the custom range as defined
1258	/// by [bLIP 2] or if it is a known `T` feature.
1259	///
1260	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
1261	/// be set instead (i.e., `bit - 1`).
1262	///
1263	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
1264	pub fn set_required_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1265		self.set_custom_bit(bit - (bit % 2))
1266	}
1267
1268	/// Sets an optional custom feature bit. Errors if `bit` is outside the custom range as defined
1269	/// by [bLIP 2] or if it is a known `T` feature.
1270	///
1271	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
1272	/// set instead (i.e., `bit + 1`).
1273	///
1274	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
1275	pub fn set_optional_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1276		self.set_custom_bit(bit + (1 - (bit % 2)))
1277	}
1278
1279	fn set_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1280		if bit < 256 {
1281			return Err(());
1282		}
1283		self.set_bit(bit, true)
1284	}
1285
1286	fn set_bit(&mut self, bit: usize, custom: bool) -> Result<(), ()> {
1287		let byte_offset = bit / 8;
1288		let mask = 1 << (bit - 8 * byte_offset);
1289		if byte_offset < T::KNOWN_FEATURE_MASK.len() && custom {
1290			if (T::KNOWN_FEATURE_MASK[byte_offset] & mask) != 0 {
1291				return Err(());
1292			}
1293		}
1294
1295		if self.flags.len() <= byte_offset {
1296			self.flags.resize(byte_offset + 1, 0u8);
1297		}
1298
1299		self.flags[byte_offset] |= mask;
1300
1301		Ok(())
1302	}
1303}
1304
1305#[cfg(any(test, feature = "_test_utils"))]
1306impl<T: sealed::UnknownFeature> Features<T> {
1307	/// Sets an unknown feature for testing
1308	pub fn unknown() -> Self {
1309		let mut features = Self::empty();
1310		features.set_unknown_feature_required();
1311		features
1312	}
1313}
1314
1315pub(crate) fn unset_features_mask_at_position<T: sealed::Context>(
1316	other: &Features<T>, index: usize,
1317) -> u8 {
1318	if index < other.flags.len() {
1319		// Form a mask similar to !T::KNOWN_FEATURE_MASK only for `other`
1320		!(other.flags[index]
1321			| ((other.flags[index] >> 1) & ANY_REQUIRED_FEATURES_MASK)
1322			| ((other.flags[index] << 1) & ANY_OPTIONAL_FEATURES_MASK))
1323	} else {
1324		0b11_11_11_11
1325	}
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330	use super::*;
1331
1332	#[test]
1333	fn sanity_test_unknown_bits() {
1334		let features = ChannelFeatures::empty();
1335		assert!(!features.requires_unknown_bits());
1336		assert!(!features.supports_unknown_bits());
1337
1338		let mut features = ChannelFeatures::empty();
1339		features.set_unknown_feature_required();
1340		assert!(features.requires_unknown_bits());
1341		assert!(features.supports_unknown_bits());
1342		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![12344]);
1343
1344		let mut features = ChannelFeatures::empty();
1345		features.set_unknown_feature_optional();
1346		assert!(!features.requires_unknown_bits());
1347		assert!(features.supports_unknown_bits());
1348		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![]);
1349
1350		let mut features = ChannelFeatures::empty();
1351		features.set_unknown_feature_required();
1352		features.set_custom_bit(12346).unwrap();
1353		assert!(features.requires_unknown_bits());
1354		assert!(features.supports_unknown_bits());
1355		assert_eq!(
1356			features.required_unknown_bits_from(&ChannelFeatures::empty()),
1357			vec![12344, 12346]
1358		);
1359
1360		let mut limiter = ChannelFeatures::empty();
1361		limiter.set_unknown_feature_optional();
1362		assert_eq!(features.required_unknown_bits_from(&limiter), vec![12346]);
1363	}
1364
1365	#[test]
1366	fn requires_unknown_bits_from() {
1367		let mut features1 = InitFeatures::empty();
1368		let mut features2 = InitFeatures::empty();
1369		assert!(!features1.requires_unknown_bits_from(&features2));
1370		assert!(!features2.requires_unknown_bits_from(&features1));
1371
1372		features1.set_provide_storage_required();
1373		assert!(features1.requires_unknown_bits_from(&features2));
1374		assert!(!features2.requires_unknown_bits_from(&features1));
1375
1376		features2.set_provide_storage_optional();
1377		assert!(!features1.requires_unknown_bits_from(&features2));
1378		assert!(!features2.requires_unknown_bits_from(&features1));
1379
1380		features1.set_data_loss_protect_required();
1381		assert!(features1.requires_unknown_bits_from(&features2));
1382		assert!(!features2.requires_unknown_bits_from(&features1));
1383
1384		features2.set_data_loss_protect_optional();
1385		assert!(!features1.requires_unknown_bits_from(&features2));
1386		assert!(!features2.requires_unknown_bits_from(&features1));
1387
1388		features2.set_gossip_queries_required();
1389		assert!(!features1.requires_unknown_bits_from(&features2));
1390		assert!(features2.requires_unknown_bits_from(&features1));
1391
1392		features1.set_gossip_queries_optional();
1393		assert!(!features1.requires_unknown_bits_from(&features2));
1394		assert!(!features2.requires_unknown_bits_from(&features1));
1395
1396		features1.set_variable_length_onion_required();
1397		assert!(features1.requires_unknown_bits_from(&features2));
1398		assert!(!features2.requires_unknown_bits_from(&features1));
1399
1400		features2.set_variable_length_onion_optional();
1401		assert!(!features1.requires_unknown_bits_from(&features2));
1402		assert!(!features2.requires_unknown_bits_from(&features1));
1403
1404		features1.set_basic_mpp_required();
1405		features2.set_wumbo_required();
1406		assert!(features1.requires_unknown_bits_from(&features2));
1407		assert!(features2.requires_unknown_bits_from(&features1));
1408	}
1409
1410	#[test]
1411	fn convert_to_context_with_relevant_flags() {
1412		let mut init_features = InitFeatures::empty();
1413		// Set a bunch of features we use, plus initial_routing_sync_required (which shouldn't get
1414		// converted as it's only relevant in an init context).
1415		init_features.set_initial_routing_sync_required();
1416		init_features.set_data_loss_protect_required();
1417		init_features.set_variable_length_onion_required();
1418		init_features.set_static_remote_key_required();
1419		init_features.set_payment_secret_required();
1420		init_features.set_basic_mpp_optional();
1421		init_features.set_wumbo_optional();
1422		init_features.set_anchors_zero_fee_htlc_tx_optional();
1423		init_features.set_route_blinding_optional();
1424		init_features.set_shutdown_any_segwit_optional();
1425		init_features.set_onion_messages_optional();
1426		init_features.set_channel_type_optional();
1427		init_features.set_scid_privacy_optional();
1428		init_features.set_zero_conf_optional();
1429		init_features.set_quiescence_optional();
1430		init_features.set_simple_close_optional();
1431		init_features.set_splicing_optional();
1432
1433		assert!(init_features.initial_routing_sync());
1434		assert!(!init_features.supports_upfront_shutdown_script());
1435		assert!(!init_features.supports_gossip_queries());
1436
1437		let node_features: NodeFeatures = init_features.to_context();
1438		{
1439			// Check that the flags are as expected:
1440			// - option_data_loss_protect (req)
1441			// - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
1442			// - basic_mpp | wumbo | option_anchors_zero_fee_htlc_tx
1443			// - option_route_blinding | opt_shutdown_anysegwit
1444			// - onion_messages
1445			// - option_channel_type | option_scid_alias
1446			// - option_zeroconf
1447			// - option_simple_close
1448			assert_eq!(node_features.flags.len(), 8);
1449			assert_eq!(node_features.flags[0], 0b00000001);
1450			assert_eq!(node_features.flags[1], 0b01010001);
1451			assert_eq!(node_features.flags[2], 0b10001010);
1452			assert_eq!(node_features.flags[3], 0b00001010);
1453			assert_eq!(node_features.flags[4], 0b10001000);
1454			assert_eq!(node_features.flags[5], 0b10100000);
1455			assert_eq!(node_features.flags[6], 0b00001000);
1456			assert_eq!(node_features.flags[7], 0b10100000);
1457		}
1458
1459		// Check that cleared flags are kept blank when converting back:
1460		// - initial_routing_sync was not applicable to NodeContext
1461		// - upfront_shutdown_script was cleared before converting
1462		// - gossip_queries was cleared before converting
1463		let features: InitFeatures = node_features.to_context_internal();
1464		assert!(!features.initial_routing_sync());
1465		assert!(!features.supports_upfront_shutdown_script());
1466		assert!(!init_features.supports_gossip_queries());
1467	}
1468
1469	#[test]
1470	fn convert_to_context_with_unknown_flags() {
1471		// Ensure the `from` context has fewer known feature bytes than the `to` context.
1472		assert!(
1473			<sealed::ChannelContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1474				< <sealed::Bolt11InvoiceContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1475		);
1476		let mut channel_features = ChannelFeatures::empty();
1477		channel_features.set_unknown_feature_optional();
1478		assert!(channel_features.supports_unknown_bits());
1479		let invoice_features: Bolt11InvoiceFeatures = channel_features.to_context_internal();
1480		assert!(!invoice_features.supports_unknown_bits());
1481	}
1482
1483	#[test]
1484	fn set_feature_bits() {
1485		let mut features = Bolt11InvoiceFeatures::empty();
1486		features.set_basic_mpp_optional();
1487		features.set_payment_secret_required();
1488		assert!(features.supports_basic_mpp());
1489		assert!(!features.requires_basic_mpp());
1490		assert!(features.requires_payment_secret());
1491		assert!(features.supports_payment_secret());
1492
1493		// Set flags manually
1494		let mut features = NodeFeatures::empty();
1495		assert!(features.set_optional_feature_bit(55).is_ok());
1496		assert!(features.supports_keysend());
1497		assert!(features.set_optional_feature_bit(255).is_ok());
1498		assert!(features.set_required_feature_bit(256).is_err());
1499	}
1500
1501	#[test]
1502	fn set_custom_bits() {
1503		let mut features = Bolt11InvoiceFeatures::empty();
1504		features.set_variable_length_onion_optional();
1505		assert_eq!(features.flags[1], 0b00000010);
1506
1507		assert!(features.set_optional_custom_bit(255).is_err());
1508		assert!(features.set_required_custom_bit(256).is_ok());
1509		assert!(features.set_required_custom_bit(258).is_ok());
1510		assert_eq!(features.flags[31], 0b00000000);
1511		assert_eq!(features.flags[32], 0b00000101);
1512
1513		let known_bit = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::EVEN_BIT;
1514		let byte_offset = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::BYTE_OFFSET;
1515		assert_eq!(byte_offset, 1);
1516		assert_eq!(features.flags[byte_offset], 0b00000010);
1517		assert!(features.set_required_custom_bit(known_bit).is_err());
1518		assert_eq!(features.flags[byte_offset], 0b00000010);
1519
1520		let mut features = Bolt11InvoiceFeatures::empty();
1521		assert!(features.set_optional_custom_bit(256).is_ok());
1522		assert!(features.set_optional_custom_bit(259).is_ok());
1523		assert_eq!(features.flags[32], 0b00001010);
1524
1525		let mut features = Bolt11InvoiceFeatures::empty();
1526		assert!(features.set_required_custom_bit(257).is_ok());
1527		assert!(features.set_required_custom_bit(258).is_ok());
1528		assert_eq!(features.flags[32], 0b00000101);
1529	}
1530
1531	#[test]
1532	fn test_channel_type_mapping() {
1533		// If we map an Bolt11InvoiceFeatures with StaticRemoteKey optional, it should map into a
1534		// required-StaticRemoteKey ChannelTypeFeatures.
1535		let mut init_features = InitFeatures::empty();
1536		init_features.set_static_remote_key_optional();
1537		let converted_features = ChannelTypeFeatures::from_init(&init_features);
1538		assert_eq!(converted_features, ChannelTypeFeatures::only_static_remote_key());
1539		assert!(!converted_features.supports_any_optional_bits());
1540		assert!(converted_features.requires_static_remote_key());
1541	}
1542
1543	#[test]
1544	fn test_excess_zero_bytes_ignored() {
1545		// Checks that `Hash` and `PartialEq` ignore excess zero bytes, which may appear due to
1546		// feature conversion or because a peer serialized their feature poorly.
1547		use std::collections::hash_map::DefaultHasher;
1548		use std::hash::{Hash, Hasher};
1549
1550		let mut zerod_features = InitFeatures::empty();
1551		zerod_features.flags = FeatureFlags::Heap(vec![0]);
1552		let empty_features = InitFeatures::empty();
1553		assert!(empty_features.flags.is_empty());
1554
1555		assert_eq!(zerod_features, empty_features);
1556
1557		let mut zerod_hash = DefaultHasher::new();
1558		zerod_features.hash(&mut zerod_hash);
1559		let mut empty_hash = DefaultHasher::new();
1560		empty_features.hash(&mut empty_hash);
1561		assert_eq!(zerod_hash.finish(), empty_hash.finish());
1562	}
1563
1564	#[test]
1565	fn test_feature_flags_transitions() {
1566		// Tests transitions from stack to heap and back in `FeatureFlags`
1567		let mut flags = FeatureFlags::empty();
1568		assert!(matches!(flags, FeatureFlags::Held { .. }));
1569
1570		flags.resize(DIRECT_ALLOC_BYTES, 42);
1571		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES);
1572		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1573		assert!(matches!(flags, FeatureFlags::Held { .. }));
1574
1575		flags.resize(DIRECT_ALLOC_BYTES * 2, 43);
1576		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES * 2);
1577		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1578		assert!(flags.iter().skip(DIRECT_ALLOC_BYTES).all(|b| *b == 43));
1579		assert!(matches!(flags, FeatureFlags::Heap(_)));
1580
1581		flags.resize(DIRECT_ALLOC_BYTES, 0);
1582		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES);
1583		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1584		assert!(matches!(flags, FeatureFlags::Held { .. }));
1585	}
1586}