0566a80b3daf5b8c0b613fc3a486629deaf88c83
[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 //! - `OnionMessages` - requires/supports forwarding onion messages
47 //!     (see [BOLT-7](https://github.com/lightning/bolts/pull/759/files) for more information).
48 //!     TODO: update link
49 //! - `ChannelType` - node supports the channel_type field in open/accept
50 //!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
51 //! - `SCIDPrivacy` - supply channel aliases for routing
52 //!     (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information).
53 //! - `Keysend` - send funds to a node without an invoice
54 //!     (see the [`Keysend` feature assignment proposal](https://github.com/lightning/bolts/issues/605#issuecomment-606679798) for more information).
55 //!
56 //! [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md
57 //! [messages]: crate::ln::msgs
58
59 use {io, io_extras};
60 use prelude::*;
61 use core::{cmp, fmt};
62 use core::hash::{Hash, Hasher};
63 use core::marker::PhantomData;
64
65 use bitcoin::bech32;
66 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
67 use ln::msgs::DecodeError;
68 use util::ser::{Readable, Writeable, Writer};
69
70 mod sealed {
71         use prelude::*;
72         use ln::features::Features;
73
74         /// The context in which [`Features`] are applicable. Defines which features are required and
75         /// which are optional for the context.
76         pub trait Context {
77                 /// Features that are known to the implementation, where a required feature is indicated by
78                 /// its even bit and an optional feature is indicated by its odd bit.
79                 const KNOWN_FEATURE_FLAGS: &'static [u8];
80
81                 /// Bitmask for selecting features that are known to the implementation, regardless of
82                 /// whether each feature is required or optional.
83                 const KNOWN_FEATURE_MASK: &'static [u8];
84         }
85
86         /// Defines a [`Context`] by stating which features it requires and which are optional. Features
87         /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
88         /// feature identifiers.
89         macro_rules! define_context {
90                 ($context: ident {
91                         required_features: [$( $( $required_feature: ident )|*, )*],
92                         optional_features: [$( $( $optional_feature: ident )|*, )*],
93                 }) => {
94                         #[derive(Eq, PartialEq)]
95                         pub struct $context {}
96
97                         impl Context for $context {
98                                 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
99                                         // For each byte, use bitwise-OR to compute the applicable flags for known
100                                         // required features `r_i` and optional features `o_j` for all `i` and `j` such
101                                         // that the following slice is formed:
102                                         //
103                                         // [
104                                         //  `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
105                                         //  ...,
106                                         // ]
107                                         $(
108                                                 0b00_00_00_00 $(|
109                                                         <Self as $required_feature>::REQUIRED_MASK)*
110                                                 $(|
111                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
112                                         )*
113                                 ];
114
115                                 const KNOWN_FEATURE_MASK: &'static [u8] = &[
116                                         // Similar as above, but set both flags for each feature regardless of whether
117                                         // the feature is required or optional.
118                                         $(
119                                                 0b00_00_00_00 $(|
120                                                         <Self as $required_feature>::REQUIRED_MASK |
121                                                         <Self as $required_feature>::OPTIONAL_MASK)*
122                                                 $(|
123                                                         <Self as $optional_feature>::REQUIRED_MASK |
124                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
125                                         )*
126                                 ];
127                         }
128
129                         impl alloc::fmt::Display for Features<$context> {
130                                 fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
131                                         $(
132                                                 $(
133                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($required_feature),
134                                                                 if <$context as $required_feature>::requires_feature(&self.flags) { "required" }
135                                                                 else if <$context as $required_feature>::supports_feature(&self.flags) { "supported" }
136                                                                 else { "not supported" }))?;
137                                                 )*
138                                                 $(
139                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($optional_feature),
140                                                                 if <$context as $optional_feature>::requires_feature(&self.flags) { "required" }
141                                                                 else if <$context as $optional_feature>::supports_feature(&self.flags) { "supported" }
142                                                                 else { "not supported" }))?;
143                                                 )*
144                                         )*
145                                         fmt.write_fmt(format_args!("unknown flags: {}",
146                                                 if self.requires_unknown_bits() { "required" }
147                                                 else if self.supports_unknown_bits() { "supported" } else { "none" }))
148                                 }
149                         }
150                 };
151         }
152
153         define_context!(InitContext {
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 | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
173                         // Byte 1
174                         ,
175                         // Byte 2
176                         BasicMPP | Wumbo,
177                         // Byte 3
178                         ShutdownAnySegwit,
179                         // Byte 4
180                         OnionMessages,
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                         OnionMessages,
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         define_feature!(39, OnionMessages, [InitContext, NodeContext],
442                 "Feature flags for `option_onion_messages`.", set_onion_messages_optional,
443                 set_onion_messages_required, supports_onion_messages, requires_onion_messages);
444         define_feature!(45, ChannelType, [InitContext, NodeContext],
445                 "Feature flags for `option_channel_type`.", set_channel_type_optional,
446                 set_channel_type_required, supports_channel_type, requires_channel_type);
447         define_feature!(47, SCIDPrivacy, [InitContext, NodeContext, ChannelTypeContext],
448                 "Feature flags for only forwarding with SCID aliasing. Called `option_scid_alias` in the BOLTs",
449                 set_scid_privacy_optional, set_scid_privacy_required, supports_scid_privacy, requires_scid_privacy);
450         define_feature!(51, ZeroConf, [InitContext, NodeContext, ChannelTypeContext],
451                 "Feature flags for accepting channels with zero confirmations. Called `option_zeroconf` in the BOLTs",
452                 set_zero_conf_optional, set_zero_conf_required, supports_zero_conf, requires_zero_conf);
453         define_feature!(55, Keysend, [NodeContext],
454                 "Feature flags for keysend payments.", set_keysend_optional, set_keysend_required,
455                 supports_keysend, requires_keysend);
456
457         #[cfg(test)]
458         define_feature!(123456789, UnknownFeature, [NodeContext, ChannelContext, InvoiceContext],
459                 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
460                 set_unknown_feature_required, supports_unknown_test_feature, requires_unknown_test_feature);
461 }
462
463 /// Tracks the set of features which a node implements, templated by the context in which it
464 /// appears.
465 ///
466 /// (C-not exported) as we map the concrete feature types below directly instead
467 #[derive(Eq)]
468 pub struct Features<T: sealed::Context> {
469         /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
470         flags: Vec<u8>,
471         mark: PhantomData<T>,
472 }
473
474 impl <T: sealed::Context> Features<T> {
475         pub(crate) fn or(mut self, o: Self) -> Self {
476                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
477                 self.flags.resize(total_feature_len, 0u8);
478                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
479                         *byte |= *o_byte;
480                 }
481                 self
482         }
483 }
484
485 impl<T: sealed::Context> Clone for Features<T> {
486         fn clone(&self) -> Self {
487                 Self {
488                         flags: self.flags.clone(),
489                         mark: PhantomData,
490                 }
491         }
492 }
493 impl<T: sealed::Context> Hash for Features<T> {
494         fn hash<H: Hasher>(&self, hasher: &mut H) {
495                 self.flags.hash(hasher);
496         }
497 }
498 impl<T: sealed::Context> PartialEq for Features<T> {
499         fn eq(&self, o: &Self) -> bool {
500                 self.flags.eq(&o.flags)
501         }
502 }
503 impl<T: sealed::Context> fmt::Debug for Features<T> {
504         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
505                 self.flags.fmt(fmt)
506         }
507 }
508
509 /// Features used within an `init` message.
510 pub type InitFeatures = Features<sealed::InitContext>;
511 /// Features used within a `node_announcement` message.
512 pub type NodeFeatures = Features<sealed::NodeContext>;
513 /// Features used within a `channel_announcement` message.
514 pub type ChannelFeatures = Features<sealed::ChannelContext>;
515 /// Features used within an invoice.
516 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
517
518 /// Features used within the channel_type field in an OpenChannel message.
519 ///
520 /// A channel is always of some known "type", describing the transaction formats used and the exact
521 /// semantics of our interaction with our peer.
522 ///
523 /// Note that because a channel is a specific type which is proposed by the opener and accepted by
524 /// the counterparty, only required features are allowed here.
525 ///
526 /// This is serialized differently from other feature types - it is not prefixed by a length, and
527 /// thus must only appear inside a TLV where its length is known in advance.
528 pub type ChannelTypeFeatures = Features<sealed::ChannelTypeContext>;
529
530 impl InitFeatures {
531         /// Writes all features present up to, and including, 13.
532         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
533                 let len = cmp::min(2, self.flags.len());
534                 (len as u16).write(w)?;
535                 for i in (0..len).rev() {
536                         if i == 0 {
537                                 self.flags[i].write(w)?;
538                         } else {
539                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
540                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
541                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
542                         }
543                 }
544                 Ok(())
545         }
546
547         /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
548         /// are included in the result.
549         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
550                 self.to_context_internal()
551         }
552 }
553
554 impl InvoiceFeatures {
555         /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
556         /// context `C` are included in the result.
557         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
558                 self.to_context_internal()
559         }
560
561         /// Getting a route for a keysend payment to a private node requires providing the payee's
562         /// features (since they were not announced in a node announcement). However, keysend payments
563         /// don't have an invoice to pull the payee's features from, so this method is provided for use in
564         /// [`PaymentParameters::for_keysend`], thus omitting the need for payers to manually construct an
565         /// `InvoiceFeatures` for [`find_route`].
566         ///
567         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
568         /// [`find_route`]: crate::routing::router::find_route
569         pub(crate) fn for_keysend() -> InvoiceFeatures {
570                 let mut res = InvoiceFeatures::empty();
571                 res.set_variable_length_onion_optional();
572                 res
573         }
574 }
575
576 impl ChannelTypeFeatures {
577         /// Constructs the implicit channel type based on the common supported types between us and our
578         /// counterparty
579         pub(crate) fn from_counterparty_init(counterparty_init: &InitFeatures) -> Self {
580                 let mut ret = counterparty_init.to_context_internal();
581                 // ChannelTypeFeatures must only contain required bits, so we OR the required forms of all
582                 // optional bits and then AND out the optional ones.
583                 for byte in ret.flags.iter_mut() {
584                         *byte |= (*byte & 0b10_10_10_10) >> 1;
585                         *byte &= 0b01_01_01_01;
586                 }
587                 ret
588         }
589
590         /// Constructs a ChannelTypeFeatures with only static_remotekey set
591         pub(crate) fn only_static_remote_key() -> Self {
592                 let mut ret = Self::empty();
593                 <sealed::ChannelTypeContext as sealed::StaticRemoteKey>::set_required_bit(&mut ret.flags);
594                 ret
595         }
596 }
597
598 impl ToBase32 for InvoiceFeatures {
599         fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
600                 // Explanation for the "4": the normal way to round up when dividing is to add the divisor
601                 // minus one before dividing
602                 let length_u5s = (self.flags.len() * 8 + 4) / 5 as usize;
603                 let mut res_u5s: Vec<u5> = vec![u5::try_from_u8(0).unwrap(); length_u5s];
604                 for (byte_idx, byte) in self.flags.iter().enumerate() {
605                         let bit_pos_from_left_0_indexed = byte_idx * 8;
606                         let new_u5_idx = length_u5s - (bit_pos_from_left_0_indexed / 5) as usize - 1;
607                         let new_bit_pos = bit_pos_from_left_0_indexed % 5;
608                         let shifted_chunk_u16 = (*byte as u16) << new_bit_pos;
609                         let curr_u5_as_u8 = res_u5s[new_u5_idx].to_u8();
610                         res_u5s[new_u5_idx] = u5::try_from_u8(curr_u5_as_u8 | ((shifted_chunk_u16 & 0x001f) as u8)).unwrap();
611                         if new_u5_idx > 0 {
612                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 1].to_u8();
613                                 res_u5s[new_u5_idx - 1] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 5) & 0x001f) as u8)).unwrap();
614                         }
615                         if new_u5_idx > 1 {
616                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 2].to_u8();
617                                 res_u5s[new_u5_idx - 2] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 10) & 0x001f) as u8)).unwrap();
618                         }
619                 }
620                 // Trim the highest feature bits.
621                 while !res_u5s.is_empty() && res_u5s[0] == u5::try_from_u8(0).unwrap() {
622                         res_u5s.remove(0);
623                 }
624                 writer.write(&res_u5s)
625         }
626 }
627
628 impl Base32Len for InvoiceFeatures {
629         fn base32_len(&self) -> usize {
630                 self.to_base32().len()
631         }
632 }
633
634 impl FromBase32 for InvoiceFeatures {
635         type Err = bech32::Error;
636
637         fn from_base32(field_data: &[u5]) -> Result<InvoiceFeatures, bech32::Error> {
638                 // Explanation for the "7": the normal way to round up when dividing is to add the divisor
639                 // minus one before dividing
640                 let length_bytes = (field_data.len() * 5 + 7) / 8 as usize;
641                 let mut res_bytes: Vec<u8> = vec![0; length_bytes];
642                 for (u5_idx, chunk) in field_data.iter().enumerate() {
643                         let bit_pos_from_right_0_indexed = (field_data.len() - u5_idx - 1) * 5;
644                         let new_byte_idx = (bit_pos_from_right_0_indexed / 8) as usize;
645                         let new_bit_pos = bit_pos_from_right_0_indexed % 8;
646                         let chunk_u16 = chunk.to_u8() as u16;
647                         res_bytes[new_byte_idx] |= ((chunk_u16 << new_bit_pos) & 0xff) as u8;
648                         if new_byte_idx != length_bytes - 1 {
649                                 res_bytes[new_byte_idx + 1] |= ((chunk_u16 >> (8-new_bit_pos)) & 0xff) as u8;
650                         }
651                 }
652                 // Trim the highest feature bits.
653                 while !res_bytes.is_empty() && res_bytes[res_bytes.len() - 1] == 0 {
654                         res_bytes.pop();
655                 }
656                 Ok(InvoiceFeatures::from_le_bytes(res_bytes))
657         }
658 }
659
660 impl<T: sealed::Context> Features<T> {
661         /// Create a blank Features with no features set
662         pub fn empty() -> Self {
663                 Features {
664                         flags: Vec::new(),
665                         mark: PhantomData,
666                 }
667         }
668
669         /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
670         /// included in the result.
671         fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
672                 let from_byte_count = T::KNOWN_FEATURE_MASK.len();
673                 let to_byte_count = C::KNOWN_FEATURE_MASK.len();
674                 let mut flags = Vec::new();
675                 for (i, byte) in self.flags.iter().enumerate() {
676                         if i < from_byte_count && i < to_byte_count {
677                                 let from_known_features = T::KNOWN_FEATURE_MASK[i];
678                                 let to_known_features = C::KNOWN_FEATURE_MASK[i];
679                                 flags.push(byte & from_known_features & to_known_features);
680                         }
681                 }
682                 Features::<C> { flags, mark: PhantomData, }
683         }
684
685         /// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
686         /// most on-the-wire encodings.
687         /// (C-not exported) as we don't support export across multiple T
688         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
689                 Features {
690                         flags,
691                         mark: PhantomData,
692                 }
693         }
694
695         #[cfg(test)]
696         /// Gets the underlying flags set, in LE.
697         pub fn le_flags(&self) -> &Vec<u8> {
698                 &self.flags
699         }
700
701         fn write_be<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
702                 for f in self.flags.iter().rev() { // Swap back to big-endian
703                         f.write(w)?;
704                 }
705                 Ok(())
706         }
707
708         fn from_be_bytes(mut flags: Vec<u8>) -> Features<T> {
709                 flags.reverse(); // Swap to little-endian
710                 Self {
711                         flags,
712                         mark: PhantomData,
713                 }
714         }
715
716         pub(crate) fn supports_any_optional_bits(&self) -> bool {
717                 self.flags.iter().any(|&byte| (byte & 0b10_10_10_10) != 0)
718         }
719
720         /// Returns true if this `Features` object contains unknown feature flags which are set as
721         /// "required".
722         pub fn requires_unknown_bits(&self) -> bool {
723                 // Bitwise AND-ing with all even bits set except for known features will select required
724                 // unknown features.
725                 let byte_count = T::KNOWN_FEATURE_MASK.len();
726                 self.flags.iter().enumerate().any(|(i, &byte)| {
727                         let required_features = 0b01_01_01_01;
728                         let unknown_features = if i < byte_count {
729                                 !T::KNOWN_FEATURE_MASK[i]
730                         } else {
731                                 0b11_11_11_11
732                         };
733                         (byte & (required_features & unknown_features)) != 0
734                 })
735         }
736
737         pub(crate) fn supports_unknown_bits(&self) -> bool {
738                 // Bitwise AND-ing with all even and odd bits set except for known features will select
739                 // both required and optional unknown features.
740                 let byte_count = T::KNOWN_FEATURE_MASK.len();
741                 self.flags.iter().enumerate().any(|(i, &byte)| {
742                         let unknown_features = if i < byte_count {
743                                 !T::KNOWN_FEATURE_MASK[i]
744                         } else {
745                                 0b11_11_11_11
746                         };
747                         (byte & unknown_features) != 0
748                 })
749         }
750 }
751
752 impl<T: sealed::UpfrontShutdownScript> Features<T> {
753         #[cfg(test)]
754         pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
755                 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
756                 self
757         }
758 }
759
760 impl<T: sealed::ShutdownAnySegwit> Features<T> {
761         #[cfg(test)]
762         pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
763                 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
764                 self
765         }
766 }
767
768 impl<T: sealed::Wumbo> Features<T> {
769         #[cfg(test)]
770         pub(crate) fn clear_wumbo(mut self) -> Self {
771                 <T as sealed::Wumbo>::clear_bits(&mut self.flags);
772                 self
773         }
774 }
775
776 macro_rules! impl_feature_len_prefixed_write {
777         ($features: ident) => {
778                 impl Writeable for $features {
779                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
780                                 (self.flags.len() as u16).write(w)?;
781                                 self.write_be(w)
782                         }
783                 }
784                 impl Readable for $features {
785                         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
786                                 Ok(Self::from_be_bytes(Vec::<u8>::read(r)?))
787                         }
788                 }
789         }
790 }
791 impl_feature_len_prefixed_write!(InitFeatures);
792 impl_feature_len_prefixed_write!(ChannelFeatures);
793 impl_feature_len_prefixed_write!(NodeFeatures);
794 impl_feature_len_prefixed_write!(InvoiceFeatures);
795
796 // Because ChannelTypeFeatures only appears inside of TLVs, it doesn't have a length prefix when
797 // serialized. Thus, we can't use `impl_feature_len_prefixed_write`, above, and have to write our
798 // own serialization.
799 impl Writeable for ChannelTypeFeatures {
800         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
801                 self.write_be(w)
802         }
803 }
804 impl Readable for ChannelTypeFeatures {
805         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
806                 let v = io_extras::read_to_end(r)?;
807                 Ok(Self::from_be_bytes(v))
808         }
809 }
810
811 #[cfg(test)]
812 mod tests {
813         use super::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, InvoiceFeatures, NodeFeatures, sealed};
814         use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5};
815
816         #[test]
817         fn sanity_test_unknown_bits() {
818                 let features = ChannelFeatures::empty();
819                 assert!(!features.requires_unknown_bits());
820                 assert!(!features.supports_unknown_bits());
821
822                 let mut features = ChannelFeatures::empty();
823                 features.set_unknown_feature_required();
824                 assert!(features.requires_unknown_bits());
825                 assert!(features.supports_unknown_bits());
826
827                 let mut features = ChannelFeatures::empty();
828                 features.set_unknown_feature_optional();
829                 assert!(!features.requires_unknown_bits());
830                 assert!(features.supports_unknown_bits());
831         }
832
833         #[test]
834         fn convert_to_context_with_relevant_flags() {
835                 let mut init_features = InitFeatures::empty();
836                 // Set a bunch of features we use, plus initial_routing_sync_required (which shouldn't get
837                 // converted as it's only relevant in an init context).
838                 init_features.set_initial_routing_sync_required();
839                 init_features.set_data_loss_protect_optional();
840                 init_features.set_variable_length_onion_required();
841                 init_features.set_static_remote_key_required();
842                 init_features.set_payment_secret_required();
843                 init_features.set_basic_mpp_optional();
844                 init_features.set_wumbo_optional();
845                 init_features.set_shutdown_any_segwit_optional();
846                 init_features.set_onion_messages_optional();
847                 init_features.set_channel_type_optional();
848                 init_features.set_scid_privacy_optional();
849                 init_features.set_zero_conf_optional();
850
851                 assert!(init_features.initial_routing_sync());
852                 assert!(!init_features.supports_upfront_shutdown_script());
853                 assert!(!init_features.supports_gossip_queries());
854
855                 let node_features: NodeFeatures = init_features.to_context();
856                 {
857                         // Check that the flags are as expected:
858                         // - option_data_loss_protect
859                         // - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
860                         // - basic_mpp | wumbo
861                         // - opt_shutdown_anysegwit
862                         // - onion_messages
863                         // - option_channel_type | option_scid_alias
864                         // - option_zeroconf
865                         assert_eq!(node_features.flags.len(), 7);
866                         assert_eq!(node_features.flags[0], 0b00000010);
867                         assert_eq!(node_features.flags[1], 0b01010001);
868                         assert_eq!(node_features.flags[2], 0b00001010);
869                         assert_eq!(node_features.flags[3], 0b00001000);
870                         assert_eq!(node_features.flags[4], 0b10000000);
871                         assert_eq!(node_features.flags[5], 0b10100000);
872                         assert_eq!(node_features.flags[6], 0b00001000);
873                 }
874
875                 // Check that cleared flags are kept blank when converting back:
876                 // - initial_routing_sync was not applicable to NodeContext
877                 // - upfront_shutdown_script was cleared before converting
878                 // - gossip_queries was cleared before converting
879                 let features: InitFeatures = node_features.to_context_internal();
880                 assert!(!features.initial_routing_sync());
881                 assert!(!features.supports_upfront_shutdown_script());
882                 assert!(!init_features.supports_gossip_queries());
883         }
884
885         #[test]
886         fn convert_to_context_with_unknown_flags() {
887                 // Ensure the `from` context has fewer known feature bytes than the `to` context.
888                 assert!(<sealed::InvoiceContext as sealed::Context>::KNOWN_FEATURE_MASK.len() <
889                         <sealed::NodeContext as sealed::Context>::KNOWN_FEATURE_MASK.len());
890                 let mut invoice_features = InvoiceFeatures::empty();
891                 invoice_features.set_unknown_feature_optional();
892                 assert!(invoice_features.supports_unknown_bits());
893                 let node_features: NodeFeatures = invoice_features.to_context();
894                 assert!(!node_features.supports_unknown_bits());
895         }
896
897         #[test]
898         fn set_feature_bits() {
899                 let mut features = InvoiceFeatures::empty();
900                 features.set_basic_mpp_optional();
901                 features.set_payment_secret_required();
902                 assert!(features.supports_basic_mpp());
903                 assert!(!features.requires_basic_mpp());
904                 assert!(features.requires_payment_secret());
905                 assert!(features.supports_payment_secret());
906         }
907
908         #[test]
909         fn invoice_features_encoding() {
910                 let features_as_u5s = vec![
911                         u5::try_from_u8(6).unwrap(),
912                         u5::try_from_u8(10).unwrap(),
913                         u5::try_from_u8(25).unwrap(),
914                         u5::try_from_u8(1).unwrap(),
915                         u5::try_from_u8(10).unwrap(),
916                         u5::try_from_u8(0).unwrap(),
917                         u5::try_from_u8(20).unwrap(),
918                         u5::try_from_u8(2).unwrap(),
919                         u5::try_from_u8(0).unwrap(),
920                         u5::try_from_u8(6).unwrap(),
921                         u5::try_from_u8(0).unwrap(),
922                         u5::try_from_u8(16).unwrap(),
923                         u5::try_from_u8(1).unwrap(),
924                 ];
925                 let features = InvoiceFeatures::from_le_bytes(vec![1, 2, 3, 4, 5, 42, 100, 101]);
926
927                 // Test length calculation.
928                 assert_eq!(features.base32_len(), 13);
929
930                 // Test serialization.
931                 let features_serialized = features.to_base32();
932                 assert_eq!(features_as_u5s, features_serialized);
933
934                 // Test deserialization.
935                 let features_deserialized = InvoiceFeatures::from_base32(&features_as_u5s).unwrap();
936                 assert_eq!(features, features_deserialized);
937         }
938
939         #[test]
940         fn test_channel_type_mapping() {
941                 // If we map an InvoiceFeatures with StaticRemoteKey optional, it should map into a
942                 // required-StaticRemoteKey ChannelTypeFeatures.
943                 let mut init_features = InitFeatures::empty();
944                 init_features.set_static_remote_key_optional();
945                 let converted_features = ChannelTypeFeatures::from_counterparty_init(&init_features);
946                 assert_eq!(converted_features, ChannelTypeFeatures::only_static_remote_key());
947                 assert!(!converted_features.supports_any_optional_bits());
948                 assert!(converted_features.requires_static_remote_key());
949         }
950 }