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