1 // This file is Copyright its original authors, visible in version control
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
10 //! Feature flag definitions for the Lightning protocol according to [BOLT #9].
12 //! Lightning nodes advertise a supported set of operation through feature flags. Features are
13 //! applicable for a specific context as indicated in some [messages]. [`Features`] encapsulates
14 //! behavior for specifying and checking feature flags for a particular context. Each feature is
15 //! defined internally by a trait specifying the corresponding flags (i.e., even and odd bits).
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.
22 //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
23 //! [messages]: crate::ln::msgs
28 use core::hash::{Hash, Hasher};
29 use core::marker::PhantomData;
32 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
33 use ln::msgs::DecodeError;
34 use util::ser::{Readable, Writeable, Writer};
38 use ln::features::Features;
40 /// The context in which [`Features`] are applicable. Defines which features are required and
41 /// which are optional for the context.
43 /// Features that are known to the implementation, where a required feature is indicated by
44 /// its even bit and an optional feature is indicated by its odd bit.
45 const KNOWN_FEATURE_FLAGS: &'static [u8];
47 /// Bitmask for selecting features that are known to the implementation, regardless of
48 /// whether each feature is required or optional.
49 const KNOWN_FEATURE_MASK: &'static [u8];
52 /// Defines a [`Context`] by stating which features it requires and which are optional. Features
53 /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
54 /// feature identifiers.
55 macro_rules! define_context {
57 required_features: [$( $( $required_feature: ident )|*, )*],
58 optional_features: [$( $( $optional_feature: ident )|*, )*],
60 #[derive(Eq, PartialEq)]
61 pub struct $context {}
63 impl Context for $context {
64 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
65 // For each byte, use bitwise-OR to compute the applicable flags for known
66 // required features `r_i` and optional features `o_j` for all `i` and `j` such
67 // that the following slice is formed:
70 // `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
75 <Self as $required_feature>::REQUIRED_MASK)*
77 <Self as $optional_feature>::OPTIONAL_MASK)*,
81 const KNOWN_FEATURE_MASK: &'static [u8] = &[
82 // Similar as above, but set both flags for each feature regardless of whether
83 // the feature is required or optional.
86 <Self as $required_feature>::REQUIRED_MASK |
87 <Self as $required_feature>::OPTIONAL_MASK)*
89 <Self as $optional_feature>::REQUIRED_MASK |
90 <Self as $optional_feature>::OPTIONAL_MASK)*,
95 impl alloc::fmt::Display for Features<$context> {
96 fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
99 fmt.write_fmt(format_args!("{}: {}, ", stringify!($required_feature),
100 if <$context as $required_feature>::requires_feature(&self.flags) { "required" }
101 else if <$context as $required_feature>::supports_feature(&self.flags) { "supported" }
102 else { "not supported" }))?;
105 fmt.write_fmt(format_args!("{}: {}, ", stringify!($optional_feature),
106 if <$context as $optional_feature>::requires_feature(&self.flags) { "required" }
107 else if <$context as $optional_feature>::supports_feature(&self.flags) { "supported" }
108 else { "not supported" }))?;
111 fmt.write_fmt(format_args!("unknown flags: {}",
112 if self.requires_unknown_bits() { "required" }
113 else if self.supports_unknown_bits() { "supported" } else { "none" }))
119 define_context!(InitContext {
124 VariableLengthOnion | StaticRemoteKey | PaymentSecret,
136 DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
149 define_context!(NodeContext {
154 VariableLengthOnion | StaticRemoteKey | PaymentSecret,
168 DataLossProtect | UpfrontShutdownScript | GossipQueries,
183 define_context!(ChannelContext {
184 required_features: [],
185 optional_features: [],
187 define_context!(InvoiceContext {
192 VariableLengthOnion | PaymentSecret,
204 // Note that the optional feature bits set here are used to check if a bit is "known", but
205 // the `InvoiceBuilder` in lightning-invoice starts with `empty()` and does not set these
206 // bits unless the relevant data is included in the invoice.
224 // This isn't a "real" feature context, and is only used in the channel_type field in an
225 // `OpenChannel` message.
226 define_context!(ChannelTypeContext {
249 /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
250 /// useful for manipulating feature flags.
251 macro_rules! define_feature {
252 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
253 $required_setter: ident, $supported_getter: ident) => {
256 /// See [BOLT #9] for details.
258 /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
259 pub trait $feature: Context {
260 /// The bit used to signify that the feature is required.
261 const EVEN_BIT: usize = $odd_bit - 1;
263 /// The bit used to signify that the feature is optional.
264 const ODD_BIT: usize = $odd_bit;
266 /// Assertion that [`EVEN_BIT`] is actually even.
268 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
269 const ASSERT_EVEN_BIT_PARITY: usize;
271 /// Assertion that [`ODD_BIT`] is actually odd.
273 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
274 const ASSERT_ODD_BIT_PARITY: usize;
276 /// The byte where the feature is set.
277 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
279 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
281 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
282 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
284 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
286 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
287 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
289 /// Returns whether the feature is required by the given flags.
291 fn requires_feature(flags: &Vec<u8>) -> bool {
292 flags.len() > Self::BYTE_OFFSET &&
293 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
296 /// Returns whether the feature is supported by the given flags.
298 fn supports_feature(flags: &Vec<u8>) -> bool {
299 flags.len() > Self::BYTE_OFFSET &&
300 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
303 /// Sets the feature's required (even) bit in the given flags.
305 fn set_required_bit(flags: &mut Vec<u8>) {
306 if flags.len() <= Self::BYTE_OFFSET {
307 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
310 flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
313 /// Sets the feature's optional (odd) bit in the given flags.
315 fn set_optional_bit(flags: &mut Vec<u8>) {
316 if flags.len() <= Self::BYTE_OFFSET {
317 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
320 flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
323 /// Clears the feature's required (even) and optional (odd) bits from the given
326 fn clear_bits(flags: &mut Vec<u8>) {
327 if flags.len() > Self::BYTE_OFFSET {
328 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
329 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
332 let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
333 let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
334 flags.resize(size, 0u8);
338 impl <T: $feature> Features<T> {
339 /// Set this feature as optional.
340 pub fn $optional_setter(mut self) -> Self {
341 <T as $feature>::set_optional_bit(&mut self.flags);
345 /// Set this feature as required.
346 pub fn $required_setter(mut self) -> Self {
347 <T as $feature>::set_required_bit(&mut self.flags);
351 /// Checks if this feature is supported.
352 pub fn $supported_getter(&self) -> bool {
353 <T as $feature>::supports_feature(&self.flags)
358 impl $feature for $context {
360 const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
363 const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
367 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
368 $required_setter: ident, $supported_getter: ident, $required_getter: ident) => {
369 define_feature!($odd_bit, $feature, [$($context),+], $doc, $optional_setter, $required_setter, $supported_getter);
370 impl <T: $feature> Features<T> {
371 /// Checks if this feature is required.
372 pub fn $required_getter(&self) -> bool {
373 <T as $feature>::requires_feature(&self.flags)
379 define_feature!(1, DataLossProtect, [InitContext, NodeContext],
380 "Feature flags for `option_data_loss_protect`.", set_data_loss_protect_optional,
381 set_data_loss_protect_required, supports_data_loss_protect, requires_data_loss_protect);
382 // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
383 define_feature!(3, InitialRoutingSync, [InitContext], "Feature flags for `initial_routing_sync`.",
384 set_initial_routing_sync_optional, set_initial_routing_sync_required,
385 initial_routing_sync);
386 define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
387 "Feature flags for `option_upfront_shutdown_script`.", set_upfront_shutdown_script_optional,
388 set_upfront_shutdown_script_required, supports_upfront_shutdown_script,
389 requires_upfront_shutdown_script);
390 define_feature!(7, GossipQueries, [InitContext, NodeContext],
391 "Feature flags for `gossip_queries`.", set_gossip_queries_optional, set_gossip_queries_required,
392 supports_gossip_queries, requires_gossip_queries);
393 define_feature!(9, VariableLengthOnion, [InitContext, NodeContext, InvoiceContext],
394 "Feature flags for `var_onion_optin`.", set_variable_length_onion_optional,
395 set_variable_length_onion_required, supports_variable_length_onion,
396 requires_variable_length_onion);
397 define_feature!(13, StaticRemoteKey, [InitContext, NodeContext, ChannelTypeContext],
398 "Feature flags for `option_static_remotekey`.", set_static_remote_key_optional,
399 set_static_remote_key_required, supports_static_remote_key, requires_static_remote_key);
400 define_feature!(15, PaymentSecret, [InitContext, NodeContext, InvoiceContext],
401 "Feature flags for `payment_secret`.", set_payment_secret_optional, set_payment_secret_required,
402 supports_payment_secret, requires_payment_secret);
403 define_feature!(17, BasicMPP, [InitContext, NodeContext, InvoiceContext],
404 "Feature flags for `basic_mpp`.", set_basic_mpp_optional, set_basic_mpp_required,
405 supports_basic_mpp, requires_basic_mpp);
406 define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
407 "Feature flags for `opt_shutdown_anysegwit`.", set_shutdown_any_segwit_optional,
408 set_shutdown_any_segwit_required, supports_shutdown_anysegwit, requires_shutdown_anysegwit);
409 define_feature!(45, ChannelType, [InitContext, NodeContext],
410 "Feature flags for `option_channel_type`.", set_channel_type_optional,
411 set_channel_type_required, supports_channel_type, requires_channel_type);
412 define_feature!(49, PaymentMetadata, [InvoiceContext],
413 "Feature flags for payment metadata in invoices.", set_payment_metadata_optional,
414 set_payment_metadata_required, supports_payment_metadata, requires_payment_metadata);
415 define_feature!(55, Keysend, [NodeContext],
416 "Feature flags for keysend payments.", set_keysend_optional, set_keysend_required,
417 supports_keysend, requires_keysend);
420 define_feature!(123456789, UnknownFeature, [NodeContext, ChannelContext, InitContext],
421 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
422 set_unknown_feature_required, supports_unknown_test_feature, requires_unknown_test_feature);
425 /// Tracks the set of features which a node implements, templated by the context in which it
428 /// (C-not exported) as we map the concrete feature types below directly instead
430 pub struct Features<T: sealed::Context> {
431 /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
433 mark: PhantomData<T>,
436 impl<T: sealed::Context> Clone for Features<T> {
437 fn clone(&self) -> Self {
439 flags: self.flags.clone(),
444 impl<T: sealed::Context> Hash for Features<T> {
445 fn hash<H: Hasher>(&self, hasher: &mut H) {
446 self.flags.hash(hasher);
449 impl<T: sealed::Context> PartialEq for Features<T> {
450 fn eq(&self, o: &Self) -> bool {
451 self.flags.eq(&o.flags)
454 impl<T: sealed::Context> fmt::Debug for Features<T> {
455 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
460 /// Features used within an `init` message.
461 pub type InitFeatures = Features<sealed::InitContext>;
462 /// Features used within a `node_announcement` message.
463 pub type NodeFeatures = Features<sealed::NodeContext>;
464 /// Features used within a `channel_announcement` message.
465 pub type ChannelFeatures = Features<sealed::ChannelContext>;
466 /// Features used within an invoice.
467 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
469 /// Features used within the channel_type field in an OpenChannel message.
471 /// A channel is always of some known "type", describing the transaction formats used and the exact
472 /// semantics of our interaction with our peer.
474 /// Note that because a channel is a specific type which is proposed by the opener and accepted by
475 /// the counterparty, only required features are allowed here.
477 /// This is serialized differently from other feature types - it is not prefixed by a length, and
478 /// thus must only appear inside a TLV where its length is known in advance.
479 pub type ChannelTypeFeatures = Features<sealed::ChannelTypeContext>;
482 /// Writes all features present up to, and including, 13.
483 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
484 let len = cmp::min(2, self.flags.len());
485 (len as u16).write(w)?;
486 for i in (0..len).rev() {
488 self.flags[i].write(w)?;
490 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
491 // up-to-and-including-bit-5, 0-indexed, on this byte:
492 (self.flags[i] & 0b00_11_11_11).write(w)?;
498 /// or's another InitFeatures into this one.
499 pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
500 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
501 self.flags.resize(total_feature_len, 0u8);
502 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
508 /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
509 /// are included in the result.
510 pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
511 self.to_context_internal()
515 impl InvoiceFeatures {
516 /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
517 /// context `C` are included in the result.
518 pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
519 self.to_context_internal()
522 /// Getting a route for a keysend payment to a private node requires providing the payee's
523 /// features (since they were not announced in a node announcement). However, keysend payments
524 /// don't have an invoice to pull the payee's features from, so this method is provided for use in
525 /// [`PaymentParameters::for_keysend`], thus omitting the need for payers to manually construct an
526 /// `InvoiceFeatures` for [`find_route`].
528 /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
529 /// [`find_route`]: crate::routing::router::find_route
530 pub(crate) fn for_keysend() -> InvoiceFeatures {
531 InvoiceFeatures::empty().set_variable_length_onion_optional()
535 impl ChannelTypeFeatures {
536 /// Constructs the implicit channel type based on the common supported types between us and our
538 pub(crate) fn from_counterparty_init(counterparty_init: &InitFeatures) -> Self {
539 let mut ret = counterparty_init.to_context_internal();
540 // ChannelTypeFeatures must only contain required bits, so we OR the required forms of all
541 // optional bits and then AND out the optional ones.
542 for byte in ret.flags.iter_mut() {
543 *byte |= (*byte & 0b10_10_10_10) >> 1;
544 *byte &= 0b01_01_01_01;
549 /// Constructs a ChannelTypeFeatures with only static_remotekey set
550 pub(crate) fn only_static_remote_key() -> Self {
551 let mut ret = Self::empty();
552 <sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret.flags);
557 impl ToBase32 for InvoiceFeatures {
558 fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
559 // Explanation for the "4": the normal way to round up when dividing is to add the divisor
560 // minus one before dividing
561 let length_u5s = (self.flags.len() * 8 + 4) / 5 as usize;
562 let mut res_u5s: Vec<u5> = vec![u5::try_from_u8(0).unwrap(); length_u5s];
563 for (byte_idx, byte) in self.flags.iter().enumerate() {
564 let bit_pos_from_left_0_indexed = byte_idx * 8;
565 let new_u5_idx = length_u5s - (bit_pos_from_left_0_indexed / 5) as usize - 1;
566 let new_bit_pos = bit_pos_from_left_0_indexed % 5;
567 let shifted_chunk_u16 = (*byte as u16) << new_bit_pos;
568 let curr_u5_as_u8 = res_u5s[new_u5_idx].to_u8();
569 res_u5s[new_u5_idx] = u5::try_from_u8(curr_u5_as_u8 | ((shifted_chunk_u16 & 0x001f) as u8)).unwrap();
571 let curr_u5_as_u8 = res_u5s[new_u5_idx - 1].to_u8();
572 res_u5s[new_u5_idx - 1] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 5) & 0x001f) as u8)).unwrap();
575 let curr_u5_as_u8 = res_u5s[new_u5_idx - 2].to_u8();
576 res_u5s[new_u5_idx - 2] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 10) & 0x001f) as u8)).unwrap();
579 // Trim the highest feature bits.
580 while !res_u5s.is_empty() && res_u5s[0] == u5::try_from_u8(0).unwrap() {
583 writer.write(&res_u5s)
587 impl Base32Len for InvoiceFeatures {
588 fn base32_len(&self) -> usize {
589 self.to_base32().len()
593 impl FromBase32 for InvoiceFeatures {
594 type Err = bech32::Error;
596 fn from_base32(field_data: &[u5]) -> Result<InvoiceFeatures, bech32::Error> {
597 // Explanation for the "7": the normal way to round up when dividing is to add the divisor
598 // minus one before dividing
599 let length_bytes = (field_data.len() * 5 + 7) / 8 as usize;
600 let mut res_bytes: Vec<u8> = vec![0; length_bytes];
601 for (u5_idx, chunk) in field_data.iter().enumerate() {
602 let bit_pos_from_right_0_indexed = (field_data.len() - u5_idx - 1) * 5;
603 let new_byte_idx = (bit_pos_from_right_0_indexed / 8) as usize;
604 let new_bit_pos = bit_pos_from_right_0_indexed % 8;
605 let chunk_u16 = chunk.to_u8() as u16;
606 res_bytes[new_byte_idx] |= ((chunk_u16 << new_bit_pos) & 0xff) as u8;
607 if new_byte_idx != length_bytes - 1 {
608 res_bytes[new_byte_idx + 1] |= ((chunk_u16 >> (8-new_bit_pos)) & 0xff) as u8;
611 // Trim the highest feature bits.
612 while !res_bytes.is_empty() && res_bytes[res_bytes.len() - 1] == 0 {
615 Ok(InvoiceFeatures::from_le_bytes(res_bytes))
619 impl<T: sealed::Context> Features<T> {
620 /// Create a blank Features with no features set
621 pub fn empty() -> Self {
628 /// Creates a Features with the bits set which are known by the implementation
629 pub fn known() -> Self {
631 flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
636 /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
637 /// included in the result.
638 fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
639 let from_byte_count = T::KNOWN_FEATURE_MASK.len();
640 let to_byte_count = C::KNOWN_FEATURE_MASK.len();
641 let mut flags = Vec::new();
642 for (i, byte) in self.flags.iter().enumerate() {
643 if i < from_byte_count && i < to_byte_count {
644 let from_known_features = T::KNOWN_FEATURE_MASK[i];
645 let to_known_features = C::KNOWN_FEATURE_MASK[i];
646 flags.push(byte & from_known_features & to_known_features);
649 Features::<C> { flags, mark: PhantomData, }
652 /// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
653 /// most on-the-wire encodings.
654 /// (C-not exported) as we don't support export across multiple T
655 pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
663 /// Gets the underlying flags set, in LE.
664 pub fn le_flags(&self) -> &Vec<u8> {
668 fn write_be<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
669 for f in self.flags.iter().rev() { // Swap back to big-endian
675 fn from_be_bytes(mut flags: Vec<u8>) -> Features<T> {
676 flags.reverse(); // Swap to little-endian
683 pub(crate) fn supports_any_optional_bits(&self) -> bool {
684 self.flags.iter().any(|&byte| (byte & 0b10_10_10_10) != 0)
687 /// Returns true if this `Features` object contains unknown feature flags which are set as
689 pub fn requires_unknown_bits(&self) -> bool {
690 // Bitwise AND-ing with all even bits set except for known features will select required
692 let byte_count = T::KNOWN_FEATURE_MASK.len();
693 self.flags.iter().enumerate().any(|(i, &byte)| {
694 let required_features = 0b01_01_01_01;
695 let unknown_features = if i < byte_count {
696 !T::KNOWN_FEATURE_MASK[i]
700 (byte & (required_features & unknown_features)) != 0
704 pub(crate) fn supports_unknown_bits(&self) -> bool {
705 // Bitwise AND-ing with all even and odd bits set except for known features will select
706 // both required and optional unknown features.
707 let byte_count = T::KNOWN_FEATURE_MASK.len();
708 self.flags.iter().enumerate().any(|(i, &byte)| {
709 let unknown_features = if i < byte_count {
710 !T::KNOWN_FEATURE_MASK[i]
714 (byte & unknown_features) != 0
719 impl<T: sealed::UpfrontShutdownScript> Features<T> {
721 pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
722 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
728 impl<T: sealed::GossipQueries> Features<T> {
730 pub(crate) fn clear_gossip_queries(mut self) -> Self {
731 <T as sealed::GossipQueries>::clear_bits(&mut self.flags);
736 impl<T: sealed::InitialRoutingSync> Features<T> {
737 // We are no longer setting initial_routing_sync now that gossip_queries
738 // is enabled. This feature is ignored by a peer when gossip_queries has
741 pub(crate) fn clear_initial_routing_sync(&mut self) {
742 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
746 impl<T: sealed::ShutdownAnySegwit> Features<T> {
748 pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
749 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
753 macro_rules! impl_feature_len_prefixed_write {
754 ($features: ident) => {
755 impl Writeable for $features {
756 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
757 (self.flags.len() as u16).write(w)?;
761 impl Readable for $features {
762 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
763 Ok(Self::from_be_bytes(Vec::<u8>::read(r)?))
768 impl_feature_len_prefixed_write!(InitFeatures);
769 impl_feature_len_prefixed_write!(ChannelFeatures);
770 impl_feature_len_prefixed_write!(NodeFeatures);
771 impl_feature_len_prefixed_write!(InvoiceFeatures);
773 // Because ChannelTypeFeatures only appears inside of TLVs, it doesn't have a length prefix when
774 // serialized. Thus, we can't use `impl_feature_len_prefixed_write`, above, and have to write our
775 // own serialization.
776 impl Writeable for ChannelTypeFeatures {
777 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
781 impl Readable for ChannelTypeFeatures {
782 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
783 let v = io_extras::read_to_end(r)?;
784 Ok(Self::from_be_bytes(v))
790 use super::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
791 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5};
794 fn sanity_test_known_features() {
795 assert!(!ChannelFeatures::known().requires_unknown_bits());
796 assert!(!ChannelFeatures::known().supports_unknown_bits());
797 assert!(!InitFeatures::known().requires_unknown_bits());
798 assert!(!InitFeatures::known().supports_unknown_bits());
799 assert!(!NodeFeatures::known().requires_unknown_bits());
800 assert!(!NodeFeatures::known().supports_unknown_bits());
802 assert!(InitFeatures::known().supports_upfront_shutdown_script());
803 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
804 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
805 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
807 assert!(InitFeatures::known().supports_gossip_queries());
808 assert!(NodeFeatures::known().supports_gossip_queries());
809 assert!(!InitFeatures::known().requires_gossip_queries());
810 assert!(!NodeFeatures::known().requires_gossip_queries());
812 assert!(InitFeatures::known().supports_data_loss_protect());
813 assert!(NodeFeatures::known().supports_data_loss_protect());
814 assert!(!InitFeatures::known().requires_data_loss_protect());
815 assert!(!NodeFeatures::known().requires_data_loss_protect());
817 assert!(InitFeatures::known().supports_variable_length_onion());
818 assert!(NodeFeatures::known().supports_variable_length_onion());
819 assert!(InvoiceFeatures::known().supports_variable_length_onion());
820 assert!(InitFeatures::known().requires_variable_length_onion());
821 assert!(NodeFeatures::known().requires_variable_length_onion());
822 assert!(InvoiceFeatures::known().requires_variable_length_onion());
824 assert!(InitFeatures::known().supports_static_remote_key());
825 assert!(NodeFeatures::known().supports_static_remote_key());
826 assert!(InitFeatures::known().requires_static_remote_key());
827 assert!(NodeFeatures::known().requires_static_remote_key());
829 assert!(InitFeatures::known().supports_payment_secret());
830 assert!(NodeFeatures::known().supports_payment_secret());
831 assert!(InvoiceFeatures::known().supports_payment_secret());
832 assert!(InitFeatures::known().requires_payment_secret());
833 assert!(NodeFeatures::known().requires_payment_secret());
834 assert!(InvoiceFeatures::known().requires_payment_secret());
836 assert!(InitFeatures::known().supports_basic_mpp());
837 assert!(NodeFeatures::known().supports_basic_mpp());
838 assert!(InvoiceFeatures::known().supports_basic_mpp());
839 assert!(!InitFeatures::known().requires_basic_mpp());
840 assert!(!NodeFeatures::known().requires_basic_mpp());
841 assert!(!InvoiceFeatures::known().requires_basic_mpp());
843 assert!(InitFeatures::known().supports_channel_type());
844 assert!(NodeFeatures::known().supports_channel_type());
845 assert!(!InitFeatures::known().requires_channel_type());
846 assert!(!NodeFeatures::known().requires_channel_type());
848 assert!(InitFeatures::known().supports_shutdown_anysegwit());
849 assert!(NodeFeatures::known().supports_shutdown_anysegwit());
851 let mut init_features = InitFeatures::known();
852 assert!(init_features.initial_routing_sync());
853 init_features.clear_initial_routing_sync();
854 assert!(!init_features.initial_routing_sync());
858 fn sanity_test_unknown_bits() {
859 let features = ChannelFeatures::empty();
860 assert!(!features.requires_unknown_bits());
861 assert!(!features.supports_unknown_bits());
863 let features = ChannelFeatures::empty().set_unknown_feature_required();
864 assert!(features.requires_unknown_bits());
865 assert!(features.supports_unknown_bits());
867 let features = ChannelFeatures::empty().set_unknown_feature_optional();
868 assert!(!features.requires_unknown_bits());
869 assert!(features.supports_unknown_bits());
873 fn convert_to_context_with_relevant_flags() {
874 let init_features = InitFeatures::known().clear_upfront_shutdown_script().clear_gossip_queries();
875 assert!(init_features.initial_routing_sync());
876 assert!(!init_features.supports_upfront_shutdown_script());
877 assert!(!init_features.supports_gossip_queries());
879 let node_features: NodeFeatures = init_features.to_context();
881 // Check that the flags are as expected:
882 // - option_data_loss_protect
883 // - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
885 // - opt_shutdown_anysegwit
887 // - option_channel_type
888 assert_eq!(node_features.flags.len(), 6);
889 assert_eq!(node_features.flags[0], 0b00000010);
890 assert_eq!(node_features.flags[1], 0b01010001);
891 assert_eq!(node_features.flags[2], 0b00000010);
892 assert_eq!(node_features.flags[3], 0b00001000);
893 assert_eq!(node_features.flags[4], 0b00000000);
894 assert_eq!(node_features.flags[5], 0b00100000);
897 // Check that cleared flags are kept blank when converting back:
898 // - initial_routing_sync was not applicable to NodeContext
899 // - upfront_shutdown_script was cleared before converting
900 // - gossip_queries was cleared before converting
901 let features: InitFeatures = node_features.to_context_internal();
902 assert!(!features.initial_routing_sync());
903 assert!(!features.supports_upfront_shutdown_script());
904 assert!(!init_features.supports_gossip_queries());
908 fn convert_to_context_with_unknown_flags() {
909 // Ensure the `from` context has fewer known feature bytes than the `to` context.
910 assert!(InitFeatures::known().flags.len() < NodeFeatures::known().flags.len());
911 let init_features = InitFeatures::known().set_unknown_feature_optional();
912 assert!(init_features.supports_unknown_bits());
913 let node_features: NodeFeatures = init_features.to_context();
914 assert!(!node_features.supports_unknown_bits());
918 fn set_feature_bits() {
919 let features = InvoiceFeatures::empty()
920 .set_basic_mpp_optional()
921 .set_payment_secret_required();
922 assert!(features.supports_basic_mpp());
923 assert!(!features.requires_basic_mpp());
924 assert!(features.requires_payment_secret());
925 assert!(features.supports_payment_secret());
929 fn invoice_features_encoding() {
930 let features_as_u5s = vec![
931 u5::try_from_u8(6).unwrap(),
932 u5::try_from_u8(10).unwrap(),
933 u5::try_from_u8(25).unwrap(),
934 u5::try_from_u8(1).unwrap(),
935 u5::try_from_u8(10).unwrap(),
936 u5::try_from_u8(0).unwrap(),
937 u5::try_from_u8(20).unwrap(),
938 u5::try_from_u8(2).unwrap(),
939 u5::try_from_u8(0).unwrap(),
940 u5::try_from_u8(6).unwrap(),
941 u5::try_from_u8(0).unwrap(),
942 u5::try_from_u8(16).unwrap(),
943 u5::try_from_u8(1).unwrap(),
945 let features = InvoiceFeatures::from_le_bytes(vec![1, 2, 3, 4, 5, 42, 100, 101]);
947 // Test length calculation.
948 assert_eq!(features.base32_len(), 13);
950 // Test serialization.
951 let features_serialized = features.to_base32();
952 assert_eq!(features_as_u5s, features_serialized);
954 // Test deserialization.
955 let features_deserialized = InvoiceFeatures::from_base32(&features_as_u5s).unwrap();
956 assert_eq!(features, features_deserialized);
960 fn test_channel_type_mapping() {
961 // If we map an InvoiceFeatures with StaticRemoteKey optional, it should map into a
962 // required-StaticRemoteKey ChannelTypeFeatures.
963 let init_features = InitFeatures::empty().set_static_remote_key_optional();
964 let converted_features = ChannelTypeFeatures::from_counterparty_init(&init_features);
965 assert_eq!(converted_features, ChannelTypeFeatures::only_static_remote_key());
966 assert!(!converted_features.supports_any_optional_bits());
967 assert!(converted_features.requires_static_remote_key());