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