Macroize feature printing to ensure we don't miss new flags
[rust-lightning] / lightning / src / ln / features.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Feature flag definitions for the Lightning protocol according to [BOLT #9].
11 //!
12 //! Lightning nodes advertise a supported set of operation through feature flags. Features are
13 //! applicable for a specific context 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).
16 //!
17 //! Whether a feature is considered "known" or "unknown" is relative to the implementation, whereas
18 //! the term "supports" is used in reference to a particular set of [`Features`]. That is, a node
19 //! supports a feature if it advertises the feature (as either required or optional) to its peers.
20 //! And the implementation can interpret a feature if the feature is known to it.
21 //!
22 //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
23 //! [messages]: crate::ln::msgs
24
25 use prelude::*;
26 use core::{cmp, fmt};
27 use core::marker::PhantomData;
28
29 use bitcoin::bech32;
30 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
31 use ln::msgs::DecodeError;
32 use util::ser::{Readable, Writeable, Writer};
33
34 mod sealed {
35         use prelude::*;
36         use ln::features::Features;
37
38         /// The context in which [`Features`] are applicable. Defines which features are required and
39         /// which are optional for the context.
40         pub trait Context {
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];
44
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];
48         }
49
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.
53         macro_rules! define_context {
54                 ($context: ident {
55                         required_features: [$( $( $required_feature: ident )|*, )*],
56                         optional_features: [$( $( $optional_feature: ident )|*, )*],
57                 }) => {
58                         #[derive(Eq, PartialEq)]
59                         pub struct $context {}
60
61                         impl Context for $context {
62                                 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
63                                         // For each byte, use bitwise-OR to compute the applicable flags for known
64                                         // required features `r_i` and optional features `o_j` for all `i` and `j` such
65                                         // that the following slice is formed:
66                                         //
67                                         // [
68                                         //  `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
69                                         //  ...,
70                                         // ]
71                                         $(
72                                                 0b00_00_00_00 $(|
73                                                         <Self as $required_feature>::REQUIRED_MASK)*
74                                                 $(|
75                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
76                                         )*
77                                 ];
78
79                                 const KNOWN_FEATURE_MASK: &'static [u8] = &[
80                                         // Similar as above, but set both flags for each feature regardless of whether
81                                         // the feature is required or optional.
82                                         $(
83                                                 0b00_00_00_00 $(|
84                                                         <Self as $required_feature>::REQUIRED_MASK |
85                                                         <Self as $required_feature>::OPTIONAL_MASK)*
86                                                 $(|
87                                                         <Self as $optional_feature>::REQUIRED_MASK |
88                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
89                                         )*
90                                 ];
91                         }
92
93                         impl alloc::fmt::Display for Features<$context> {
94                                 fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
95                                         $(
96                                                 $(
97                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($required_feature),
98                                                                 if <$context as $required_feature>::requires_feature(&self.flags) { "required" }
99                                                                 else if <$context as $required_feature>::supports_feature(&self.flags) { "supported" }
100                                                                 else { "not supported" }))?;
101                                                 )*
102                                                 $(
103                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($optional_feature),
104                                                                 if <$context as $optional_feature>::requires_feature(&self.flags) { "required" }
105                                                                 else if <$context as $optional_feature>::supports_feature(&self.flags) { "supported" }
106                                                                 else { "not supported" }))?;
107                                                 )*
108                                         )*
109                                         fmt.write_fmt(format_args!("unknown flags: {}",
110                                                 if self.requires_unknown_bits() { "required" }
111                                                 else if self.supports_unknown_bits() { "supported" } else { "none" }))
112                                 }
113                         }
114                 };
115         }
116
117         define_context!(InitContext {
118                 required_features: [
119                         // Byte 0
120                         ,
121                         // Byte 1
122                         VariableLengthOnion | StaticRemoteKey | PaymentSecret,
123                         // Byte 2
124                         ,
125                         // Byte 3
126                         ,
127                 ],
128                 optional_features: [
129                         // Byte 0
130                         DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
131                         // Byte 1
132                         ,
133                         // Byte 2
134                         BasicMPP,
135                         // Byte 3
136                         ShutdownAnySegwit,
137                 ],
138         });
139         define_context!(NodeContext {
140                 required_features: [
141                         // Byte 0
142                         ,
143                         // Byte 1
144                         VariableLengthOnion | StaticRemoteKey | PaymentSecret,
145                         // Byte 2
146                         ,
147                         // Byte 3
148                         ,
149                         // Byte 4
150                         ,
151                         // Byte 5
152                         ,
153                         // Byte 6
154                         ,
155                 ],
156                 optional_features: [
157                         // Byte 0
158                         DataLossProtect | UpfrontShutdownScript | GossipQueries,
159                         // Byte 1
160                         ,
161                         // Byte 2
162                         BasicMPP,
163                         // Byte 3
164                         ShutdownAnySegwit,
165                         // Byte 4
166                         ,
167                         // Byte 5
168                         ,
169                         // Byte 6
170                         Keysend,
171                 ],
172         });
173         define_context!(ChannelContext {
174                 required_features: [],
175                 optional_features: [],
176         });
177         define_context!(InvoiceContext {
178                 required_features: [
179                         // Byte 0
180                         ,
181                         // Byte 1
182                         VariableLengthOnion | PaymentSecret,
183                         // Byte 2
184                         ,
185                 ],
186                 optional_features: [
187                         // Byte 0
188                         ,
189                         // Byte 1
190                         ,
191                         // Byte 2
192                         BasicMPP,
193                 ],
194         });
195
196         /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
197         /// useful for manipulating feature flags.
198         macro_rules! define_feature {
199                 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
200                  $required_setter: ident) => {
201                         #[doc = $doc]
202                         ///
203                         /// See [BOLT #9] for details.
204                         ///
205                         /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
206                         pub trait $feature: Context {
207                                 /// The bit used to signify that the feature is required.
208                                 const EVEN_BIT: usize = $odd_bit - 1;
209
210                                 /// The bit used to signify that the feature is optional.
211                                 const ODD_BIT: usize = $odd_bit;
212
213                                 /// Assertion that [`EVEN_BIT`] is actually even.
214                                 ///
215                                 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
216                                 const ASSERT_EVEN_BIT_PARITY: usize;
217
218                                 /// Assertion that [`ODD_BIT`] is actually odd.
219                                 ///
220                                 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
221                                 const ASSERT_ODD_BIT_PARITY: usize;
222
223                                 /// The byte where the feature is set.
224                                 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
225
226                                 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
227                                 ///
228                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
229                                 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
230
231                                 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
232                                 ///
233                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
234                                 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
235
236                                 /// Returns whether the feature is required by the given flags.
237                                 #[inline]
238                                 fn requires_feature(flags: &Vec<u8>) -> bool {
239                                         flags.len() > Self::BYTE_OFFSET &&
240                                                 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
241                                 }
242
243                                 /// Returns whether the feature is supported by the given flags.
244                                 #[inline]
245                                 fn supports_feature(flags: &Vec<u8>) -> bool {
246                                         flags.len() > Self::BYTE_OFFSET &&
247                                                 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
248                                 }
249
250                                 /// Sets the feature's required (even) bit in the given flags.
251                                 #[inline]
252                                 fn set_required_bit(flags: &mut Vec<u8>) {
253                                         if flags.len() <= Self::BYTE_OFFSET {
254                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
255                                         }
256
257                                         flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
258                                 }
259
260                                 /// Sets the feature's optional (odd) bit in the given flags.
261                                 #[inline]
262                                 fn set_optional_bit(flags: &mut Vec<u8>) {
263                                         if flags.len() <= Self::BYTE_OFFSET {
264                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
265                                         }
266
267                                         flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
268                                 }
269
270                                 /// Clears the feature's required (even) and optional (odd) bits from the given
271                                 /// flags.
272                                 #[inline]
273                                 fn clear_bits(flags: &mut Vec<u8>) {
274                                         if flags.len() > Self::BYTE_OFFSET {
275                                                 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
276                                                 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
277                                         }
278
279                                         let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
280                                         let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
281                                         flags.resize(size, 0u8);
282                                 }
283                         }
284
285                         impl <T: $feature> Features<T> {
286                                 /// Set this feature as optional.
287                                 pub fn $optional_setter(mut self) -> Self {
288                                         <T as $feature>::set_optional_bit(&mut self.flags);
289                                         self
290                                 }
291
292                                 /// Set this feature as required.
293                                 pub fn $required_setter(mut self) -> Self {
294                                         <T as $feature>::set_required_bit(&mut self.flags);
295                                         self
296                                 }
297                         }
298
299                         $(
300                                 impl $feature for $context {
301                                         // EVEN_BIT % 2 == 0
302                                         const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
303
304                                         // ODD_BIT % 2 == 1
305                                         const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
306                                 }
307                         )*
308
309                 }
310         }
311
312         define_feature!(1, DataLossProtect, [InitContext, NodeContext],
313                 "Feature flags for `option_data_loss_protect`.", set_data_loss_protect_optional,
314                 set_data_loss_protect_required);
315         // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
316         define_feature!(3, InitialRoutingSync, [InitContext], "Feature flags for `initial_routing_sync`.",
317                 set_initial_routing_sync_optional, set_initial_routing_sync_required);
318         define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
319                 "Feature flags for `option_upfront_shutdown_script`.", set_upfront_shutdown_script_optional,
320                 set_upfront_shutdown_script_required);
321         define_feature!(7, GossipQueries, [InitContext, NodeContext],
322                 "Feature flags for `gossip_queries`.", set_gossip_queries_optional, set_gossip_queries_required);
323         define_feature!(9, VariableLengthOnion, [InitContext, NodeContext, InvoiceContext],
324                 "Feature flags for `var_onion_optin`.", set_variable_length_onion_optional,
325                 set_variable_length_onion_required);
326         define_feature!(13, StaticRemoteKey, [InitContext, NodeContext],
327                 "Feature flags for `option_static_remotekey`.", set_static_remote_key_optional,
328                 set_static_remote_key_required);
329         define_feature!(15, PaymentSecret, [InitContext, NodeContext, InvoiceContext],
330                 "Feature flags for `payment_secret`.", set_payment_secret_optional, set_payment_secret_required);
331         define_feature!(17, BasicMPP, [InitContext, NodeContext, InvoiceContext],
332                 "Feature flags for `basic_mpp`.", set_basic_mpp_optional, set_basic_mpp_required);
333         define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
334                 "Feature flags for `opt_shutdown_anysegwit`.", set_shutdown_any_segwit_optional,
335                 set_shutdown_any_segwit_required);
336         define_feature!(55, Keysend, [NodeContext],
337                 "Feature flags for keysend payments.", set_keysend_optional, set_keysend_required);
338
339         #[cfg(test)]
340         define_feature!(123456789, UnknownFeature, [NodeContext, ChannelContext, InvoiceContext],
341                 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
342                 set_unknown_feature_required);
343 }
344
345 /// Tracks the set of features which a node implements, templated by the context in which it
346 /// appears.
347 ///
348 /// (C-not exported) as we map the concrete feature types below directly instead
349 #[derive(Eq)]
350 pub struct Features<T: sealed::Context> {
351         /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
352         flags: Vec<u8>,
353         mark: PhantomData<T>,
354 }
355
356 impl<T: sealed::Context> Clone for Features<T> {
357         fn clone(&self) -> Self {
358                 Self {
359                         flags: self.flags.clone(),
360                         mark: PhantomData,
361                 }
362         }
363 }
364 impl<T: sealed::Context> PartialEq for Features<T> {
365         fn eq(&self, o: &Self) -> bool {
366                 self.flags.eq(&o.flags)
367         }
368 }
369 impl<T: sealed::Context> fmt::Debug for Features<T> {
370         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
371                 self.flags.fmt(fmt)
372         }
373 }
374
375 /// Features used within an `init` message.
376 pub type InitFeatures = Features<sealed::InitContext>;
377 /// Features used within a `node_announcement` message.
378 pub type NodeFeatures = Features<sealed::NodeContext>;
379 /// Features used within a `channel_announcement` message.
380 pub type ChannelFeatures = Features<sealed::ChannelContext>;
381 /// Features used within an invoice.
382 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
383
384 impl InitFeatures {
385         /// Writes all features present up to, and including, 13.
386         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
387                 let len = cmp::min(2, self.flags.len());
388                 w.size_hint(len + 2);
389                 (len as u16).write(w)?;
390                 for i in (0..len).rev() {
391                         if i == 0 {
392                                 self.flags[i].write(w)?;
393                         } else {
394                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
395                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
396                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
397                         }
398                 }
399                 Ok(())
400         }
401
402         /// or's another InitFeatures into this one.
403         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
404                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
405                 self.flags.resize(total_feature_len, 0u8);
406                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
407                         *byte |= *o_byte;
408                 }
409                 self
410         }
411
412         /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
413         /// are included in the result.
414         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
415                 self.to_context_internal()
416         }
417 }
418
419 impl InvoiceFeatures {
420         /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
421         /// context `C` are included in the result.
422         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
423                 self.to_context_internal()
424         }
425
426         /// Getting a route for a keysend payment to a private node requires providing the payee's
427         /// features (since they were not announced in a node announcement). However, keysend payments
428         /// don't have an invoice to pull the payee's features from, so this method is provided for use in
429         /// [`get_keysend_route`], thus omitting the need for payers to manually construct an
430         /// `InvoiceFeatures` for [`get_route`].
431         ///
432         /// [`get_keysend_route`]: crate::routing::router::get_keysend_route
433         /// [`get_route`]: crate::routing::router::get_route
434         pub(crate) fn for_keysend() -> InvoiceFeatures {
435                 InvoiceFeatures::empty().set_variable_length_onion_optional()
436         }
437 }
438
439 impl ToBase32 for InvoiceFeatures {
440         fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
441                 // Explanation for the "4": the normal way to round up when dividing is to add the divisor
442                 // minus one before dividing
443                 let length_u5s = (self.flags.len() * 8 + 4) / 5 as usize;
444                 let mut res_u5s: Vec<u5> = vec![u5::try_from_u8(0).unwrap(); length_u5s];
445                 for (byte_idx, byte) in self.flags.iter().enumerate() {
446                         let bit_pos_from_left_0_indexed = byte_idx * 8;
447                         let new_u5_idx = length_u5s - (bit_pos_from_left_0_indexed / 5) as usize - 1;
448                         let new_bit_pos = bit_pos_from_left_0_indexed % 5;
449                         let shifted_chunk_u16 = (*byte as u16) << new_bit_pos;
450                         let curr_u5_as_u8 = res_u5s[new_u5_idx].to_u8();
451                         res_u5s[new_u5_idx] = u5::try_from_u8(curr_u5_as_u8 | ((shifted_chunk_u16 & 0x001f) as u8)).unwrap();
452                         if new_u5_idx > 0 {
453                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 1].to_u8();
454                                 res_u5s[new_u5_idx - 1] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 5) & 0x001f) as u8)).unwrap();
455                         }
456                         if new_u5_idx > 1 {
457                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 2].to_u8();
458                                 res_u5s[new_u5_idx - 2] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 10) & 0x001f) as u8)).unwrap();
459                         }
460                 }
461                 // Trim the highest feature bits.
462                 while !res_u5s.is_empty() && res_u5s[0] == u5::try_from_u8(0).unwrap() {
463                         res_u5s.remove(0);
464                 }
465                 writer.write(&res_u5s)
466         }
467 }
468
469 impl Base32Len for InvoiceFeatures {
470         fn base32_len(&self) -> usize {
471                 self.to_base32().len()
472         }
473 }
474
475 impl FromBase32 for InvoiceFeatures {
476         type Err = bech32::Error;
477
478         fn from_base32(field_data: &[u5]) -> Result<InvoiceFeatures, bech32::Error> {
479                 // Explanation for the "7": the normal way to round up when dividing is to add the divisor
480                 // minus one before dividing
481                 let length_bytes = (field_data.len() * 5 + 7) / 8 as usize;
482                 let mut res_bytes: Vec<u8> = vec![0; length_bytes];
483                 for (u5_idx, chunk) in field_data.iter().enumerate() {
484                         let bit_pos_from_right_0_indexed = (field_data.len() - u5_idx - 1) * 5;
485                         let new_byte_idx = (bit_pos_from_right_0_indexed / 8) as usize;
486                         let new_bit_pos = bit_pos_from_right_0_indexed % 8;
487                         let chunk_u16 = chunk.to_u8() as u16;
488                         res_bytes[new_byte_idx] |= ((chunk_u16 << new_bit_pos) & 0xff) as u8;
489                         if new_byte_idx != length_bytes - 1 {
490                                 res_bytes[new_byte_idx + 1] |= ((chunk_u16 >> (8-new_bit_pos)) & 0xff) as u8;
491                         }
492                 }
493                 // Trim the highest feature bits.
494                 while !res_bytes.is_empty() && res_bytes[res_bytes.len() - 1] == 0 {
495                         res_bytes.pop();
496                 }
497                 Ok(InvoiceFeatures::from_le_bytes(res_bytes))
498         }
499 }
500
501 impl<T: sealed::Context> Features<T> {
502         /// Create a blank Features with no features set
503         pub fn empty() -> Self {
504                 Features {
505                         flags: Vec::new(),
506                         mark: PhantomData,
507                 }
508         }
509
510         /// Creates a Features with the bits set which are known by the implementation
511         pub fn known() -> Self {
512                 Self {
513                         flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
514                         mark: PhantomData,
515                 }
516         }
517
518         /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
519         /// included in the result.
520         fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
521                 let from_byte_count = T::KNOWN_FEATURE_MASK.len();
522                 let to_byte_count = C::KNOWN_FEATURE_MASK.len();
523                 let mut flags = Vec::new();
524                 for (i, byte) in self.flags.iter().enumerate() {
525                         if i < from_byte_count && i < to_byte_count {
526                                 let from_known_features = T::KNOWN_FEATURE_MASK[i];
527                                 let to_known_features = C::KNOWN_FEATURE_MASK[i];
528                                 flags.push(byte & from_known_features & to_known_features);
529                         }
530                 }
531                 Features::<C> { flags, mark: PhantomData, }
532         }
533
534         /// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
535         /// most on-the-wire encodings.
536         /// (C-not exported) as we don't support export across multiple T
537         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
538                 Features {
539                         flags,
540                         mark: PhantomData,
541                 }
542         }
543
544         #[cfg(test)]
545         /// Gets the underlying flags set, in LE.
546         pub fn le_flags(&self) -> &Vec<u8> {
547                 &self.flags
548         }
549
550         pub(crate) fn requires_unknown_bits(&self) -> bool {
551                 // Bitwise AND-ing with all even bits set except for known features will select required
552                 // unknown features.
553                 let byte_count = T::KNOWN_FEATURE_MASK.len();
554                 self.flags.iter().enumerate().any(|(i, &byte)| {
555                         let required_features = 0b01_01_01_01;
556                         let unknown_features = if i < byte_count {
557                                 !T::KNOWN_FEATURE_MASK[i]
558                         } else {
559                                 0b11_11_11_11
560                         };
561                         (byte & (required_features & unknown_features)) != 0
562                 })
563         }
564
565         pub(crate) fn supports_unknown_bits(&self) -> bool {
566                 // Bitwise AND-ing with all even and odd bits set except for known features will select
567                 // both required and optional unknown features.
568                 let byte_count = T::KNOWN_FEATURE_MASK.len();
569                 self.flags.iter().enumerate().any(|(i, &byte)| {
570                         let unknown_features = if i < byte_count {
571                                 !T::KNOWN_FEATURE_MASK[i]
572                         } else {
573                                 0b11_11_11_11
574                         };
575                         (byte & unknown_features) != 0
576                 })
577         }
578
579         /// The number of bytes required to represent the feature flags present. This does not include
580         /// the length bytes which are included in the serialized form.
581         pub(crate) fn byte_count(&self) -> usize {
582                 self.flags.len()
583         }
584 }
585
586 impl<T: sealed::DataLossProtect> Features<T> {
587         #[cfg(test)]
588         pub(crate) fn requires_data_loss_protect(&self) -> bool {
589                 <T as sealed::DataLossProtect>::requires_feature(&self.flags)
590         }
591         #[cfg(test)]
592         pub(crate) fn supports_data_loss_protect(&self) -> bool {
593                 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
594         }
595 }
596
597 impl<T: sealed::UpfrontShutdownScript> Features<T> {
598         #[cfg(test)]
599         pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
600                 <T as sealed::UpfrontShutdownScript>::requires_feature(&self.flags)
601         }
602         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
603                 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
604         }
605         #[cfg(test)]
606         pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
607                 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
608                 self
609         }
610 }
611
612
613 impl<T: sealed::GossipQueries> Features<T> {
614         #[cfg(test)]
615         pub(crate) fn requires_gossip_queries(&self) -> bool {
616                 <T as sealed::GossipQueries>::requires_feature(&self.flags)
617         }
618         pub(crate) fn supports_gossip_queries(&self) -> bool {
619                 <T as sealed::GossipQueries>::supports_feature(&self.flags)
620         }
621         #[cfg(test)]
622         pub(crate) fn clear_gossip_queries(mut self) -> Self {
623                 <T as sealed::GossipQueries>::clear_bits(&mut self.flags);
624                 self
625         }
626 }
627
628 impl<T: sealed::VariableLengthOnion> Features<T> {
629         #[cfg(test)]
630         pub(crate) fn requires_variable_length_onion(&self) -> bool {
631                 <T as sealed::VariableLengthOnion>::requires_feature(&self.flags)
632         }
633         pub(crate) fn supports_variable_length_onion(&self) -> bool {
634                 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
635         }
636 }
637
638 impl<T: sealed::StaticRemoteKey> Features<T> {
639         pub(crate) fn supports_static_remote_key(&self) -> bool {
640                 <T as sealed::StaticRemoteKey>::supports_feature(&self.flags)
641         }
642         #[cfg(test)]
643         pub(crate) fn requires_static_remote_key(&self) -> bool {
644                 <T as sealed::StaticRemoteKey>::requires_feature(&self.flags)
645         }
646 }
647
648 impl<T: sealed::InitialRoutingSync> Features<T> {
649         pub(crate) fn initial_routing_sync(&self) -> bool {
650                 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
651         }
652         // We are no longer setting initial_routing_sync now that gossip_queries
653         // is enabled. This feature is ignored by a peer when gossip_queries has 
654         // been negotiated.
655         #[cfg(test)]
656         pub(crate) fn clear_initial_routing_sync(&mut self) {
657                 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
658         }
659 }
660
661 impl<T: sealed::PaymentSecret> Features<T> {
662         #[cfg(test)]
663         pub(crate) fn requires_payment_secret(&self) -> bool {
664                 <T as sealed::PaymentSecret>::requires_feature(&self.flags)
665         }
666         /// Returns whether the `payment_secret` feature is supported.
667         pub fn supports_payment_secret(&self) -> bool {
668                 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
669         }
670 }
671
672 impl<T: sealed::BasicMPP> Features<T> {
673         #[cfg(test)]
674         pub(crate) fn requires_basic_mpp(&self) -> bool {
675                 <T as sealed::BasicMPP>::requires_feature(&self.flags)
676         }
677         // We currently never test for this since we don't actually *generate* multipath routes.
678         pub(crate) fn supports_basic_mpp(&self) -> bool {
679                 <T as sealed::BasicMPP>::supports_feature(&self.flags)
680         }
681 }
682
683 impl<T: sealed::ShutdownAnySegwit> Features<T> {
684         pub(crate) fn supports_shutdown_anysegwit(&self) -> bool {
685                 <T as sealed::ShutdownAnySegwit>::supports_feature(&self.flags)
686         }
687         #[cfg(test)]
688         pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
689                 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
690                 self
691         }
692 }
693
694 impl<T: sealed::Context> Writeable for Features<T> {
695         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
696                 w.size_hint(self.flags.len() + 2);
697                 (self.flags.len() as u16).write(w)?;
698                 for f in self.flags.iter().rev() { // Swap back to big-endian
699                         f.write(w)?;
700                 }
701                 Ok(())
702         }
703 }
704
705 impl<T: sealed::Context> Readable for Features<T> {
706         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
707                 let mut flags: Vec<u8> = Readable::read(r)?;
708                 flags.reverse(); // Swap to little-endian
709                 Ok(Self {
710                         flags,
711                         mark: PhantomData,
712                 })
713         }
714 }
715
716 #[cfg(test)]
717 mod tests {
718         use super::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
719         use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5};
720
721         #[test]
722         fn sanity_test_known_features() {
723                 assert!(!ChannelFeatures::known().requires_unknown_bits());
724                 assert!(!ChannelFeatures::known().supports_unknown_bits());
725                 assert!(!InitFeatures::known().requires_unknown_bits());
726                 assert!(!InitFeatures::known().supports_unknown_bits());
727                 assert!(!NodeFeatures::known().requires_unknown_bits());
728                 assert!(!NodeFeatures::known().supports_unknown_bits());
729
730                 assert!(InitFeatures::known().supports_upfront_shutdown_script());
731                 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
732                 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
733                 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
734
735                 assert!(InitFeatures::known().supports_gossip_queries());
736                 assert!(NodeFeatures::known().supports_gossip_queries());
737                 assert!(!InitFeatures::known().requires_gossip_queries());
738                 assert!(!NodeFeatures::known().requires_gossip_queries());
739
740                 assert!(InitFeatures::known().supports_data_loss_protect());
741                 assert!(NodeFeatures::known().supports_data_loss_protect());
742                 assert!(!InitFeatures::known().requires_data_loss_protect());
743                 assert!(!NodeFeatures::known().requires_data_loss_protect());
744
745                 assert!(InitFeatures::known().supports_variable_length_onion());
746                 assert!(NodeFeatures::known().supports_variable_length_onion());
747                 assert!(InvoiceFeatures::known().supports_variable_length_onion());
748                 assert!(InitFeatures::known().requires_variable_length_onion());
749                 assert!(NodeFeatures::known().requires_variable_length_onion());
750                 assert!(InvoiceFeatures::known().requires_variable_length_onion());
751
752                 assert!(InitFeatures::known().supports_static_remote_key());
753                 assert!(NodeFeatures::known().supports_static_remote_key());
754                 assert!(InitFeatures::known().requires_static_remote_key());
755                 assert!(NodeFeatures::known().requires_static_remote_key());
756
757                 assert!(InitFeatures::known().supports_payment_secret());
758                 assert!(NodeFeatures::known().supports_payment_secret());
759                 assert!(InvoiceFeatures::known().supports_payment_secret());
760                 assert!(InitFeatures::known().requires_payment_secret());
761                 assert!(NodeFeatures::known().requires_payment_secret());
762                 assert!(InvoiceFeatures::known().requires_payment_secret());
763
764                 assert!(InitFeatures::known().supports_basic_mpp());
765                 assert!(NodeFeatures::known().supports_basic_mpp());
766                 assert!(InvoiceFeatures::known().supports_basic_mpp());
767                 assert!(!InitFeatures::known().requires_basic_mpp());
768                 assert!(!NodeFeatures::known().requires_basic_mpp());
769                 assert!(!InvoiceFeatures::known().requires_basic_mpp());
770
771                 assert!(InitFeatures::known().supports_shutdown_anysegwit());
772                 assert!(NodeFeatures::known().supports_shutdown_anysegwit());
773
774                 let mut init_features = InitFeatures::known();
775                 assert!(init_features.initial_routing_sync());
776                 init_features.clear_initial_routing_sync();
777                 assert!(!init_features.initial_routing_sync());
778         }
779
780         #[test]
781         fn sanity_test_unknown_bits() {
782                 let features = ChannelFeatures::empty();
783                 assert!(!features.requires_unknown_bits());
784                 assert!(!features.supports_unknown_bits());
785
786                 let features = ChannelFeatures::empty().set_unknown_feature_required();
787                 assert!(features.requires_unknown_bits());
788                 assert!(features.supports_unknown_bits());
789
790                 let features = ChannelFeatures::empty().set_unknown_feature_optional();
791                 assert!(!features.requires_unknown_bits());
792                 assert!(features.supports_unknown_bits());
793         }
794
795         #[test]
796         fn convert_to_context_with_relevant_flags() {
797                 let init_features = InitFeatures::known().clear_upfront_shutdown_script().clear_gossip_queries();
798                 assert!(init_features.initial_routing_sync());
799                 assert!(!init_features.supports_upfront_shutdown_script());
800                 assert!(!init_features.supports_gossip_queries());
801
802                 let node_features: NodeFeatures = init_features.to_context();
803                 {
804                         // Check that the flags are as expected:
805                         // - option_data_loss_protect
806                         // - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
807                         // - basic_mpp
808                         // - opt_shutdown_anysegwit
809                         assert_eq!(node_features.flags.len(), 4);
810                         assert_eq!(node_features.flags[0], 0b00000010);
811                         assert_eq!(node_features.flags[1], 0b01010001);
812                         assert_eq!(node_features.flags[2], 0b00000010);
813                         assert_eq!(node_features.flags[3], 0b00001000);
814                 }
815
816                 // Check that cleared flags are kept blank when converting back:
817                 // - initial_routing_sync was not applicable to NodeContext
818                 // - upfront_shutdown_script was cleared before converting
819                 // - gossip_queries was cleared before converting
820                 let features: InitFeatures = node_features.to_context_internal();
821                 assert!(!features.initial_routing_sync());
822                 assert!(!features.supports_upfront_shutdown_script());
823                 assert!(!init_features.supports_gossip_queries());
824         }
825
826         #[test]
827         fn convert_to_context_with_unknown_flags() {
828                 // Ensure the `from` context has fewer known feature bytes than the `to` context.
829                 assert!(InvoiceFeatures::known().byte_count() < NodeFeatures::known().byte_count());
830                 let invoice_features = InvoiceFeatures::known().set_unknown_feature_optional();
831                 assert!(invoice_features.supports_unknown_bits());
832                 let node_features: NodeFeatures = invoice_features.to_context();
833                 assert!(!node_features.supports_unknown_bits());
834         }
835
836         #[test]
837         fn set_feature_bits() {
838                 let features = InvoiceFeatures::empty()
839                         .set_basic_mpp_optional()
840                         .set_payment_secret_required();
841                 assert!(features.supports_basic_mpp());
842                 assert!(!features.requires_basic_mpp());
843                 assert!(features.requires_payment_secret());
844                 assert!(features.supports_payment_secret());
845         }
846
847         #[test]
848         fn invoice_features_encoding() {
849                 let features_as_u5s = vec![
850                         u5::try_from_u8(6).unwrap(),
851                         u5::try_from_u8(10).unwrap(),
852                         u5::try_from_u8(25).unwrap(),
853                         u5::try_from_u8(1).unwrap(),
854                         u5::try_from_u8(10).unwrap(),
855                         u5::try_from_u8(0).unwrap(),
856                         u5::try_from_u8(20).unwrap(),
857                         u5::try_from_u8(2).unwrap(),
858                         u5::try_from_u8(0).unwrap(),
859                         u5::try_from_u8(6).unwrap(),
860                         u5::try_from_u8(0).unwrap(),
861                         u5::try_from_u8(16).unwrap(),
862                         u5::try_from_u8(1).unwrap(),
863                 ];
864                 let features = InvoiceFeatures::from_le_bytes(vec![1, 2, 3, 4, 5, 42, 100, 101]);
865
866                 // Test length calculation.
867                 assert_eq!(features.base32_len(), 13);
868
869                 // Test serialization.
870                 let features_serialized = features.to_base32();
871                 assert_eq!(features_as_u5s, features_serialized);
872
873                 // Test deserialization.
874                 let features_deserialized = InvoiceFeatures::from_base32(&features_as_u5s).unwrap();
875                 assert_eq!(features, features_deserialized);
876         }
877 }