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