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