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
26 use std::marker::PhantomData;
29 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
30 use ln::msgs::DecodeError;
31 use util::ser::{Readable, Writeable, Writer};
34 use ln::features::Features;
36 /// The context in which [`Features`] are applicable. Defines which features are required and
37 /// which are optional for the context.
39 /// Features that are known to the implementation, where a required feature is indicated by
40 /// its even bit and an optional feature is indicated by its odd bit.
41 const KNOWN_FEATURE_FLAGS: &'static [u8];
43 /// Bitmask for selecting features that are known to the implementation, regardless of
44 /// whether each feature is required or optional.
45 const KNOWN_FEATURE_MASK: &'static [u8];
48 /// Defines a [`Context`] by stating which features it requires and which are optional. Features
49 /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
50 /// feature identifiers.
51 macro_rules! define_context {
53 required_features: [$( $( $required_feature: ident )|*, )*],
54 optional_features: [$( $( $optional_feature: ident )|*, )*],
56 #[derive(Eq, PartialEq)]
57 pub struct $context {}
59 impl Context for $context {
60 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
61 // For each byte, use bitwise-OR to compute the applicable flags for known
62 // required features `r_i` and optional features `o_j` for all `i` and `j` such
63 // that the following slice is formed:
66 // `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
71 <Self as $required_feature>::REQUIRED_MASK)*
73 <Self as $optional_feature>::OPTIONAL_MASK)*,
77 const KNOWN_FEATURE_MASK: &'static [u8] = &[
78 // Similar as above, but set both flags for each feature regardless of whether
79 // the feature is required or optional.
82 <Self as $required_feature>::REQUIRED_MASK |
83 <Self as $required_feature>::OPTIONAL_MASK)*
85 <Self as $optional_feature>::REQUIRED_MASK |
86 <Self as $optional_feature>::OPTIONAL_MASK)*,
93 define_context!(InitContext {
98 StaticRemoteKey | PaymentSecret,
106 DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
115 define_context!(NodeContext {
120 StaticRemoteKey | PaymentSecret,
128 DataLossProtect | UpfrontShutdownScript | GossipQueries,
137 define_context!(ChannelContext {
138 required_features: [],
139 optional_features: [],
141 define_context!(InvoiceContext {
160 /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
161 /// useful for manipulating feature flags.
162 macro_rules! define_feature {
163 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
164 $required_setter: ident) => {
167 /// See [BOLT #9] for details.
169 /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
170 pub trait $feature: Context {
171 /// The bit used to signify that the feature is required.
172 const EVEN_BIT: usize = $odd_bit - 1;
174 /// The bit used to signify that the feature is optional.
175 const ODD_BIT: usize = $odd_bit;
177 /// Assertion that [`EVEN_BIT`] is actually even.
179 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
180 const ASSERT_EVEN_BIT_PARITY: usize;
182 /// Assertion that [`ODD_BIT`] is actually odd.
184 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
185 const ASSERT_ODD_BIT_PARITY: usize;
187 /// The byte where the feature is set.
188 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
190 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
192 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
193 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
195 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
197 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
198 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
200 /// Returns whether the feature is required by the given flags.
202 fn requires_feature(flags: &Vec<u8>) -> bool {
203 flags.len() > Self::BYTE_OFFSET &&
204 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
207 /// Returns whether the feature is supported by the given flags.
209 fn supports_feature(flags: &Vec<u8>) -> bool {
210 flags.len() > Self::BYTE_OFFSET &&
211 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
214 /// Sets the feature's required (even) bit in the given flags.
216 fn set_required_bit(flags: &mut Vec<u8>) {
217 if flags.len() <= Self::BYTE_OFFSET {
218 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
221 flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
224 /// Sets the feature's optional (odd) bit in the given flags.
226 fn set_optional_bit(flags: &mut Vec<u8>) {
227 if flags.len() <= Self::BYTE_OFFSET {
228 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
231 flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
234 /// Clears the feature's required (even) and optional (odd) bits from the given
237 fn clear_bits(flags: &mut Vec<u8>) {
238 if flags.len() > Self::BYTE_OFFSET {
239 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
240 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
243 let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
244 let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
245 flags.resize(size, 0u8);
249 impl <T: $feature> Features<T> {
250 /// Set this feature as optional.
251 pub fn $optional_setter(mut self) -> Self {
252 <T as $feature>::set_optional_bit(&mut self.flags);
256 /// Set this feature as required.
257 pub fn $required_setter(mut self) -> Self {
258 <T as $feature>::set_required_bit(&mut self.flags);
264 impl $feature for $context {
266 const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
269 const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
276 define_feature!(1, DataLossProtect, [InitContext, NodeContext],
277 "Feature flags for `option_data_loss_protect`.", set_data_loss_protect_optional,
278 set_data_loss_protect_required);
279 // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
280 define_feature!(3, InitialRoutingSync, [InitContext], "Feature flags for `initial_routing_sync`.",
281 set_initial_routing_sync_optional, set_initial_routing_sync_required);
282 define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
283 "Feature flags for `option_upfront_shutdown_script`.", set_upfront_shutdown_script_optional,
284 set_upfront_shutdown_script_required);
285 define_feature!(7, GossipQueries, [InitContext, NodeContext],
286 "Feature flags for `gossip_queries`.", set_gossip_queries_optional, set_gossip_queries_required);
287 define_feature!(9, VariableLengthOnion, [InitContext, NodeContext, InvoiceContext],
288 "Feature flags for `var_onion_optin`.", set_variable_length_onion_optional,
289 set_variable_length_onion_required);
290 define_feature!(13, StaticRemoteKey, [InitContext, NodeContext],
291 "Feature flags for `option_static_remotekey`.", set_static_remote_key_optional,
292 set_static_remote_key_required);
293 define_feature!(15, PaymentSecret, [InitContext, NodeContext, InvoiceContext],
294 "Feature flags for `payment_secret`.", set_payment_secret_optional, set_payment_secret_required);
295 define_feature!(17, BasicMPP, [InitContext, NodeContext, InvoiceContext],
296 "Feature flags for `basic_mpp`.", set_basic_mpp_optional, set_basic_mpp_required);
297 define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
298 "Feature flags for `opt_shutdown_anysegwit`.", set_shutdown_any_segwit_optional,
299 set_shutdown_any_segwit_required);
302 define_context!(TestingContext {
322 define_feature!(23, UnknownFeature, [TestingContext],
323 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
324 set_unknown_feature_required);
327 /// Tracks the set of features which a node implements, templated by the context in which it
330 /// (C-not exported) as we map the concrete feature types below directly instead
332 pub struct Features<T: sealed::Context> {
333 /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
335 mark: PhantomData<T>,
338 impl<T: sealed::Context> Clone for Features<T> {
339 fn clone(&self) -> Self {
341 flags: self.flags.clone(),
346 impl<T: sealed::Context> PartialEq for Features<T> {
347 fn eq(&self, o: &Self) -> bool {
348 self.flags.eq(&o.flags)
351 impl<T: sealed::Context> fmt::Debug for Features<T> {
352 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
357 /// Features used within an `init` message.
358 pub type InitFeatures = Features<sealed::InitContext>;
359 /// Features used within a `node_announcement` message.
360 pub type NodeFeatures = Features<sealed::NodeContext>;
361 /// Features used within a `channel_announcement` message.
362 pub type ChannelFeatures = Features<sealed::ChannelContext>;
363 /// Features used within an invoice.
364 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
367 /// Writes all features present up to, and including, 13.
368 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
369 let len = cmp::min(2, self.flags.len());
370 w.size_hint(len + 2);
371 (len as u16).write(w)?;
372 for i in (0..len).rev() {
374 self.flags[i].write(w)?;
376 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
377 // up-to-and-including-bit-5, 0-indexed, on this byte:
378 (self.flags[i] & 0b00_11_11_11).write(w)?;
384 /// or's another InitFeatures into this one.
385 pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
386 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
387 self.flags.resize(total_feature_len, 0u8);
388 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
394 /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
395 /// are included in the result.
396 pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
397 self.to_context_internal()
401 impl InvoiceFeatures {
402 /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
403 /// context `C` are included in the result.
404 pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
405 self.to_context_internal()
409 impl ToBase32 for InvoiceFeatures {
410 fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
411 // Explanation for the "4": the normal way to round up when dividing is to add the divisor
412 // minus one before dividing
413 let length_u5s = (self.flags.len() * 8 + 4) / 5 as usize;
414 let mut res_u5s: Vec<u5> = vec![u5::try_from_u8(0).unwrap(); length_u5s];
415 for (byte_idx, byte) in self.flags.iter().enumerate() {
416 let bit_pos_from_left_0_indexed = byte_idx * 8;
417 let new_u5_idx = length_u5s - (bit_pos_from_left_0_indexed / 5) as usize - 1;
418 let new_bit_pos = bit_pos_from_left_0_indexed % 5;
419 let shifted_chunk_u16 = (*byte as u16) << new_bit_pos;
420 let curr_u5_as_u8 = res_u5s[new_u5_idx].to_u8();
421 res_u5s[new_u5_idx] = u5::try_from_u8(curr_u5_as_u8 | ((shifted_chunk_u16 & 0x001f) as u8)).unwrap();
423 let curr_u5_as_u8 = res_u5s[new_u5_idx - 1].to_u8();
424 res_u5s[new_u5_idx - 1] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 5) & 0x001f) as u8)).unwrap();
427 let curr_u5_as_u8 = res_u5s[new_u5_idx - 2].to_u8();
428 res_u5s[new_u5_idx - 2] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 10) & 0x001f) as u8)).unwrap();
431 // Trim the highest feature bits.
432 while !res_u5s.is_empty() && res_u5s[0] == u5::try_from_u8(0).unwrap() {
435 writer.write(&res_u5s)
439 impl Base32Len for InvoiceFeatures {
440 fn base32_len(&self) -> usize {
441 self.to_base32().len()
445 impl FromBase32 for InvoiceFeatures {
446 type Err = bech32::Error;
448 fn from_base32(field_data: &[u5]) -> Result<InvoiceFeatures, bech32::Error> {
449 // Explanation for the "7": the normal way to round up when dividing is to add the divisor
450 // minus one before dividing
451 let length_bytes = (field_data.len() * 5 + 7) / 8 as usize;
452 let mut res_bytes: Vec<u8> = vec![0; length_bytes];
453 for (u5_idx, chunk) in field_data.iter().enumerate() {
454 let bit_pos_from_right_0_indexed = (field_data.len() - u5_idx - 1) * 5;
455 let new_byte_idx = (bit_pos_from_right_0_indexed / 8) as usize;
456 let new_bit_pos = bit_pos_from_right_0_indexed % 8;
457 let chunk_u16 = chunk.to_u8() as u16;
458 res_bytes[new_byte_idx] |= ((chunk_u16 << new_bit_pos) & 0xff) as u8;
459 if new_byte_idx != length_bytes - 1 {
460 res_bytes[new_byte_idx + 1] |= ((chunk_u16 >> (8-new_bit_pos)) & 0xff) as u8;
463 // Trim the highest feature bits.
464 while !res_bytes.is_empty() && res_bytes[res_bytes.len() - 1] == 0 {
467 Ok(InvoiceFeatures::from_le_bytes(res_bytes))
471 impl<T: sealed::Context> Features<T> {
472 /// Create a blank Features with no features set
473 pub fn empty() -> Self {
480 /// Creates a Features with the bits set which are known by the implementation
481 pub fn known() -> Self {
483 flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
488 /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
489 /// included in the result.
490 fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
491 let byte_count = C::KNOWN_FEATURE_MASK.len();
492 let mut flags = Vec::new();
493 for (i, byte) in self.flags.iter().enumerate() {
495 let known_source_features = T::KNOWN_FEATURE_MASK[i];
496 let known_target_features = C::KNOWN_FEATURE_MASK[i];
497 flags.push(byte & known_source_features & known_target_features);
500 Features::<C> { flags, mark: PhantomData, }
503 /// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
504 /// most on-the-wire encodings.
505 pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
513 /// Gets the underlying flags set, in LE.
514 pub fn le_flags(&self) -> &Vec<u8> {
518 pub(crate) fn requires_unknown_bits(&self) -> bool {
519 // Bitwise AND-ing with all even bits set except for known features will select required
521 let byte_count = T::KNOWN_FEATURE_MASK.len();
522 self.flags.iter().enumerate().any(|(i, &byte)| {
523 let required_features = 0b01_01_01_01;
524 let unknown_features = if i < byte_count {
525 !T::KNOWN_FEATURE_MASK[i]
529 (byte & (required_features & unknown_features)) != 0
533 pub(crate) fn supports_unknown_bits(&self) -> bool {
534 // Bitwise AND-ing with all even and odd bits set except for known features will select
535 // both required and optional unknown features.
536 let byte_count = T::KNOWN_FEATURE_MASK.len();
537 self.flags.iter().enumerate().any(|(i, &byte)| {
538 let unknown_features = if i < byte_count {
539 !T::KNOWN_FEATURE_MASK[i]
543 (byte & unknown_features) != 0
547 /// The number of bytes required to represent the feature flags present. This does not include
548 /// the length bytes which are included in the serialized form.
549 pub(crate) fn byte_count(&self) -> usize {
554 pub(crate) fn set_required_unknown_bits(&mut self) {
555 <sealed::TestingContext as sealed::UnknownFeature>::set_required_bit(&mut self.flags);
559 pub(crate) fn set_optional_unknown_bits(&mut self) {
560 <sealed::TestingContext as sealed::UnknownFeature>::set_optional_bit(&mut self.flags);
564 pub(crate) fn clear_unknown_bits(&mut self) {
565 <sealed::TestingContext as sealed::UnknownFeature>::clear_bits(&mut self.flags);
569 impl<T: sealed::DataLossProtect> Features<T> {
571 pub(crate) fn requires_data_loss_protect(&self) -> bool {
572 <T as sealed::DataLossProtect>::requires_feature(&self.flags)
574 pub(crate) fn supports_data_loss_protect(&self) -> bool {
575 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
579 impl<T: sealed::UpfrontShutdownScript> Features<T> {
581 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
582 <T as sealed::UpfrontShutdownScript>::requires_feature(&self.flags)
584 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
585 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
588 pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
589 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
595 impl<T: sealed::GossipQueries> Features<T> {
597 pub(crate) fn requires_gossip_queries(&self) -> bool {
598 <T as sealed::GossipQueries>::requires_feature(&self.flags)
600 pub(crate) fn supports_gossip_queries(&self) -> bool {
601 <T as sealed::GossipQueries>::supports_feature(&self.flags)
604 pub(crate) fn clear_gossip_queries(mut self) -> Self {
605 <T as sealed::GossipQueries>::clear_bits(&mut self.flags);
610 impl<T: sealed::VariableLengthOnion> Features<T> {
612 pub(crate) fn requires_variable_length_onion(&self) -> bool {
613 <T as sealed::VariableLengthOnion>::requires_feature(&self.flags)
615 pub(crate) fn supports_variable_length_onion(&self) -> bool {
616 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
620 impl<T: sealed::StaticRemoteKey> Features<T> {
621 pub(crate) fn supports_static_remote_key(&self) -> bool {
622 <T as sealed::StaticRemoteKey>::supports_feature(&self.flags)
625 pub(crate) fn requires_static_remote_key(&self) -> bool {
626 <T as sealed::StaticRemoteKey>::requires_feature(&self.flags)
630 impl<T: sealed::InitialRoutingSync> Features<T> {
631 pub(crate) fn initial_routing_sync(&self) -> bool {
632 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
634 // We are no longer setting initial_routing_sync now that gossip_queries
635 // is enabled. This feature is ignored by a peer when gossip_queries has
638 pub(crate) fn clear_initial_routing_sync(&mut self) {
639 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
643 impl<T: sealed::PaymentSecret> Features<T> {
645 pub(crate) fn requires_payment_secret(&self) -> bool {
646 <T as sealed::PaymentSecret>::requires_feature(&self.flags)
648 // Note that we never need to test this since what really matters is the invoice - iff the
649 // invoice provides a payment_secret, we assume that we can use it (ie that the recipient
650 // supports payment_secret).
652 pub(crate) fn supports_payment_secret(&self) -> bool {
653 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
657 impl<T: sealed::BasicMPP> Features<T> {
659 pub(crate) fn requires_basic_mpp(&self) -> bool {
660 <T as sealed::BasicMPP>::requires_feature(&self.flags)
662 // We currently never test for this since we don't actually *generate* multipath routes.
663 pub(crate) fn supports_basic_mpp(&self) -> bool {
664 <T as sealed::BasicMPP>::supports_feature(&self.flags)
668 impl<T: sealed::ShutdownAnySegwit> Features<T> {
669 pub(crate) fn supports_shutdown_anysegwit(&self) -> bool {
670 <T as sealed::ShutdownAnySegwit>::supports_feature(&self.flags)
673 pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
674 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
679 impl<T: sealed::Context> Writeable for Features<T> {
680 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
681 w.size_hint(self.flags.len() + 2);
682 (self.flags.len() as u16).write(w)?;
683 for f in self.flags.iter().rev() { // Swap back to big-endian
690 impl<T: sealed::Context> Readable for Features<T> {
691 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
692 let mut flags: Vec<u8> = Readable::read(r)?;
693 flags.reverse(); // Swap to little-endian
703 use super::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
704 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5};
707 fn sanity_test_known_features() {
708 assert!(!ChannelFeatures::known().requires_unknown_bits());
709 assert!(!ChannelFeatures::known().supports_unknown_bits());
710 assert!(!InitFeatures::known().requires_unknown_bits());
711 assert!(!InitFeatures::known().supports_unknown_bits());
712 assert!(!NodeFeatures::known().requires_unknown_bits());
713 assert!(!NodeFeatures::known().supports_unknown_bits());
715 assert!(InitFeatures::known().supports_upfront_shutdown_script());
716 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
717 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
718 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
720 assert!(InitFeatures::known().supports_gossip_queries());
721 assert!(NodeFeatures::known().supports_gossip_queries());
722 assert!(!InitFeatures::known().requires_gossip_queries());
723 assert!(!NodeFeatures::known().requires_gossip_queries());
725 assert!(InitFeatures::known().supports_data_loss_protect());
726 assert!(NodeFeatures::known().supports_data_loss_protect());
727 assert!(!InitFeatures::known().requires_data_loss_protect());
728 assert!(!NodeFeatures::known().requires_data_loss_protect());
730 assert!(InitFeatures::known().supports_variable_length_onion());
731 assert!(NodeFeatures::known().supports_variable_length_onion());
732 assert!(!InitFeatures::known().requires_variable_length_onion());
733 assert!(!NodeFeatures::known().requires_variable_length_onion());
735 assert!(InitFeatures::known().supports_static_remote_key());
736 assert!(NodeFeatures::known().supports_static_remote_key());
737 assert!(InitFeatures::known().requires_static_remote_key());
738 assert!(NodeFeatures::known().requires_static_remote_key());
740 assert!(InitFeatures::known().supports_payment_secret());
741 assert!(NodeFeatures::known().supports_payment_secret());
742 assert!(InitFeatures::known().requires_payment_secret());
743 assert!(NodeFeatures::known().requires_payment_secret());
745 assert!(InitFeatures::known().supports_basic_mpp());
746 assert!(NodeFeatures::known().supports_basic_mpp());
747 assert!(!InitFeatures::known().requires_basic_mpp());
748 assert!(!NodeFeatures::known().requires_basic_mpp());
750 assert!(InitFeatures::known().supports_shutdown_anysegwit());
751 assert!(NodeFeatures::known().supports_shutdown_anysegwit());
753 let mut init_features = InitFeatures::known();
754 assert!(init_features.initial_routing_sync());
755 init_features.clear_initial_routing_sync();
756 assert!(!init_features.initial_routing_sync());
760 fn sanity_test_unknown_bits() {
761 let mut features = ChannelFeatures::empty();
762 assert!(!features.requires_unknown_bits());
763 assert!(!features.supports_unknown_bits());
765 features.set_required_unknown_bits();
766 assert!(features.requires_unknown_bits());
767 assert!(features.supports_unknown_bits());
769 features.clear_unknown_bits();
770 assert!(!features.requires_unknown_bits());
771 assert!(!features.supports_unknown_bits());
773 features.set_optional_unknown_bits();
774 assert!(!features.requires_unknown_bits());
775 assert!(features.supports_unknown_bits());
779 fn convert_to_context_with_relevant_flags() {
780 let init_features = InitFeatures::known().clear_upfront_shutdown_script().clear_gossip_queries();
781 assert!(init_features.initial_routing_sync());
782 assert!(!init_features.supports_upfront_shutdown_script());
783 assert!(!init_features.supports_gossip_queries());
785 let node_features: NodeFeatures = init_features.to_context();
787 // Check that the flags are as expected:
788 // - option_data_loss_protect
789 // - var_onion_optin | static_remote_key (req) | payment_secret(req)
791 // - opt_shutdown_anysegwit
792 assert_eq!(node_features.flags.len(), 4);
793 assert_eq!(node_features.flags[0], 0b00000010);
794 assert_eq!(node_features.flags[1], 0b01010010);
795 assert_eq!(node_features.flags[2], 0b00000010);
796 assert_eq!(node_features.flags[3], 0b00001000);
799 // Check that cleared flags are kept blank when converting back:
800 // - initial_routing_sync was not applicable to NodeContext
801 // - upfront_shutdown_script was cleared before converting
802 // - gossip_queries was cleared before converting
803 let features: InitFeatures = node_features.to_context_internal();
804 assert!(!features.initial_routing_sync());
805 assert!(!features.supports_upfront_shutdown_script());
806 assert!(!init_features.supports_gossip_queries());
810 fn set_feature_bits() {
811 let features = InvoiceFeatures::empty()
812 .set_basic_mpp_optional()
813 .set_payment_secret_required();
814 assert!(features.supports_basic_mpp());
815 assert!(!features.requires_basic_mpp());
816 assert!(features.requires_payment_secret());
817 assert!(features.supports_payment_secret());
821 fn invoice_features_encoding() {
822 let features_as_u5s = vec![
823 u5::try_from_u8(6).unwrap(),
824 u5::try_from_u8(10).unwrap(),
825 u5::try_from_u8(25).unwrap(),
826 u5::try_from_u8(1).unwrap(),
827 u5::try_from_u8(10).unwrap(),
828 u5::try_from_u8(0).unwrap(),
829 u5::try_from_u8(20).unwrap(),
830 u5::try_from_u8(2).unwrap(),
831 u5::try_from_u8(0).unwrap(),
832 u5::try_from_u8(6).unwrap(),
833 u5::try_from_u8(0).unwrap(),
834 u5::try_from_u8(16).unwrap(),
835 u5::try_from_u8(1).unwrap(),
837 let features = InvoiceFeatures::from_le_bytes(vec![1, 2, 3, 4, 5, 42, 100, 101]);
839 // Test length calculation.
840 assert_eq!(features.base32_len(), 13);
842 // Test serialization.
843 let features_serialized = features.to_base32();
844 assert_eq!(features_as_u5s, features_serialized);
846 // Test deserialization.
847 let features_deserialized = InvoiceFeatures::from_base32(&features_as_u5s).unwrap();
848 assert_eq!(features, features_deserialized);