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