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