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