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//!
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 | SplicePrototype,
170			// Byte 8 - 16
171			,,,,,,,,,
172			// Byte 17
173			AnchorZeroFeeCommitmentsStaging,
174			// Byte 18
175			,
176			// Byte 19
177			HtlcHold,
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 | SplicePrototype,
199			// Byte 8 - 16
200			,,,,,,,,,
201			// Byte 17
202			AnchorZeroFeeCommitmentsStaging,
203			// Byte 18
204			,
205			// Byte 19
206			HtlcHold,
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!(
653		51,
654		ZeroConf,
655		[InitContext, NodeContext, ChannelTypeContext],
656		"Feature flags for accepting channels with zero confirmations. Called `option_zeroconf` in the BOLTs",
657		set_zero_conf_optional,
658		set_zero_conf_required,
659		clear_zero_conf,
660		supports_zero_conf,
661		requires_zero_conf
662	);
663	define_feature!(
664		55,
665		Keysend,
666		[NodeContext],
667		"Feature flags for keysend payments.",
668		set_keysend_optional,
669		set_keysend_required,
670		clear_keysend,
671		supports_keysend,
672		requires_keysend
673	);
674	define_feature!(
675		57,
676		Trampoline,
677		[InitContext, NodeContext, Bolt11InvoiceContext, Bolt12InvoiceContext],
678		"Feature flags for Trampoline routing.",
679		set_trampoline_routing_optional,
680		set_trampoline_routing_required,
681		clear_trampoline_routing,
682		supports_trampoline_routing,
683		requires_trampoline_routing
684	);
685	define_feature!(
686		61,
687		SimpleClose,
688		[InitContext, NodeContext],
689		"Feature flags for simplified closing negotiation.",
690		set_simple_close_optional,
691		set_simple_close_required,
692		clear_simple_close,
693		supports_simple_close,
694		requires_simple_close
695	);
696	define_feature!(
697		63,
698		SpliceProduction,
699		[InitContext, NodeContext],
700		"Feature flags for channel splicing.",
701		set_splicing_production_optional,
702		set_splicing_production_required,
703		clear_splicing_production,
704		supports_splicing_production,
705		requires_splicing_production
706	);
707	// By default, allocate enough bytes to cover up to Splice. Update this as new features are
708	// added which we expect to appear commonly across contexts.
709	pub(super) const MIN_FEATURES_ALLOCATION_BYTES: usize = (63 + 7) / 8;
710	define_feature!(
711		141, // The BOLTs PR uses feature bit 40/41, so add +100 for the experimental bit
712		AnchorZeroFeeCommitmentsStaging,
713		[InitContext, NodeContext, ChannelTypeContext],
714		"Feature flags for `option_zero_fee_commitments`.",
715		set_anchor_zero_fee_commitments_optional,
716		set_anchor_zero_fee_commitments_required,
717		clear_anchor_zero_fee_commitments,
718		supports_anchor_zero_fee_commitments,
719		requires_anchor_zero_fee_commitments
720	);
721	define_feature!(
722		153, // The BOLTs PR uses feature bit 52/53, so add +100 for the experimental bit
723		HtlcHold,
724		[InitContext, NodeContext],
725		"Feature flags for holding HTLCs and forwarding on receipt of an onion message",
726		set_htlc_hold_optional,
727		set_htlc_hold_required,
728		clear_htlc_hold,
729		supports_htlc_hold,
730		requires_htlc_hold
731	);
732	define_feature!(
733		63, // Actually the SpliceProduction feature
734		SplicePrototype,
735		[InitContext, NodeContext],
736		"Feature flags for channel splicing.",
737		set_splicing_optional,
738		set_splicing_required,
739		clear_splicing,
740		supports_splicing,
741		requires_splicing
742	);
743	define_feature!(
744		259,
745		DnsResolver,
746		[NodeContext],
747		"Feature flags for DNS resolving.",
748		set_dns_resolution_optional,
749		set_dns_resolution_required,
750		clear_dns_resolution,
751		supports_dns_resolution,
752		requires_dns_resolution
753	);
754
755	// Note: update the module-level docs when a new feature bit is added!
756
757	#[cfg(any(test, feature = "_test_utils"))]
758	define_feature!(
759		12345,
760		UnknownFeature,
761		[
762			NodeContext,
763			ChannelContext,
764			Bolt11InvoiceContext,
765			OfferContext,
766			InvoiceRequestContext,
767			Bolt12InvoiceContext,
768			BlindedHopContext
769		],
770		"Feature flags for an unknown feature used in testing.",
771		set_unknown_feature_optional,
772		set_unknown_feature_required,
773		clear_unknown_feature,
774		supports_unknown_test_feature,
775		requires_unknown_test_feature
776	);
777}
778
779const ANY_REQUIRED_FEATURES_MASK: u8 = 0b01_01_01_01;
780const ANY_OPTIONAL_FEATURES_MASK: u8 = 0b10_10_10_10;
781
782// Vecs are always 3 pointers long, so `FeatureFlags` is never shorter than 24 bytes on 64-bit
783// platforms no matter what we do.
784//
785// Luckily, because `Vec` uses a `NonNull` pointer to its buffer, the two-variant enum is free
786// space-wise, but we only get the remaining 2 usizes in length available for our own stuff (as any
787// other value is interpreted as the `Heap` variant).
788//
789// Thus, as long as we never use more than 16 bytes (15 bytes for the data and one byte for the
790// length) for our Held variant `FeatureFlags` is the same length as a `Vec` in memory.
791const DIRECT_ALLOC_BYTES: usize = if sealed::MIN_FEATURES_ALLOCATION_BYTES > 8 * 2 - 1 {
792	sealed::MIN_FEATURES_ALLOCATION_BYTES
793} else {
794	8 * 2 - 1
795};
796const _ASSERT: () = assert!(DIRECT_ALLOC_BYTES <= u8::MAX as usize);
797
798#[cfg(fuzzing)]
799#[derive(Clone, PartialEq, Eq)]
800pub enum FeatureFlags {
801	Held { bytes: [u8; DIRECT_ALLOC_BYTES], len: u8 },
802	Heap(Vec<u8>),
803}
804
805#[cfg(not(fuzzing))]
806#[derive(Clone, PartialEq, Eq)]
807enum FeatureFlags {
808	Held { bytes: [u8; DIRECT_ALLOC_BYTES], len: u8 },
809	Heap(Vec<u8>),
810}
811
812impl FeatureFlags {
813	/// Constructs an empty [`FeatureFlags`]
814	pub fn empty() -> Self {
815		Self::Held { bytes: [0; DIRECT_ALLOC_BYTES], len: 0 }
816	}
817
818	/// Constructs a [`FeatureFlags`] from the given bytes
819	pub fn from(vec: Vec<u8>) -> Self {
820		if vec.len() <= DIRECT_ALLOC_BYTES {
821			let mut bytes = [0; DIRECT_ALLOC_BYTES];
822			bytes[..vec.len()].copy_from_slice(&vec);
823			Self::Held { bytes, len: vec.len() as u8 }
824		} else {
825			Self::Heap(vec)
826		}
827	}
828
829	/// Resizes a [`FeatureFlags`] to the given length, padding with `default` if required.
830	///
831	/// See [`Vec::resize`] for more info.
832	pub fn resize(&mut self, new_len: usize, default: u8) {
833		match self {
834			Self::Held { bytes, len } => {
835				let start_len = *len as usize;
836				if new_len <= DIRECT_ALLOC_BYTES {
837					bytes[start_len..].copy_from_slice(&[default; DIRECT_ALLOC_BYTES][start_len..]);
838					*len = new_len as u8;
839				} else {
840					let mut vec = Vec::new();
841					vec.resize(new_len, default);
842					vec[..start_len].copy_from_slice(&bytes[..start_len]);
843					*self = Self::Heap(vec);
844				}
845			},
846			Self::Heap(vec) => {
847				vec.resize(new_len, default);
848				if new_len <= DIRECT_ALLOC_BYTES {
849					let mut bytes = [0; DIRECT_ALLOC_BYTES];
850					bytes[..new_len].copy_from_slice(&vec[..new_len]);
851					*self = Self::Held { bytes, len: new_len as u8 };
852				}
853			},
854		}
855	}
856
857	/// Fetches the length of the [`FeatureFlags`], in bytes.
858	pub fn len(&self) -> usize {
859		self.deref().len()
860	}
861
862	/// Fetches an iterator over the bytes of this [`FeatureFlags`]
863	pub fn iter(
864		&self,
865	) -> impl Clone + ExactSizeIterator<Item = &u8> + DoubleEndedIterator<Item = &u8> {
866		let slice = self.deref();
867		slice.iter()
868	}
869
870	/// Fetches a mutable iterator over the bytes of this [`FeatureFlags`]
871	pub fn iter_mut(
872		&mut self,
873	) -> impl ExactSizeIterator<Item = &mut u8> + DoubleEndedIterator<Item = &mut u8> {
874		let slice = self.deref_mut();
875		slice.iter_mut()
876	}
877}
878
879impl Deref for FeatureFlags {
880	type Target = [u8];
881	fn deref(&self) -> &[u8] {
882		match self {
883			FeatureFlags::Held { bytes, len } => &bytes[..*len as usize],
884			FeatureFlags::Heap(vec) => &vec,
885		}
886	}
887}
888
889impl DerefMut for FeatureFlags {
890	fn deref_mut(&mut self) -> &mut [u8] {
891		match self {
892			FeatureFlags::Held { bytes, len } => &mut bytes[..*len as usize],
893			FeatureFlags::Heap(vec) => &mut vec[..],
894		}
895	}
896}
897
898impl PartialOrd for FeatureFlags {
899	fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
900		Some(self.cmp(other))
901	}
902}
903impl Ord for FeatureFlags {
904	fn cmp(&self, other: &Self) -> cmp::Ordering {
905		self.deref().cmp(other.deref())
906	}
907}
908impl fmt::Debug for FeatureFlags {
909	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
910		self.deref().fmt(fmt)
911	}
912}
913
914/// Tracks the set of features which a node implements, templated by the context in which it
915/// appears.
916///
917/// This is not exported to bindings users as we map the concrete feature types below directly instead
918#[derive(Eq)]
919pub struct Features<T: sealed::Context + ?Sized> {
920	/// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
921	flags: FeatureFlags,
922	mark: PhantomData<T>,
923}
924
925impl<T: sealed::Context, Rhs: Borrow<Self>> core::ops::BitOrAssign<Rhs> for Features<T> {
926	fn bitor_assign(&mut self, rhs: Rhs) {
927		let total_feature_len = cmp::max(self.flags.len(), rhs.borrow().flags.len());
928		self.flags.resize(total_feature_len, 0u8);
929		for (byte, rhs_byte) in self.flags.iter_mut().zip(rhs.borrow().flags.iter()) {
930			*byte |= *rhs_byte;
931		}
932	}
933}
934
935impl<T: sealed::Context> core::ops::BitOr for Features<T> {
936	type Output = Self;
937
938	fn bitor(mut self, o: Self) -> Self {
939		self |= o;
940		self
941	}
942}
943
944impl<T: sealed::Context> Clone for Features<T> {
945	fn clone(&self) -> Self {
946		Self { flags: self.flags.clone(), mark: PhantomData }
947	}
948}
949impl<T: sealed::Context> Hash for Features<T> {
950	fn hash<H: Hasher>(&self, hasher: &mut H) {
951		let mut nonzero_flags = &self.flags[..];
952		while nonzero_flags.last() == Some(&0) {
953			nonzero_flags = &nonzero_flags[..nonzero_flags.len() - 1];
954		}
955		nonzero_flags.hash(hasher);
956	}
957}
958impl<T: sealed::Context + ?Sized> PartialEq for Features<T> {
959	fn eq(&self, o: &Self) -> bool {
960		let mut o_iter = o.flags.iter();
961		let mut self_iter = self.flags.iter();
962		loop {
963			match (o_iter.next(), self_iter.next()) {
964				(Some(o), Some(us)) => {
965					if o != us {
966						return false;
967					}
968				},
969				(Some(b), None) | (None, Some(b)) => {
970					if *b != 0 {
971						return false;
972					}
973				},
974				(None, None) => return true,
975			}
976		}
977	}
978}
979impl<T: sealed::Context> PartialOrd for Features<T> {
980	fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
981		self.flags.partial_cmp(&other.flags)
982	}
983}
984impl<T: sealed::Context + Eq> Ord for Features<T> {
985	fn cmp(&self, other: &Self) -> cmp::Ordering {
986		self.flags.cmp(&other.flags)
987	}
988}
989impl<T: sealed::Context> fmt::Debug for Features<T> {
990	fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
991		self.flags.fmt(fmt)
992	}
993}
994
995/// Features used within an `init` message.
996pub type InitFeatures = Features<sealed::InitContext>;
997/// Features used within a `node_announcement` message.
998pub type NodeFeatures = Features<sealed::NodeContext>;
999/// Features used within a `channel_announcement` message.
1000pub type ChannelFeatures = Features<sealed::ChannelContext>;
1001/// Features used within an invoice.
1002pub type Bolt11InvoiceFeatures = Features<sealed::Bolt11InvoiceContext>;
1003/// Features used within an `offer`.
1004pub type OfferFeatures = Features<sealed::OfferContext>;
1005/// Features used within an `invoice_request`.
1006pub type InvoiceRequestFeatures = Features<sealed::InvoiceRequestContext>;
1007/// Features used within an `invoice`.
1008pub type Bolt12InvoiceFeatures = Features<sealed::Bolt12InvoiceContext>;
1009/// Features used within BOLT 4 encrypted_data_tlv and BOLT 12 blinded_payinfo
1010pub type BlindedHopFeatures = Features<sealed::BlindedHopContext>;
1011
1012/// Features used within the channel_type field in an OpenChannel message.
1013///
1014/// A channel is always of some known "type", describing the transaction formats used and the exact
1015/// semantics of our interaction with our peer.
1016///
1017/// Note that because a channel is a specific type which is proposed by the opener and accepted by
1018/// the counterparty, only required features are allowed here.
1019///
1020/// This is serialized differently from other feature types - it is not prefixed by a length, and
1021/// thus must only appear inside a TLV where its length is known in advance.
1022pub type ChannelTypeFeatures = Features<sealed::ChannelTypeContext>;
1023
1024impl InitFeatures {
1025	#[doc(hidden)]
1026	/// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
1027	/// are included in the result.
1028	///
1029	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1030	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1031		self.to_context_internal()
1032	}
1033}
1034
1035impl Bolt11InvoiceFeatures {
1036	#[doc(hidden)]
1037	/// Converts `Bolt11InvoiceFeatures` to `Features<C>`. Only known `Bolt11InvoiceFeatures` relevant to
1038	/// context `C` are included in the result.
1039	///
1040	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1041	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1042		self.to_context_internal()
1043	}
1044
1045	/// Getting a route for a keysend payment to a private node requires providing the payee's
1046	/// features (since they were not announced in a node announcement). However, keysend payments
1047	/// don't have an invoice to pull the payee's features from, so this method is provided for use
1048	/// when a [`Bolt11InvoiceFeatures`] is required in a route.
1049	///
1050	/// MPP keysend is not widely supported yet, so we parameterize support to allow the user to
1051	/// choose whether their router should find multi-part routes.
1052	pub fn for_keysend(allow_mpp: bool) -> Bolt11InvoiceFeatures {
1053		let mut res = Bolt11InvoiceFeatures::empty();
1054		res.set_variable_length_onion_optional();
1055		if allow_mpp {
1056			res.set_basic_mpp_optional();
1057		}
1058		res
1059	}
1060}
1061
1062impl Bolt12InvoiceFeatures {
1063	#[doc(hidden)]
1064	/// Converts [`Bolt12InvoiceFeatures`] to [`Features<C>`]. Only known [`Bolt12InvoiceFeatures`]
1065	/// relevant to context `C` are included in the result.
1066	///
1067	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1068	pub fn to_context<C: sealed::Context>(&self) -> Features<C> {
1069		self.to_context_internal()
1070	}
1071}
1072
1073impl ChannelTypeFeatures {
1074	#[doc(hidden)]
1075	/// Maps the relevant `InitFeatures` to `ChannelTypeFeatures`. Any unknown features to
1076	/// `ChannelTypeFeatures` are not included in the result.
1077	///
1078	/// This is not exported to bindings users as it shouldn't be used outside of LDK
1079	pub fn from_init(init: &InitFeatures) -> Self {
1080		let mut ret = init.to_context_internal();
1081		// ChannelTypeFeatures must only contain required bits, so we OR the required forms of all
1082		// optional bits and then AND out the optional ones.
1083		for byte in ret.flags.iter_mut() {
1084			*byte |= (*byte & ANY_OPTIONAL_FEATURES_MASK) >> 1;
1085			*byte &= ANY_REQUIRED_FEATURES_MASK;
1086		}
1087		ret
1088	}
1089
1090	/// Constructs a ChannelTypeFeatures with only static_remotekey set
1091	pub fn only_static_remote_key() -> Self {
1092		let mut ret = Self::empty();
1093		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret);
1094		ret
1095	}
1096
1097	/// Constructs a ChannelTypeFeatures with anchors support
1098	pub fn anchors_zero_htlc_fee_and_dependencies() -> Self {
1099		let mut ret = Self::empty();
1100		<sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret);
1101		<sealed::ChannelTypeContext as sealed::AnchorsZeroFeeHtlcTx>::set_required_bit(&mut ret);
1102		ret
1103	}
1104
1105	/// Constructs a ChannelTypeFeatures with zero fee commitment anchors support.
1106	pub fn anchors_zero_fee_commitments() -> Self {
1107		let mut ret = Self::empty();
1108		<sealed::ChannelTypeContext as sealed::AnchorZeroFeeCommitmentsStaging>::set_required_bit(
1109			&mut ret,
1110		);
1111		ret
1112	}
1113}
1114
1115impl<T: sealed::Context> Features<T> {
1116	/// Create a blank Features with no features set
1117	pub fn empty() -> Self {
1118		Features { flags: FeatureFlags::empty(), mark: PhantomData }
1119	}
1120
1121	/// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
1122	/// included in the result.
1123	fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
1124		let flag_iter = self.flags.iter().enumerate().filter_map(|(i, byte)| {
1125			if i < T::KNOWN_FEATURE_MASK.len() && i < C::KNOWN_FEATURE_MASK.len() {
1126				Some((i, *byte & T::KNOWN_FEATURE_MASK[i] & C::KNOWN_FEATURE_MASK[i]))
1127			} else {
1128				None
1129			}
1130		});
1131		let mut flags = FeatureFlags::empty();
1132		flags.resize(flag_iter.clone().count(), 0);
1133		for (i, byte) in flag_iter {
1134			flags[i] = byte;
1135		}
1136		Features::<C> { flags, mark: PhantomData }
1137	}
1138
1139	/// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
1140	/// most on-the-wire encodings.
1141	///
1142	/// This is not exported to bindings users as we don't support export across multiple T
1143	pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
1144		Features { flags: FeatureFlags::from(flags), mark: PhantomData }
1145	}
1146
1147	/// Returns the feature set as a list of bytes, in little-endian. This is in reverse byte order
1148	/// from most on-the-wire encodings.
1149	pub fn le_flags(&self) -> &[u8] {
1150		&self.flags
1151	}
1152
1153	/// Create a [`Features`] given a set of flags, in big-endian. This is in byte order from
1154	/// most on-the-wire encodings.
1155	///
1156	/// This is not exported to bindings users as we don't support export across multiple T
1157	pub fn from_be_bytes(mut flags: Vec<u8>) -> Features<T> {
1158		flags.reverse(); // Swap to little-endian
1159		Self { flags: FeatureFlags::from(flags), mark: PhantomData }
1160	}
1161
1162	/// Returns true if this `Features` has any optional flags set
1163	pub fn supports_any_optional_bits(&self) -> bool {
1164		self.flags.iter().any(|&byte| (byte & ANY_OPTIONAL_FEATURES_MASK) != 0)
1165	}
1166
1167	/// Returns true if this `Features` object contains required features unknown by `other`.
1168	pub fn requires_unknown_bits_from(&self, other: &Self) -> bool {
1169		// Bitwise AND-ing with all even bits set except for known features will select required
1170		// unknown features.
1171		self.flags.iter().enumerate().any(|(i, &byte)| {
1172			let unknown_features = unset_features_mask_at_position(other, i);
1173			(byte & (ANY_REQUIRED_FEATURES_MASK & unknown_features)) != 0
1174		})
1175	}
1176
1177	/// Returns the set of required features unknown by `other`, as their bit position.
1178	pub fn required_unknown_bits_from(&self, other: &Self) -> Vec<u64> {
1179		let mut unknown_bits = Vec::new();
1180
1181		// Bitwise AND-ing with all even bits set except for known features will select required
1182		// unknown features.
1183		self.flags.iter().enumerate().for_each(|(i, &byte)| {
1184			let unknown_features = unset_features_mask_at_position(other, i);
1185			if byte & unknown_features != 0 {
1186				for bit in (0..8).step_by(2) {
1187					if ((byte & unknown_features) >> bit) & 1 == 1 {
1188						unknown_bits.push((i as u64) * 8 + bit);
1189					}
1190				}
1191			}
1192		});
1193
1194		unknown_bits
1195	}
1196
1197	/// Returns true if this `Features` object contains unknown feature flags which are set as
1198	/// "required".
1199	pub fn requires_unknown_bits(&self) -> bool {
1200		// Bitwise AND-ing with all even bits set except for known features will select required
1201		// unknown features.
1202		let mut known_chunks = T::KNOWN_FEATURE_MASK.chunks(8);
1203		for chunk in self.flags.chunks(8) {
1204			let mut flag_bytes = [0; 8];
1205			flag_bytes[..chunk.len()].copy_from_slice(&chunk);
1206			let flag_int = u64::from_le_bytes(flag_bytes);
1207
1208			let known_chunk = known_chunks.next().unwrap_or(&[0; 0]);
1209			let mut known_bytes = [0; 8];
1210			known_bytes[..known_chunk.len()].copy_from_slice(&known_chunk);
1211			let known_int = u64::from_le_bytes(known_bytes);
1212
1213			const REQ_MASK: u64 = u64::from_le_bytes([ANY_REQUIRED_FEATURES_MASK; 8]);
1214			if flag_int & (REQ_MASK & !known_int) != 0 {
1215				return true;
1216			}
1217		}
1218		false
1219	}
1220
1221	/// Returns true if this `Features` supports any bits which we do not know of
1222	pub fn supports_unknown_bits(&self) -> bool {
1223		// Bitwise AND-ing with all even and odd bits set except for known features will select
1224		// both required and optional unknown features.
1225		let byte_count = T::KNOWN_FEATURE_MASK.len();
1226		self.flags.iter().enumerate().any(|(i, &byte)| {
1227			let unknown_features =
1228				if i < byte_count { !T::KNOWN_FEATURE_MASK[i] } else { 0b11_11_11_11 };
1229			(byte & unknown_features) != 0
1230		})
1231	}
1232
1233	/// Sets a required feature bit. Errors if `bit` is outside the feature range as defined
1234	/// by [BOLT 9].
1235	///
1236	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
1237	/// be set instead (i.e., `bit - 1`).
1238	///
1239	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
1240	pub fn set_required_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1241		self.set_feature_bit(bit - (bit % 2))
1242	}
1243
1244	/// Sets an optional feature bit. Errors if `bit` is outside the feature range as defined
1245	/// by [BOLT 9].
1246	///
1247	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
1248	/// set instead (i.e., `bit + 1`).
1249	///
1250	/// [BOLT 9]: https://github.com/lightning/bolts/blob/master/09-features.md
1251	pub fn set_optional_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1252		self.set_feature_bit(bit + (1 - (bit % 2)))
1253	}
1254
1255	fn set_feature_bit(&mut self, bit: usize) -> Result<(), ()> {
1256		if bit > 255 {
1257			return Err(());
1258		}
1259		self.set_bit(bit, false)
1260	}
1261
1262	/// Sets a required custom feature bit. Errors if `bit` is outside the custom range as defined
1263	/// by [bLIP 2] or if it is a known `T` feature.
1264	///
1265	/// Note: Required bits are even. If an odd bit is given, then the corresponding even bit will
1266	/// be set instead (i.e., `bit - 1`).
1267	///
1268	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
1269	pub fn set_required_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1270		self.set_custom_bit(bit - (bit % 2))
1271	}
1272
1273	/// Sets an optional custom feature bit. Errors if `bit` is outside the custom range as defined
1274	/// by [bLIP 2] or if it is a known `T` feature.
1275	///
1276	/// Note: Optional bits are odd. If an even bit is given, then the corresponding odd bit will be
1277	/// set instead (i.e., `bit + 1`).
1278	///
1279	/// [bLIP 2]: https://github.com/lightning/blips/blob/master/blip-0002.md#feature-bits
1280	pub fn set_optional_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1281		self.set_custom_bit(bit + (1 - (bit % 2)))
1282	}
1283
1284	fn set_custom_bit(&mut self, bit: usize) -> Result<(), ()> {
1285		if bit < 256 {
1286			return Err(());
1287		}
1288		self.set_bit(bit, true)
1289	}
1290
1291	fn set_bit(&mut self, bit: usize, custom: bool) -> Result<(), ()> {
1292		let byte_offset = bit / 8;
1293		let mask = 1 << (bit - 8 * byte_offset);
1294		if byte_offset < T::KNOWN_FEATURE_MASK.len() && custom {
1295			if (T::KNOWN_FEATURE_MASK[byte_offset] & mask) != 0 {
1296				return Err(());
1297			}
1298		}
1299
1300		if self.flags.len() <= byte_offset {
1301			self.flags.resize(byte_offset + 1, 0u8);
1302		}
1303
1304		self.flags[byte_offset] |= mask;
1305
1306		Ok(())
1307	}
1308}
1309
1310#[cfg(any(test, feature = "_test_utils"))]
1311impl<T: sealed::UnknownFeature> Features<T> {
1312	/// Sets an unknown feature for testing
1313	pub fn unknown() -> Self {
1314		let mut features = Self::empty();
1315		features.set_unknown_feature_required();
1316		features
1317	}
1318}
1319
1320pub(crate) fn unset_features_mask_at_position<T: sealed::Context>(
1321	other: &Features<T>, index: usize,
1322) -> u8 {
1323	if index < other.flags.len() {
1324		// Form a mask similar to !T::KNOWN_FEATURE_MASK only for `other`
1325		!(other.flags[index]
1326			| ((other.flags[index] >> 1) & ANY_REQUIRED_FEATURES_MASK)
1327			| ((other.flags[index] << 1) & ANY_OPTIONAL_FEATURES_MASK))
1328	} else {
1329		0b11_11_11_11
1330	}
1331}
1332
1333#[cfg(test)]
1334mod tests {
1335	use super::*;
1336
1337	#[test]
1338	fn sanity_test_unknown_bits() {
1339		let features = ChannelFeatures::empty();
1340		assert!(!features.requires_unknown_bits());
1341		assert!(!features.supports_unknown_bits());
1342
1343		let mut features = ChannelFeatures::empty();
1344		features.set_unknown_feature_required();
1345		assert!(features.requires_unknown_bits());
1346		assert!(features.supports_unknown_bits());
1347		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![12344]);
1348
1349		let mut features = ChannelFeatures::empty();
1350		features.set_unknown_feature_optional();
1351		assert!(!features.requires_unknown_bits());
1352		assert!(features.supports_unknown_bits());
1353		assert_eq!(features.required_unknown_bits_from(&ChannelFeatures::empty()), vec![]);
1354
1355		let mut features = ChannelFeatures::empty();
1356		features.set_unknown_feature_required();
1357		features.set_custom_bit(12346).unwrap();
1358		assert!(features.requires_unknown_bits());
1359		assert!(features.supports_unknown_bits());
1360		assert_eq!(
1361			features.required_unknown_bits_from(&ChannelFeatures::empty()),
1362			vec![12344, 12346]
1363		);
1364
1365		let mut limiter = ChannelFeatures::empty();
1366		limiter.set_unknown_feature_optional();
1367		assert_eq!(features.required_unknown_bits_from(&limiter), vec![12346]);
1368	}
1369
1370	#[test]
1371	fn requires_unknown_bits_from() {
1372		let mut features1 = InitFeatures::empty();
1373		let mut features2 = InitFeatures::empty();
1374		assert!(!features1.requires_unknown_bits_from(&features2));
1375		assert!(!features2.requires_unknown_bits_from(&features1));
1376
1377		features1.set_provide_storage_required();
1378		assert!(features1.requires_unknown_bits_from(&features2));
1379		assert!(!features2.requires_unknown_bits_from(&features1));
1380
1381		features2.set_provide_storage_optional();
1382		assert!(!features1.requires_unknown_bits_from(&features2));
1383		assert!(!features2.requires_unknown_bits_from(&features1));
1384
1385		features1.set_data_loss_protect_required();
1386		assert!(features1.requires_unknown_bits_from(&features2));
1387		assert!(!features2.requires_unknown_bits_from(&features1));
1388
1389		features2.set_data_loss_protect_optional();
1390		assert!(!features1.requires_unknown_bits_from(&features2));
1391		assert!(!features2.requires_unknown_bits_from(&features1));
1392
1393		features2.set_gossip_queries_required();
1394		assert!(!features1.requires_unknown_bits_from(&features2));
1395		assert!(features2.requires_unknown_bits_from(&features1));
1396
1397		features1.set_gossip_queries_optional();
1398		assert!(!features1.requires_unknown_bits_from(&features2));
1399		assert!(!features2.requires_unknown_bits_from(&features1));
1400
1401		features1.set_variable_length_onion_required();
1402		assert!(features1.requires_unknown_bits_from(&features2));
1403		assert!(!features2.requires_unknown_bits_from(&features1));
1404
1405		features2.set_variable_length_onion_optional();
1406		assert!(!features1.requires_unknown_bits_from(&features2));
1407		assert!(!features2.requires_unknown_bits_from(&features1));
1408
1409		features1.set_basic_mpp_required();
1410		features2.set_wumbo_required();
1411		assert!(features1.requires_unknown_bits_from(&features2));
1412		assert!(features2.requires_unknown_bits_from(&features1));
1413	}
1414
1415	#[test]
1416	fn convert_to_context_with_relevant_flags() {
1417		let mut init_features = InitFeatures::empty();
1418		// Set a bunch of features we use, plus initial_routing_sync_required (which shouldn't get
1419		// converted as it's only relevant in an init context).
1420		init_features.set_initial_routing_sync_required();
1421		init_features.set_data_loss_protect_required();
1422		init_features.set_variable_length_onion_required();
1423		init_features.set_static_remote_key_required();
1424		init_features.set_payment_secret_required();
1425		init_features.set_basic_mpp_optional();
1426		init_features.set_wumbo_optional();
1427		init_features.set_anchors_zero_fee_htlc_tx_optional();
1428		init_features.set_route_blinding_optional();
1429		init_features.set_shutdown_any_segwit_optional();
1430		init_features.set_onion_messages_optional();
1431		init_features.set_channel_type_optional();
1432		init_features.set_scid_privacy_optional();
1433		init_features.set_zero_conf_optional();
1434		init_features.set_quiescence_optional();
1435		init_features.set_simple_close_optional();
1436		init_features.set_splicing_optional();
1437
1438		assert!(init_features.initial_routing_sync());
1439		assert!(!init_features.supports_upfront_shutdown_script());
1440		assert!(!init_features.supports_gossip_queries());
1441
1442		let node_features: NodeFeatures = init_features.to_context();
1443		{
1444			// Check that the flags are as expected:
1445			// - option_data_loss_protect (req)
1446			// - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
1447			// - basic_mpp | wumbo | option_anchors_zero_fee_htlc_tx
1448			// - option_route_blinding | opt_shutdown_anysegwit
1449			// - onion_messages
1450			// - option_channel_type | option_scid_alias
1451			// - option_zeroconf
1452			// - option_simple_close
1453			assert_eq!(node_features.flags.len(), 8);
1454			assert_eq!(node_features.flags[0], 0b00000001);
1455			assert_eq!(node_features.flags[1], 0b01010001);
1456			assert_eq!(node_features.flags[2], 0b10001010);
1457			assert_eq!(node_features.flags[3], 0b00001010);
1458			assert_eq!(node_features.flags[4], 0b10001000);
1459			assert_eq!(node_features.flags[5], 0b10100000);
1460			assert_eq!(node_features.flags[6], 0b00001000);
1461			assert_eq!(node_features.flags[7], 0b10100000);
1462		}
1463
1464		// Check that cleared flags are kept blank when converting back:
1465		// - initial_routing_sync was not applicable to NodeContext
1466		// - upfront_shutdown_script was cleared before converting
1467		// - gossip_queries was cleared before converting
1468		let features: InitFeatures = node_features.to_context_internal();
1469		assert!(!features.initial_routing_sync());
1470		assert!(!features.supports_upfront_shutdown_script());
1471		assert!(!init_features.supports_gossip_queries());
1472	}
1473
1474	#[test]
1475	fn convert_to_context_with_unknown_flags() {
1476		// Ensure the `from` context has fewer known feature bytes than the `to` context.
1477		assert!(
1478			<sealed::ChannelContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1479				< <sealed::Bolt11InvoiceContext as sealed::Context>::KNOWN_FEATURE_MASK.len()
1480		);
1481		let mut channel_features = ChannelFeatures::empty();
1482		channel_features.set_unknown_feature_optional();
1483		assert!(channel_features.supports_unknown_bits());
1484		let invoice_features: Bolt11InvoiceFeatures = channel_features.to_context_internal();
1485		assert!(!invoice_features.supports_unknown_bits());
1486	}
1487
1488	#[test]
1489	fn set_feature_bits() {
1490		let mut features = Bolt11InvoiceFeatures::empty();
1491		features.set_basic_mpp_optional();
1492		features.set_payment_secret_required();
1493		assert!(features.supports_basic_mpp());
1494		assert!(!features.requires_basic_mpp());
1495		assert!(features.requires_payment_secret());
1496		assert!(features.supports_payment_secret());
1497
1498		// Set flags manually
1499		let mut features = NodeFeatures::empty();
1500		assert!(features.set_optional_feature_bit(55).is_ok());
1501		assert!(features.supports_keysend());
1502		assert!(features.set_optional_feature_bit(255).is_ok());
1503		assert!(features.set_required_feature_bit(256).is_err());
1504	}
1505
1506	#[test]
1507	fn set_custom_bits() {
1508		let mut features = Bolt11InvoiceFeatures::empty();
1509		features.set_variable_length_onion_optional();
1510		assert_eq!(features.flags[1], 0b00000010);
1511
1512		assert!(features.set_optional_custom_bit(255).is_err());
1513		assert!(features.set_required_custom_bit(256).is_ok());
1514		assert!(features.set_required_custom_bit(258).is_ok());
1515		assert_eq!(features.flags[31], 0b00000000);
1516		assert_eq!(features.flags[32], 0b00000101);
1517
1518		let known_bit = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::EVEN_BIT;
1519		let byte_offset = <sealed::Bolt11InvoiceContext as sealed::PaymentSecret>::BYTE_OFFSET;
1520		assert_eq!(byte_offset, 1);
1521		assert_eq!(features.flags[byte_offset], 0b00000010);
1522		assert!(features.set_required_custom_bit(known_bit).is_err());
1523		assert_eq!(features.flags[byte_offset], 0b00000010);
1524
1525		let mut features = Bolt11InvoiceFeatures::empty();
1526		assert!(features.set_optional_custom_bit(256).is_ok());
1527		assert!(features.set_optional_custom_bit(259).is_ok());
1528		assert_eq!(features.flags[32], 0b00001010);
1529
1530		let mut features = Bolt11InvoiceFeatures::empty();
1531		assert!(features.set_required_custom_bit(257).is_ok());
1532		assert!(features.set_required_custom_bit(258).is_ok());
1533		assert_eq!(features.flags[32], 0b00000101);
1534	}
1535
1536	#[test]
1537	fn test_channel_type_mapping() {
1538		// If we map an Bolt11InvoiceFeatures with StaticRemoteKey optional, it should map into a
1539		// required-StaticRemoteKey ChannelTypeFeatures.
1540		let mut init_features = InitFeatures::empty();
1541		init_features.set_static_remote_key_optional();
1542		let converted_features = ChannelTypeFeatures::from_init(&init_features);
1543		assert_eq!(converted_features, ChannelTypeFeatures::only_static_remote_key());
1544		assert!(!converted_features.supports_any_optional_bits());
1545		assert!(converted_features.requires_static_remote_key());
1546	}
1547
1548	#[test]
1549	fn test_excess_zero_bytes_ignored() {
1550		// Checks that `Hash` and `PartialEq` ignore excess zero bytes, which may appear due to
1551		// feature conversion or because a peer serialized their feature poorly.
1552		use std::collections::hash_map::DefaultHasher;
1553		use std::hash::{Hash, Hasher};
1554
1555		let mut zerod_features = InitFeatures::empty();
1556		zerod_features.flags = FeatureFlags::Heap(vec![0]);
1557		let empty_features = InitFeatures::empty();
1558		assert!(empty_features.flags.is_empty());
1559
1560		assert_eq!(zerod_features, empty_features);
1561
1562		let mut zerod_hash = DefaultHasher::new();
1563		zerod_features.hash(&mut zerod_hash);
1564		let mut empty_hash = DefaultHasher::new();
1565		empty_features.hash(&mut empty_hash);
1566		assert_eq!(zerod_hash.finish(), empty_hash.finish());
1567	}
1568
1569	#[test]
1570	fn test_feature_flags_transitions() {
1571		// Tests transitions from stack to heap and back in `FeatureFlags`
1572		let mut flags = FeatureFlags::empty();
1573		assert!(matches!(flags, FeatureFlags::Held { .. }));
1574
1575		flags.resize(DIRECT_ALLOC_BYTES, 42);
1576		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES);
1577		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1578		assert!(matches!(flags, FeatureFlags::Held { .. }));
1579
1580		flags.resize(DIRECT_ALLOC_BYTES * 2, 43);
1581		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES * 2);
1582		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1583		assert!(flags.iter().skip(DIRECT_ALLOC_BYTES).all(|b| *b == 43));
1584		assert!(matches!(flags, FeatureFlags::Heap(_)));
1585
1586		flags.resize(DIRECT_ALLOC_BYTES, 0);
1587		assert_eq!(flags.len(), DIRECT_ALLOC_BYTES);
1588		assert!(flags.iter().take(DIRECT_ALLOC_BYTES).all(|b| *b == 42));
1589		assert!(matches!(flags, FeatureFlags::Held { .. }));
1590	}
1591}