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