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). A
16 //! [`Context`] is used to parameterize [`Features`] and defines which features it can support.
18 //! Whether a feature is considered "known" or "unknown" is relative to the implementation, whereas
19 //! the term "supports" is used in reference to a particular set of [`Features`]. That is, a node
20 //! supports a feature if it advertises the feature (as either required or optional) to its peers.
21 //! And the implementation can interpret a feature if the feature is known to it.
23 //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
24 //! [messages]: ../msgs/index.html
25 //! [`Features`]: struct.Features.html
26 //! [`Context`]: sealed/trait.Context.html
29 use std::result::Result;
30 use std::marker::PhantomData;
32 use ln::msgs::DecodeError;
33 use util::ser::{Readable, Writeable, Writer};
36 /// The context in which [`Features`] are applicable. Defines which features are required and
37 /// which are optional for the context.
39 /// [`Features`]: ../struct.Features.html
41 /// Features that are known to the implementation, where a required feature is indicated by
42 /// its even bit and an optional feature is indicated by its odd bit.
43 const KNOWN_FEATURE_FLAGS: &'static [u8];
45 /// Bitmask for selecting features that are known to the implementation, regardless of
46 /// whether each feature is required or optional.
47 const KNOWN_FEATURE_MASK: &'static [u8];
50 /// Defines a [`Context`] by stating which features it requires and which are optional. Features
51 /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
52 /// feature identifiers.
54 /// [`Context`]: trait.Context.html
55 macro_rules! define_context {
57 required_features: [$( $( $required_feature: ident )|*, )*],
58 optional_features: [$( $( $optional_feature: ident )|*, )*],
60 pub struct $context {}
62 impl Context for $context {
63 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
64 // For each byte, use bitwise-OR to compute the applicable flags for known
65 // required features `r_i` and optional features `o_j` for all `i` and `j` such
66 // that the following slice is formed:
69 // `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
74 <Self as $required_feature>::REQUIRED_MASK)*
76 <Self as $optional_feature>::OPTIONAL_MASK)*,
80 const KNOWN_FEATURE_MASK: &'static [u8] = &[
81 // Similar as above, but set both flags for each feature regardless of whether
82 // the feature is required or optional.
85 <Self as $required_feature>::REQUIRED_MASK |
86 <Self as $required_feature>::OPTIONAL_MASK)*
88 <Self as $optional_feature>::REQUIRED_MASK |
89 <Self as $optional_feature>::OPTIONAL_MASK)*,
96 define_context!(InitContext {
107 DataLossProtect | InitialRoutingSync | UpfrontShutdownScript,
109 VariableLengthOnion | PaymentSecret,
114 define_context!(NodeContext {
125 DataLossProtect | UpfrontShutdownScript,
127 VariableLengthOnion | PaymentSecret,
132 define_context!(ChannelContext {
133 required_features: [],
134 optional_features: [],
137 /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
138 /// useful for manipulating feature flags.
140 /// [`Context`]: trait.Context.html
141 macro_rules! define_feature {
142 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr) => {
145 /// See [BOLT #9] for details.
147 /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
148 pub trait $feature: Context {
149 /// The bit used to signify that the feature is required.
150 const EVEN_BIT: usize = $odd_bit - 1;
152 /// The bit used to signify that the feature is optional.
153 const ODD_BIT: usize = $odd_bit;
155 /// Assertion that [`EVEN_BIT`] is actually even.
157 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
158 const ASSERT_EVEN_BIT_PARITY: usize;
160 /// Assertion that [`ODD_BIT`] is actually odd.
162 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
163 const ASSERT_ODD_BIT_PARITY: usize;
165 /// The byte where the feature is set.
166 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
168 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
170 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
171 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
173 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
175 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
176 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
178 /// Returns whether the feature is required by the given flags.
180 fn requires_feature(flags: &Vec<u8>) -> bool {
181 flags.len() > Self::BYTE_OFFSET &&
182 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
185 /// Returns whether the feature is supported by the given flags.
187 fn supports_feature(flags: &Vec<u8>) -> bool {
188 flags.len() > Self::BYTE_OFFSET &&
189 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
192 /// Sets the feature's required (even) bit in the given flags.
194 fn set_required_bit(flags: &mut Vec<u8>) {
195 if flags.len() <= Self::BYTE_OFFSET {
196 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
199 flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
202 /// Sets the feature's optional (odd) bit in the given flags.
204 fn set_optional_bit(flags: &mut Vec<u8>) {
205 if flags.len() <= Self::BYTE_OFFSET {
206 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
209 flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
212 /// Clears the feature's required (even) and optional (odd) bits from the given
215 fn clear_bits(flags: &mut Vec<u8>) {
216 if flags.len() > Self::BYTE_OFFSET {
217 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
218 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
221 let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
222 let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
223 flags.resize(size, 0u8);
228 impl $feature for $context {
230 const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
233 const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
239 define_feature!(1, DataLossProtect, [InitContext, NodeContext],
240 "Feature flags for `option_data_loss_protect`.");
241 // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
242 define_feature!(3, InitialRoutingSync, [InitContext],
243 "Feature flags for `initial_routing_sync`.");
244 define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
245 "Feature flags for `option_upfront_shutdown_script`.");
246 define_feature!(9, VariableLengthOnion, [InitContext, NodeContext],
247 "Feature flags for `var_onion_optin`.");
248 define_feature!(13, StaticRemoteKey, [InitContext, NodeContext],
249 "Feature flags for `option_static_remotekey`.");
250 define_feature!(15, PaymentSecret, [InitContext, NodeContext],
251 "Feature flags for `payment_secret`.");
252 define_feature!(17, BasicMPP, [InitContext, NodeContext],
253 "Feature flags for `basic_mpp`.");
256 define_context!(TestingContext {
276 define_feature!(23, UnknownFeature, [TestingContext],
277 "Feature flags for an unknown feature used in testing.");
280 /// Tracks the set of features which a node implements, templated by the context in which it
283 /// (C-not exported) as we map the concrete feature types below directly instead
284 pub struct Features<T: sealed::Context> {
285 /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
287 mark: PhantomData<T>,
290 impl<T: sealed::Context> Clone for Features<T> {
291 fn clone(&self) -> Self {
293 flags: self.flags.clone(),
298 impl<T: sealed::Context> PartialEq for Features<T> {
299 fn eq(&self, o: &Self) -> bool {
300 self.flags.eq(&o.flags)
303 impl<T: sealed::Context> fmt::Debug for Features<T> {
304 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
309 /// Features used within an `init` message.
310 pub type InitFeatures = Features<sealed::InitContext>;
311 /// Features used within a `node_announcement` message.
312 pub type NodeFeatures = Features<sealed::NodeContext>;
313 /// Features used within a `channel_announcement` message.
314 pub type ChannelFeatures = Features<sealed::ChannelContext>;
317 /// Writes all features present up to, and including, 13.
318 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
319 let len = cmp::min(2, self.flags.len());
320 w.size_hint(len + 2);
321 (len as u16).write(w)?;
322 for i in (0..len).rev() {
324 self.flags[i].write(w)?;
326 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
327 // up-to-and-including-bit-5, 0-indexed, on this byte:
328 (self.flags[i] & 0b00_11_11_11).write(w)?;
334 /// or's another InitFeatures into this one.
335 pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
336 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
337 self.flags.resize(total_feature_len, 0u8);
338 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
344 /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
345 /// are included in the result.
346 pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
347 self.to_context_internal()
351 impl<T: sealed::Context> Features<T> {
352 /// Create a blank Features with no features set
353 pub fn empty() -> Features<T> {
360 /// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
362 /// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
363 pub fn known() -> Features<T> {
365 flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
370 /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
371 /// included in the result.
372 fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
373 let byte_count = C::KNOWN_FEATURE_MASK.len();
374 let mut flags = Vec::new();
375 for (i, byte) in self.flags.iter().enumerate() {
377 let known_source_features = T::KNOWN_FEATURE_MASK[i];
378 let known_target_features = C::KNOWN_FEATURE_MASK[i];
379 flags.push(byte & known_source_features & known_target_features);
382 Features::<C> { flags, mark: PhantomData, }
386 /// Create a Features given a set of flags, in LE.
387 pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
395 /// Gets the underlying flags set, in LE.
396 pub fn le_flags(&self) -> &Vec<u8> {
400 pub(crate) fn requires_unknown_bits(&self) -> bool {
401 // Bitwise AND-ing with all even bits set except for known features will select required
403 let byte_count = T::KNOWN_FEATURE_MASK.len();
404 self.flags.iter().enumerate().any(|(i, &byte)| {
405 let required_features = 0b01_01_01_01;
406 let unknown_features = if i < byte_count {
407 !T::KNOWN_FEATURE_MASK[i]
411 (byte & (required_features & unknown_features)) != 0
415 pub(crate) fn supports_unknown_bits(&self) -> bool {
416 // Bitwise AND-ing with all even and odd bits set except for known features will select
417 // both required and optional unknown features.
418 let byte_count = T::KNOWN_FEATURE_MASK.len();
419 self.flags.iter().enumerate().any(|(i, &byte)| {
420 let unknown_features = if i < byte_count {
421 !T::KNOWN_FEATURE_MASK[i]
425 (byte & unknown_features) != 0
429 /// The number of bytes required to represent the feature flags present. This does not include
430 /// the length bytes which are included in the serialized form.
431 pub(crate) fn byte_count(&self) -> usize {
436 pub(crate) fn set_required_unknown_bits(&mut self) {
437 <sealed::TestingContext as sealed::UnknownFeature>::set_required_bit(&mut self.flags);
441 pub(crate) fn set_optional_unknown_bits(&mut self) {
442 <sealed::TestingContext as sealed::UnknownFeature>::set_optional_bit(&mut self.flags);
446 pub(crate) fn clear_unknown_bits(&mut self) {
447 <sealed::TestingContext as sealed::UnknownFeature>::clear_bits(&mut self.flags);
451 impl<T: sealed::DataLossProtect> Features<T> {
453 pub(crate) fn requires_data_loss_protect(&self) -> bool {
454 <T as sealed::DataLossProtect>::requires_feature(&self.flags)
456 pub(crate) fn supports_data_loss_protect(&self) -> bool {
457 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
461 impl<T: sealed::UpfrontShutdownScript> Features<T> {
463 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
464 <T as sealed::UpfrontShutdownScript>::requires_feature(&self.flags)
466 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
467 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
470 pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
471 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
476 impl<T: sealed::VariableLengthOnion> Features<T> {
478 pub(crate) fn requires_variable_length_onion(&self) -> bool {
479 <T as sealed::VariableLengthOnion>::requires_feature(&self.flags)
481 pub(crate) fn supports_variable_length_onion(&self) -> bool {
482 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
486 impl<T: sealed::StaticRemoteKey> Features<T> {
487 pub(crate) fn supports_static_remote_key(&self) -> bool {
488 <T as sealed::StaticRemoteKey>::supports_feature(&self.flags)
491 pub(crate) fn requires_static_remote_key(&self) -> bool {
492 <T as sealed::StaticRemoteKey>::requires_feature(&self.flags)
496 impl<T: sealed::InitialRoutingSync> Features<T> {
497 pub(crate) fn initial_routing_sync(&self) -> bool {
498 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
500 pub(crate) fn clear_initial_routing_sync(&mut self) {
501 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
505 impl<T: sealed::PaymentSecret> Features<T> {
507 pub(crate) fn requires_payment_secret(&self) -> bool {
508 <T as sealed::PaymentSecret>::requires_feature(&self.flags)
510 // Note that we never need to test this since what really matters is the invoice - iff the
511 // invoice provides a payment_secret, we assume that we can use it (ie that the recipient
512 // supports payment_secret).
514 pub(crate) fn supports_payment_secret(&self) -> bool {
515 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
519 impl<T: sealed::BasicMPP> Features<T> {
521 pub(crate) fn requires_basic_mpp(&self) -> bool {
522 <T as sealed::BasicMPP>::requires_feature(&self.flags)
524 // We currently never test for this since we don't actually *generate* multipath routes.
526 pub(crate) fn supports_basic_mpp(&self) -> bool {
527 <T as sealed::BasicMPP>::supports_feature(&self.flags)
531 impl<T: sealed::Context> Writeable for Features<T> {
532 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
533 w.size_hint(self.flags.len() + 2);
534 (self.flags.len() as u16).write(w)?;
535 for f in self.flags.iter().rev() { // Swap back to big-endian
542 impl<T: sealed::Context> Readable for Features<T> {
543 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
544 let mut flags: Vec<u8> = Readable::read(r)?;
545 flags.reverse(); // Swap to little-endian
555 use super::{ChannelFeatures, InitFeatures, NodeFeatures};
558 fn sanity_test_known_features() {
559 assert!(!ChannelFeatures::known().requires_unknown_bits());
560 assert!(!ChannelFeatures::known().supports_unknown_bits());
561 assert!(!InitFeatures::known().requires_unknown_bits());
562 assert!(!InitFeatures::known().supports_unknown_bits());
563 assert!(!NodeFeatures::known().requires_unknown_bits());
564 assert!(!NodeFeatures::known().supports_unknown_bits());
566 assert!(InitFeatures::known().supports_upfront_shutdown_script());
567 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
568 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
569 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
571 assert!(InitFeatures::known().supports_data_loss_protect());
572 assert!(NodeFeatures::known().supports_data_loss_protect());
573 assert!(!InitFeatures::known().requires_data_loss_protect());
574 assert!(!NodeFeatures::known().requires_data_loss_protect());
576 assert!(InitFeatures::known().supports_variable_length_onion());
577 assert!(NodeFeatures::known().supports_variable_length_onion());
578 assert!(!InitFeatures::known().requires_variable_length_onion());
579 assert!(!NodeFeatures::known().requires_variable_length_onion());
581 assert!(InitFeatures::known().supports_static_remote_key());
582 assert!(NodeFeatures::known().supports_static_remote_key());
583 assert!(InitFeatures::known().requires_static_remote_key());
584 assert!(NodeFeatures::known().requires_static_remote_key());
586 assert!(InitFeatures::known().supports_payment_secret());
587 assert!(NodeFeatures::known().supports_payment_secret());
588 assert!(!InitFeatures::known().requires_payment_secret());
589 assert!(!NodeFeatures::known().requires_payment_secret());
591 assert!(InitFeatures::known().supports_basic_mpp());
592 assert!(NodeFeatures::known().supports_basic_mpp());
593 assert!(!InitFeatures::known().requires_basic_mpp());
594 assert!(!NodeFeatures::known().requires_basic_mpp());
596 let mut init_features = InitFeatures::known();
597 assert!(init_features.initial_routing_sync());
598 init_features.clear_initial_routing_sync();
599 assert!(!init_features.initial_routing_sync());
603 fn sanity_test_unknown_bits() {
604 let mut features = ChannelFeatures::empty();
605 assert!(!features.requires_unknown_bits());
606 assert!(!features.supports_unknown_bits());
608 features.set_required_unknown_bits();
609 assert!(features.requires_unknown_bits());
610 assert!(features.supports_unknown_bits());
612 features.clear_unknown_bits();
613 assert!(!features.requires_unknown_bits());
614 assert!(!features.supports_unknown_bits());
616 features.set_optional_unknown_bits();
617 assert!(!features.requires_unknown_bits());
618 assert!(features.supports_unknown_bits());
622 fn convert_to_context_with_relevant_flags() {
623 let init_features = InitFeatures::known().clear_upfront_shutdown_script();
624 assert!(init_features.initial_routing_sync());
625 assert!(!init_features.supports_upfront_shutdown_script());
627 let node_features: NodeFeatures = init_features.to_context();
629 // Check that the flags are as expected:
630 // - option_data_loss_protect
631 // - var_onion_optin | static_remote_key (req) | payment_secret
633 assert_eq!(node_features.flags.len(), 3);
634 assert_eq!(node_features.flags[0], 0b00000010);
635 assert_eq!(node_features.flags[1], 0b10010010);
636 assert_eq!(node_features.flags[2], 0b00000010);
639 // Check that cleared flags are kept blank when converting back:
640 // - initial_routing_sync was not applicable to NodeContext
641 // - upfront_shutdown_script was cleared before converting
642 let features: InitFeatures = node_features.to_context_internal();
643 assert!(!features.initial_routing_sync());
644 assert!(!features.supports_upfront_shutdown_script());