1 //! Lightning exposes sets of supported operations through "feature flags". This module includes
2 //! types to store those feature flags and query for specific flags.
5 use std::result::Result;
6 use std::marker::PhantomData;
8 use ln::msgs::DecodeError;
9 use util::ser::{Readable, Writeable, Writer};
12 mod sealed { // You should just use the type aliases instead.
13 pub struct InitContext {}
14 pub struct NodeContext {}
15 pub struct ChannelContext {}
17 /// An internal trait capturing the various feature context types
19 impl Context for InitContext {}
20 impl Context for NodeContext {}
21 impl Context for ChannelContext {}
23 /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
24 /// useful for manipulating feature flags.
26 /// [`Context`]: trait.Context.html
27 macro_rules! define_feature {
28 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr) => {
31 /// See [BOLT #9] for details.
33 /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
34 pub trait $feature: Context {
35 /// The bit used to signify that the feature is required.
36 const EVEN_BIT: usize = $odd_bit - 1;
38 /// The bit used to signify that the feature is optional.
39 const ODD_BIT: usize = $odd_bit;
41 /// Assertion that [`EVEN_BIT`] is actually even.
43 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
44 const ASSERT_EVEN_BIT_PARITY: usize;
46 /// Assertion that [`ODD_BIT`] is actually odd.
48 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
49 const ASSERT_ODD_BIT_PARITY: usize;
51 /// The byte where the feature is set.
52 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
54 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
56 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
57 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
59 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
61 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
62 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
64 /// Returns whether the feature is supported by the given flags.
66 fn supports_feature(flags: &Vec<u8>) -> bool {
67 flags.len() > Self::BYTE_OFFSET &&
68 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
71 /// Sets the feature's optional (odd) bit in the given flags.
73 fn set_optional_bit(flags: &mut Vec<u8>) {
74 if flags.len() <= Self::BYTE_OFFSET {
75 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
78 flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
81 /// Clears the feature's optional (odd) bit from the given flags.
83 fn clear_optional_bit(flags: &mut Vec<u8>) {
84 if flags.len() > Self::BYTE_OFFSET {
85 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
91 impl $feature for $context {
93 const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
96 const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
102 define_feature!(1, DataLossProtect, [InitContext, NodeContext],
103 "Feature flags for `option_data_loss_protect`.");
104 // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
105 define_feature!(3, InitialRoutingSync, [InitContext],
106 "Feature flags for `initial_routing_sync`.");
107 define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
108 "Feature flags for `option_upfront_shutdown_script`.");
109 define_feature!(9, VariableLengthOnion, [InitContext, NodeContext],
110 "Feature flags for `var_onion_optin`.");
111 define_feature!(15, PaymentSecret, [InitContext, NodeContext],
112 "Feature flags for `payment_secret`.");
113 define_feature!(17, BasicMPP, [InitContext, NodeContext],
114 "Feature flags for `basic_mpp`.");
116 /// Generates a feature flag byte with the given features set as optional. Useful for initializing
117 /// the flags within [`Features`].
119 /// [`Features`]: struct.Features.html
120 macro_rules! feature_flags {
121 ($context: ty; $($feature: ident)|*) => {
124 | <$context as sealed::$feature>::OPTIONAL_MASK
131 /// Tracks the set of features which a node implements, templated by the context in which it
133 pub struct Features<T: sealed::Context> {
134 /// Note that, for convinience, flags is LITTLE endian (despite being big-endian on the wire)
136 mark: PhantomData<T>,
139 impl<T: sealed::Context> Clone for Features<T> {
140 fn clone(&self) -> Self {
142 flags: self.flags.clone(),
147 impl<T: sealed::Context> PartialEq for Features<T> {
148 fn eq(&self, o: &Self) -> bool {
149 self.flags.eq(&o.flags)
152 impl<T: sealed::Context> fmt::Debug for Features<T> {
153 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
158 /// A feature message as it appears in an init message
159 pub type InitFeatures = Features<sealed::InitContext>;
160 /// A feature message as it appears in a node_announcement message
161 pub type NodeFeatures = Features<sealed::NodeContext>;
162 /// A feature message as it appears in a channel_announcement message
163 pub type ChannelFeatures = Features<sealed::ChannelContext>;
166 /// Create a Features with the features we support
167 pub fn supported() -> InitFeatures {
170 feature_flags![sealed::InitContext; DataLossProtect | InitialRoutingSync | UpfrontShutdownScript],
171 feature_flags![sealed::InitContext; VariableLengthOnion | PaymentSecret],
172 feature_flags![sealed::InitContext; BasicMPP],
178 /// Writes all features present up to, and including, 13.
179 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
180 let len = cmp::min(2, self.flags.len());
181 w.size_hint(len + 2);
182 (len as u16).write(w)?;
183 for i in (0..len).rev() {
185 self.flags[i].write(w)?;
187 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
188 // up-to-and-including-bit-5, 0-indexed, on this byte:
189 (self.flags[i] & 0b00_11_11_11).write(w)?;
195 /// or's another InitFeatures into this one.
196 pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
197 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
198 self.flags.resize(total_feature_len, 0u8);
199 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
206 impl ChannelFeatures {
207 /// Create a Features with the features we support
208 #[cfg(not(feature = "fuzztarget"))]
209 pub(crate) fn supported() -> ChannelFeatures {
215 #[cfg(feature = "fuzztarget")]
216 pub fn supported() -> ChannelFeatures {
223 /// Takes the flags that we know how to interpret in an init-context features that are also
224 /// relevant in a channel-context features and creates a channel-context features from them.
225 pub(crate) fn with_known_relevant_init_flags(_init_ctx: &InitFeatures) -> Self {
226 // There are currently no channel flags defined that we understand.
227 Self { flags: Vec::new(), mark: PhantomData, }
232 /// Create a Features with the features we support
233 #[cfg(not(feature = "fuzztarget"))]
234 pub(crate) fn supported() -> NodeFeatures {
237 feature_flags![sealed::NodeContext; DataLossProtect | UpfrontShutdownScript],
238 feature_flags![sealed::NodeContext; VariableLengthOnion | PaymentSecret],
239 feature_flags![sealed::NodeContext; BasicMPP],
244 #[cfg(feature = "fuzztarget")]
245 pub fn supported() -> NodeFeatures {
248 feature_flags![sealed::NodeContext; DataLossProtect | UpfrontShutdownScript],
249 feature_flags![sealed::NodeContext; VariableLengthOnion | PaymentSecret],
250 feature_flags![sealed::NodeContext; BasicMPP],
256 /// Takes the flags that we know how to interpret in an init-context features that are also
257 /// relevant in a node-context features and creates a node-context features from them.
258 /// Be sure to blank out features that are unknown to us.
259 pub(crate) fn with_known_relevant_init_flags(init_ctx: &InitFeatures) -> Self {
260 // Generates a bitmask with both even and odd bits set for the given features. Bitwise
261 // AND-ing it with a byte will select only common features.
262 macro_rules! features_including {
263 ($($feature: ident)|*) => {
266 | <sealed::NodeContext as sealed::$feature>::REQUIRED_MASK
267 | <sealed::NodeContext as sealed::$feature>::OPTIONAL_MASK
273 let mut flags = Vec::new();
274 for (i, feature_byte)in init_ctx.flags.iter().enumerate() {
276 0 => flags.push(feature_byte & features_including![DataLossProtect | UpfrontShutdownScript]),
277 1 => flags.push(feature_byte & features_including![VariableLengthOnion | PaymentSecret]),
278 2 => flags.push(feature_byte & features_including![BasicMPP]),
282 Self { flags, mark: PhantomData, }
286 impl<T: sealed::Context> Features<T> {
287 /// Create a blank Features with no features set
288 pub fn empty() -> Features<T> {
296 /// Create a Features given a set of flags, in LE.
297 pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
305 /// Gets the underlying flags set, in LE.
306 pub fn le_flags(&self) -> &Vec<u8> {
310 pub(crate) fn requires_unknown_bits(&self) -> bool {
311 // Generates a bitmask with all even bits set except for the given features. Bitwise
312 // AND-ing it with a byte will select unknown required features.
313 macro_rules! features_excluding {
314 ($($feature: ident)|*) => {
317 & !(<sealed::InitContext as sealed::$feature>::REQUIRED_MASK)
323 self.flags.iter().enumerate().any(|(idx, &byte)| {
325 0 => (byte & features_excluding![DataLossProtect | InitialRoutingSync | UpfrontShutdownScript]),
326 1 => (byte & features_excluding![VariableLengthOnion | PaymentSecret]),
327 2 => (byte & features_excluding![BasicMPP]),
328 _ => (byte & features_excluding![]),
333 pub(crate) fn supports_unknown_bits(&self) -> bool {
334 // Generates a bitmask with all even and odd bits set except for the given features. Bitwise
335 // AND-ing it with a byte will select unknown supported features.
336 macro_rules! features_excluding {
337 ($($feature: ident)|*) => {
340 & !(<sealed::InitContext as sealed::$feature>::REQUIRED_MASK)
341 & !(<sealed::InitContext as sealed::$feature>::OPTIONAL_MASK)
347 self.flags.iter().enumerate().any(|(idx, &byte)| {
349 0 => (byte & features_excluding![DataLossProtect | InitialRoutingSync | UpfrontShutdownScript]),
350 1 => (byte & features_excluding![VariableLengthOnion | PaymentSecret]),
351 2 => (byte & features_excluding![BasicMPP]),
357 /// The number of bytes required to represent the feature flags present. This does not include
358 /// the length bytes which are included in the serialized form.
359 pub(crate) fn byte_count(&self) -> usize {
364 pub(crate) fn set_require_unknown_bits(&mut self) {
365 let newlen = cmp::max(3, self.flags.len());
366 self.flags.resize(newlen, 0u8);
367 self.flags[2] |= 0x40;
371 pub(crate) fn clear_require_unknown_bits(&mut self) {
372 let newlen = cmp::max(3, self.flags.len());
373 self.flags.resize(newlen, 0u8);
374 self.flags[2] &= !0x40;
375 if self.flags.len() == 3 && self.flags[2] == 0 {
376 self.flags.resize(2, 0u8);
378 if self.flags.len() == 2 && self.flags[1] == 0 {
379 self.flags.resize(1, 0u8);
384 impl<T: sealed::DataLossProtect> Features<T> {
385 pub(crate) fn supports_data_loss_protect(&self) -> bool {
386 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
390 impl<T: sealed::UpfrontShutdownScript> Features<T> {
391 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
392 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
395 pub(crate) fn unset_upfront_shutdown_script(&mut self) {
396 <T as sealed::UpfrontShutdownScript>::clear_optional_bit(&mut self.flags)
400 impl<T: sealed::VariableLengthOnion> Features<T> {
401 pub(crate) fn supports_variable_length_onion(&self) -> bool {
402 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
406 impl<T: sealed::InitialRoutingSync> Features<T> {
407 pub(crate) fn initial_routing_sync(&self) -> bool {
408 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
410 pub(crate) fn clear_initial_routing_sync(&mut self) {
411 <T as sealed::InitialRoutingSync>::clear_optional_bit(&mut self.flags)
415 impl<T: sealed::PaymentSecret> Features<T> {
417 // Note that we never need to test this since what really matters is the invoice - iff the
418 // invoice provides a payment_secret, we assume that we can use it (ie that the recipient
419 // supports payment_secret).
420 pub(crate) fn supports_payment_secret(&self) -> bool {
421 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
425 impl<T: sealed::BasicMPP> Features<T> {
426 // We currently never test for this since we don't actually *generate* multipath routes.
428 pub(crate) fn supports_basic_mpp(&self) -> bool {
429 <T as sealed::BasicMPP>::supports_feature(&self.flags)
433 impl<T: sealed::Context> Writeable for Features<T> {
434 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
435 w.size_hint(self.flags.len() + 2);
436 (self.flags.len() as u16).write(w)?;
437 for f in self.flags.iter().rev() { // Swap back to big-endian
444 impl<T: sealed::Context> Readable for Features<T> {
445 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
446 let mut flags: Vec<u8> = Readable::read(r)?;
447 flags.reverse(); // Swap to little-endian
457 use super::{ChannelFeatures, InitFeatures, NodeFeatures, Features};
460 fn sanity_test_our_features() {
461 assert!(!ChannelFeatures::supported().requires_unknown_bits());
462 assert!(!ChannelFeatures::supported().supports_unknown_bits());
463 assert!(!InitFeatures::supported().requires_unknown_bits());
464 assert!(!InitFeatures::supported().supports_unknown_bits());
465 assert!(!NodeFeatures::supported().requires_unknown_bits());
466 assert!(!NodeFeatures::supported().supports_unknown_bits());
468 assert!(InitFeatures::supported().supports_upfront_shutdown_script());
469 assert!(NodeFeatures::supported().supports_upfront_shutdown_script());
471 assert!(InitFeatures::supported().supports_data_loss_protect());
472 assert!(NodeFeatures::supported().supports_data_loss_protect());
474 assert!(InitFeatures::supported().supports_variable_length_onion());
475 assert!(NodeFeatures::supported().supports_variable_length_onion());
477 assert!(InitFeatures::supported().supports_payment_secret());
478 assert!(NodeFeatures::supported().supports_payment_secret());
480 assert!(InitFeatures::supported().supports_basic_mpp());
481 assert!(NodeFeatures::supported().supports_basic_mpp());
483 let mut init_features = InitFeatures::supported();
484 assert!(init_features.initial_routing_sync());
485 init_features.clear_initial_routing_sync();
486 assert!(!init_features.initial_routing_sync());
490 fn sanity_test_unkown_bits_testing() {
491 let mut features = ChannelFeatures::supported();
492 features.set_require_unknown_bits();
493 assert!(features.requires_unknown_bits());
494 features.clear_require_unknown_bits();
495 assert!(!features.requires_unknown_bits());
499 fn test_node_with_known_relevant_init_flags() {
500 // Create an InitFeatures with initial_routing_sync supported.
501 let init_features = InitFeatures::supported();
502 assert!(init_features.initial_routing_sync());
504 // Attempt to pull out non-node-context feature flags from these InitFeatures.
505 let res = NodeFeatures::with_known_relevant_init_flags(&init_features);
508 // Check that the flags are as expected: optional_data_loss_protect,
509 // option_upfront_shutdown_script, var_onion_optin, payment_secret, and
511 assert_eq!(res.flags.len(), 3);
512 assert_eq!(res.flags[0], 0b00100010);
513 assert_eq!(res.flags[1], 0b10000010);
514 assert_eq!(res.flags[2], 0b00000010);
517 // Check that the initial_routing_sync feature was correctly blanked out.
518 let new_features: InitFeatures = Features::from_le_bytes(res.flags);
519 assert!(!new_features.initial_routing_sync());