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