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