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