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