Implement core::hash::Hash more incl invoice::RawTaggedField
[rust-lightning] / lightning / src / ln / features.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Feature flag definitions for the Lightning protocol according to [BOLT #9].
11 //!
12 //! Lightning nodes advertise a supported set of operation through feature flags. Features are
13 //! applicable for a specific context as indicated in some [messages]. [`Features`] encapsulates
14 //! behavior for specifying and checking feature flags for a particular context. Each feature is
15 //! defined internally by a trait specifying the corresponding flags (i.e., even and odd bits).
16 //!
17 //! Whether a feature is considered "known" or "unknown" is relative to the implementation, whereas
18 //! the term "supports" is used in reference to a particular set of [`Features`]. That is, a node
19 //! supports a feature if it advertises the feature (as either required or optional) to its peers.
20 //! And the implementation can interpret a feature if the feature is known to it.
21 //!
22 //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
23 //! [messages]: crate::ln::msgs
24
25 use io;
26 use prelude::*;
27 use core::{cmp, fmt};
28 use core::hash::{Hash, Hasher};
29 use core::marker::PhantomData;
30
31 use bitcoin::bech32;
32 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32};
33 use ln::msgs::DecodeError;
34 use util::ser::{Readable, Writeable, Writer};
35
36 mod sealed {
37         use prelude::*;
38         use ln::features::Features;
39
40         /// The context in which [`Features`] are applicable. Defines which features are required and
41         /// which are optional for the context.
42         pub trait Context {
43                 /// Features that are known to the implementation, where a required feature is indicated by
44                 /// its even bit and an optional feature is indicated by its odd bit.
45                 const KNOWN_FEATURE_FLAGS: &'static [u8];
46
47                 /// Bitmask for selecting features that are known to the implementation, regardless of
48                 /// whether each feature is required or optional.
49                 const KNOWN_FEATURE_MASK: &'static [u8];
50         }
51
52         /// Defines a [`Context`] by stating which features it requires and which are optional. Features
53         /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
54         /// feature identifiers.
55         macro_rules! define_context {
56                 ($context: ident {
57                         required_features: [$( $( $required_feature: ident )|*, )*],
58                         optional_features: [$( $( $optional_feature: ident )|*, )*],
59                 }) => {
60                         #[derive(Eq, PartialEq)]
61                         pub struct $context {}
62
63                         impl Context for $context {
64                                 const KNOWN_FEATURE_FLAGS: &'static [u8] = &[
65                                         // For each byte, use bitwise-OR to compute the applicable flags for known
66                                         // required features `r_i` and optional features `o_j` for all `i` and `j` such
67                                         // that the following slice is formed:
68                                         //
69                                         // [
70                                         //  `r_0` | `r_1` | ... | `o_0` | `o_1` | ...,
71                                         //  ...,
72                                         // ]
73                                         $(
74                                                 0b00_00_00_00 $(|
75                                                         <Self as $required_feature>::REQUIRED_MASK)*
76                                                 $(|
77                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
78                                         )*
79                                 ];
80
81                                 const KNOWN_FEATURE_MASK: &'static [u8] = &[
82                                         // Similar as above, but set both flags for each feature regardless of whether
83                                         // the feature is required or optional.
84                                         $(
85                                                 0b00_00_00_00 $(|
86                                                         <Self as $required_feature>::REQUIRED_MASK |
87                                                         <Self as $required_feature>::OPTIONAL_MASK)*
88                                                 $(|
89                                                         <Self as $optional_feature>::REQUIRED_MASK |
90                                                         <Self as $optional_feature>::OPTIONAL_MASK)*,
91                                         )*
92                                 ];
93                         }
94
95                         impl alloc::fmt::Display for Features<$context> {
96                                 fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> {
97                                         $(
98                                                 $(
99                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($required_feature),
100                                                                 if <$context as $required_feature>::requires_feature(&self.flags) { "required" }
101                                                                 else if <$context as $required_feature>::supports_feature(&self.flags) { "supported" }
102                                                                 else { "not supported" }))?;
103                                                 )*
104                                                 $(
105                                                         fmt.write_fmt(format_args!("{}: {}, ", stringify!($optional_feature),
106                                                                 if <$context as $optional_feature>::requires_feature(&self.flags) { "required" }
107                                                                 else if <$context as $optional_feature>::supports_feature(&self.flags) { "supported" }
108                                                                 else { "not supported" }))?;
109                                                 )*
110                                         )*
111                                         fmt.write_fmt(format_args!("unknown flags: {}",
112                                                 if self.requires_unknown_bits() { "required" }
113                                                 else if self.supports_unknown_bits() { "supported" } else { "none" }))
114                                 }
115                         }
116                 };
117         }
118
119         define_context!(InitContext {
120                 required_features: [
121                         // Byte 0
122                         ,
123                         // Byte 1
124                         VariableLengthOnion | StaticRemoteKey | PaymentSecret,
125                         // Byte 2
126                         ,
127                         // Byte 3
128                         ,
129                 ],
130                 optional_features: [
131                         // Byte 0
132                         DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
133                         // Byte 1
134                         ,
135                         // Byte 2
136                         BasicMPP,
137                         // Byte 3
138                         ShutdownAnySegwit,
139                 ],
140         });
141         define_context!(NodeContext {
142                 required_features: [
143                         // Byte 0
144                         ,
145                         // Byte 1
146                         VariableLengthOnion | StaticRemoteKey | PaymentSecret,
147                         // Byte 2
148                         ,
149                         // Byte 3
150                         ,
151                         // Byte 4
152                         ,
153                         // Byte 5
154                         ,
155                         // Byte 6
156                         ,
157                 ],
158                 optional_features: [
159                         // Byte 0
160                         DataLossProtect | UpfrontShutdownScript | GossipQueries,
161                         // Byte 1
162                         ,
163                         // Byte 2
164                         BasicMPP,
165                         // Byte 3
166                         ShutdownAnySegwit,
167                         // Byte 4
168                         ,
169                         // Byte 5
170                         ,
171                         // Byte 6
172                         Keysend,
173                 ],
174         });
175         define_context!(ChannelContext {
176                 required_features: [],
177                 optional_features: [],
178         });
179         define_context!(InvoiceContext {
180                 required_features: [
181                         // Byte 0
182                         ,
183                         // Byte 1
184                         VariableLengthOnion | PaymentSecret,
185                         // Byte 2
186                         ,
187                 ],
188                 optional_features: [
189                         // Byte 0
190                         ,
191                         // Byte 1
192                         ,
193                         // Byte 2
194                         BasicMPP,
195                 ],
196         });
197
198         /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
199         /// useful for manipulating feature flags.
200         macro_rules! define_feature {
201                 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
202                  $required_setter: ident) => {
203                         #[doc = $doc]
204                         ///
205                         /// See [BOLT #9] for details.
206                         ///
207                         /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
208                         pub trait $feature: Context {
209                                 /// The bit used to signify that the feature is required.
210                                 const EVEN_BIT: usize = $odd_bit - 1;
211
212                                 /// The bit used to signify that the feature is optional.
213                                 const ODD_BIT: usize = $odd_bit;
214
215                                 /// Assertion that [`EVEN_BIT`] is actually even.
216                                 ///
217                                 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
218                                 const ASSERT_EVEN_BIT_PARITY: usize;
219
220                                 /// Assertion that [`ODD_BIT`] is actually odd.
221                                 ///
222                                 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
223                                 const ASSERT_ODD_BIT_PARITY: usize;
224
225                                 /// The byte where the feature is set.
226                                 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
227
228                                 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
229                                 ///
230                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
231                                 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
232
233                                 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
234                                 ///
235                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
236                                 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
237
238                                 /// Returns whether the feature is required by the given flags.
239                                 #[inline]
240                                 fn requires_feature(flags: &Vec<u8>) -> bool {
241                                         flags.len() > Self::BYTE_OFFSET &&
242                                                 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
243                                 }
244
245                                 /// Returns whether the feature is supported by the given flags.
246                                 #[inline]
247                                 fn supports_feature(flags: &Vec<u8>) -> bool {
248                                         flags.len() > Self::BYTE_OFFSET &&
249                                                 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
250                                 }
251
252                                 /// Sets the feature's required (even) bit in the given flags.
253                                 #[inline]
254                                 fn set_required_bit(flags: &mut Vec<u8>) {
255                                         if flags.len() <= Self::BYTE_OFFSET {
256                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
257                                         }
258
259                                         flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
260                                 }
261
262                                 /// Sets the feature's optional (odd) bit in the given flags.
263                                 #[inline]
264                                 fn set_optional_bit(flags: &mut Vec<u8>) {
265                                         if flags.len() <= Self::BYTE_OFFSET {
266                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
267                                         }
268
269                                         flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
270                                 }
271
272                                 /// Clears the feature's required (even) and optional (odd) bits from the given
273                                 /// flags.
274                                 #[inline]
275                                 fn clear_bits(flags: &mut Vec<u8>) {
276                                         if flags.len() > Self::BYTE_OFFSET {
277                                                 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
278                                                 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
279                                         }
280
281                                         let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
282                                         let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
283                                         flags.resize(size, 0u8);
284                                 }
285                         }
286
287                         impl <T: $feature> Features<T> {
288                                 /// Set this feature as optional.
289                                 pub fn $optional_setter(mut self) -> Self {
290                                         <T as $feature>::set_optional_bit(&mut self.flags);
291                                         self
292                                 }
293
294                                 /// Set this feature as required.
295                                 pub fn $required_setter(mut self) -> Self {
296                                         <T as $feature>::set_required_bit(&mut self.flags);
297                                         self
298                                 }
299                         }
300
301                         $(
302                                 impl $feature for $context {
303                                         // EVEN_BIT % 2 == 0
304                                         const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
305
306                                         // ODD_BIT % 2 == 1
307                                         const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
308                                 }
309                         )*
310
311                 }
312         }
313
314         define_feature!(1, DataLossProtect, [InitContext, NodeContext],
315                 "Feature flags for `option_data_loss_protect`.", set_data_loss_protect_optional,
316                 set_data_loss_protect_required);
317         // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
318         define_feature!(3, InitialRoutingSync, [InitContext], "Feature flags for `initial_routing_sync`.",
319                 set_initial_routing_sync_optional, set_initial_routing_sync_required);
320         define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
321                 "Feature flags for `option_upfront_shutdown_script`.", set_upfront_shutdown_script_optional,
322                 set_upfront_shutdown_script_required);
323         define_feature!(7, GossipQueries, [InitContext, NodeContext],
324                 "Feature flags for `gossip_queries`.", set_gossip_queries_optional, set_gossip_queries_required);
325         define_feature!(9, VariableLengthOnion, [InitContext, NodeContext, InvoiceContext],
326                 "Feature flags for `var_onion_optin`.", set_variable_length_onion_optional,
327                 set_variable_length_onion_required);
328         define_feature!(13, StaticRemoteKey, [InitContext, NodeContext],
329                 "Feature flags for `option_static_remotekey`.", set_static_remote_key_optional,
330                 set_static_remote_key_required);
331         define_feature!(15, PaymentSecret, [InitContext, NodeContext, InvoiceContext],
332                 "Feature flags for `payment_secret`.", set_payment_secret_optional, set_payment_secret_required);
333         define_feature!(17, BasicMPP, [InitContext, NodeContext, InvoiceContext],
334                 "Feature flags for `basic_mpp`.", set_basic_mpp_optional, set_basic_mpp_required);
335         define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
336                 "Feature flags for `opt_shutdown_anysegwit`.", set_shutdown_any_segwit_optional,
337                 set_shutdown_any_segwit_required);
338         define_feature!(55, Keysend, [NodeContext],
339                 "Feature flags for keysend payments.", set_keysend_optional, set_keysend_required);
340
341         #[cfg(test)]
342         define_feature!(123456789, UnknownFeature, [NodeContext, ChannelContext, InvoiceContext],
343                 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
344                 set_unknown_feature_required);
345 }
346
347 /// Tracks the set of features which a node implements, templated by the context in which it
348 /// appears.
349 ///
350 /// (C-not exported) as we map the concrete feature types below directly instead
351 #[derive(Eq)]
352 pub struct Features<T: sealed::Context> {
353         /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
354         flags: Vec<u8>,
355         mark: PhantomData<T>,
356 }
357
358 impl<T: sealed::Context> Clone for Features<T> {
359         fn clone(&self) -> Self {
360                 Self {
361                         flags: self.flags.clone(),
362                         mark: PhantomData,
363                 }
364         }
365 }
366 impl<T: sealed::Context> Hash for Features<T> {
367         fn hash<H: Hasher>(&self, hasher: &mut H) {
368                 self.flags.hash(hasher);
369         }
370 }
371 impl<T: sealed::Context> PartialEq for Features<T> {
372         fn eq(&self, o: &Self) -> bool {
373                 self.flags.eq(&o.flags)
374         }
375 }
376 impl<T: sealed::Context> fmt::Debug for Features<T> {
377         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
378                 self.flags.fmt(fmt)
379         }
380 }
381
382 /// Features used within an `init` message.
383 pub type InitFeatures = Features<sealed::InitContext>;
384 /// Features used within a `node_announcement` message.
385 pub type NodeFeatures = Features<sealed::NodeContext>;
386 /// Features used within a `channel_announcement` message.
387 pub type ChannelFeatures = Features<sealed::ChannelContext>;
388 /// Features used within an invoice.
389 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
390
391 impl InitFeatures {
392         /// Writes all features present up to, and including, 13.
393         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
394                 let len = cmp::min(2, self.flags.len());
395                 w.size_hint(len + 2);
396                 (len as u16).write(w)?;
397                 for i in (0..len).rev() {
398                         if i == 0 {
399                                 self.flags[i].write(w)?;
400                         } else {
401                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
402                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
403                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
404                         }
405                 }
406                 Ok(())
407         }
408
409         /// or's another InitFeatures into this one.
410         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
411                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
412                 self.flags.resize(total_feature_len, 0u8);
413                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
414                         *byte |= *o_byte;
415                 }
416                 self
417         }
418
419         /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
420         /// are included in the result.
421         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
422                 self.to_context_internal()
423         }
424 }
425
426 impl InvoiceFeatures {
427         /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
428         /// context `C` are included in the result.
429         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
430                 self.to_context_internal()
431         }
432
433         /// Getting a route for a keysend payment to a private node requires providing the payee's
434         /// features (since they were not announced in a node announcement). However, keysend payments
435         /// don't have an invoice to pull the payee's features from, so this method is provided for use in
436         /// [`get_keysend_route`], thus omitting the need for payers to manually construct an
437         /// `InvoiceFeatures` for [`get_route`].
438         ///
439         /// [`get_keysend_route`]: crate::routing::router::get_keysend_route
440         /// [`get_route`]: crate::routing::router::get_route
441         pub(crate) fn for_keysend() -> InvoiceFeatures {
442                 InvoiceFeatures::empty().set_variable_length_onion_optional()
443         }
444 }
445
446 impl ToBase32 for InvoiceFeatures {
447         fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
448                 // Explanation for the "4": the normal way to round up when dividing is to add the divisor
449                 // minus one before dividing
450                 let length_u5s = (self.flags.len() * 8 + 4) / 5 as usize;
451                 let mut res_u5s: Vec<u5> = vec![u5::try_from_u8(0).unwrap(); length_u5s];
452                 for (byte_idx, byte) in self.flags.iter().enumerate() {
453                         let bit_pos_from_left_0_indexed = byte_idx * 8;
454                         let new_u5_idx = length_u5s - (bit_pos_from_left_0_indexed / 5) as usize - 1;
455                         let new_bit_pos = bit_pos_from_left_0_indexed % 5;
456                         let shifted_chunk_u16 = (*byte as u16) << new_bit_pos;
457                         let curr_u5_as_u8 = res_u5s[new_u5_idx].to_u8();
458                         res_u5s[new_u5_idx] = u5::try_from_u8(curr_u5_as_u8 | ((shifted_chunk_u16 & 0x001f) as u8)).unwrap();
459                         if new_u5_idx > 0 {
460                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 1].to_u8();
461                                 res_u5s[new_u5_idx - 1] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 5) & 0x001f) as u8)).unwrap();
462                         }
463                         if new_u5_idx > 1 {
464                                 let curr_u5_as_u8 = res_u5s[new_u5_idx - 2].to_u8();
465                                 res_u5s[new_u5_idx - 2] = u5::try_from_u8(curr_u5_as_u8 | (((shifted_chunk_u16 >> 10) & 0x001f) as u8)).unwrap();
466                         }
467                 }
468                 // Trim the highest feature bits.
469                 while !res_u5s.is_empty() && res_u5s[0] == u5::try_from_u8(0).unwrap() {
470                         res_u5s.remove(0);
471                 }
472                 writer.write(&res_u5s)
473         }
474 }
475
476 impl Base32Len for InvoiceFeatures {
477         fn base32_len(&self) -> usize {
478                 self.to_base32().len()
479         }
480 }
481
482 impl FromBase32 for InvoiceFeatures {
483         type Err = bech32::Error;
484
485         fn from_base32(field_data: &[u5]) -> Result<InvoiceFeatures, bech32::Error> {
486                 // Explanation for the "7": the normal way to round up when dividing is to add the divisor
487                 // minus one before dividing
488                 let length_bytes = (field_data.len() * 5 + 7) / 8 as usize;
489                 let mut res_bytes: Vec<u8> = vec![0; length_bytes];
490                 for (u5_idx, chunk) in field_data.iter().enumerate() {
491                         let bit_pos_from_right_0_indexed = (field_data.len() - u5_idx - 1) * 5;
492                         let new_byte_idx = (bit_pos_from_right_0_indexed / 8) as usize;
493                         let new_bit_pos = bit_pos_from_right_0_indexed % 8;
494                         let chunk_u16 = chunk.to_u8() as u16;
495                         res_bytes[new_byte_idx] |= ((chunk_u16 << new_bit_pos) & 0xff) as u8;
496                         if new_byte_idx != length_bytes - 1 {
497                                 res_bytes[new_byte_idx + 1] |= ((chunk_u16 >> (8-new_bit_pos)) & 0xff) as u8;
498                         }
499                 }
500                 // Trim the highest feature bits.
501                 while !res_bytes.is_empty() && res_bytes[res_bytes.len() - 1] == 0 {
502                         res_bytes.pop();
503                 }
504                 Ok(InvoiceFeatures::from_le_bytes(res_bytes))
505         }
506 }
507
508 impl<T: sealed::Context> Features<T> {
509         /// Create a blank Features with no features set
510         pub fn empty() -> Self {
511                 Features {
512                         flags: Vec::new(),
513                         mark: PhantomData,
514                 }
515         }
516
517         /// Creates a Features with the bits set which are known by the implementation
518         pub fn known() -> Self {
519                 Self {
520                         flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
521                         mark: PhantomData,
522                 }
523         }
524
525         /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
526         /// included in the result.
527         fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
528                 let from_byte_count = T::KNOWN_FEATURE_MASK.len();
529                 let to_byte_count = C::KNOWN_FEATURE_MASK.len();
530                 let mut flags = Vec::new();
531                 for (i, byte) in self.flags.iter().enumerate() {
532                         if i < from_byte_count && i < to_byte_count {
533                                 let from_known_features = T::KNOWN_FEATURE_MASK[i];
534                                 let to_known_features = C::KNOWN_FEATURE_MASK[i];
535                                 flags.push(byte & from_known_features & to_known_features);
536                         }
537                 }
538                 Features::<C> { flags, mark: PhantomData, }
539         }
540
541         /// Create a Features given a set of flags, in little-endian. This is in reverse byte order from
542         /// most on-the-wire encodings.
543         /// (C-not exported) as we don't support export across multiple T
544         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
545                 Features {
546                         flags,
547                         mark: PhantomData,
548                 }
549         }
550
551         #[cfg(test)]
552         /// Gets the underlying flags set, in LE.
553         pub fn le_flags(&self) -> &Vec<u8> {
554                 &self.flags
555         }
556
557         /// Returns true if this `Features` object contains unknown feature flags which are set as
558         /// "required".
559         pub fn requires_unknown_bits(&self) -> bool {
560                 // Bitwise AND-ing with all even bits set except for known features will select required
561                 // unknown features.
562                 let byte_count = T::KNOWN_FEATURE_MASK.len();
563                 self.flags.iter().enumerate().any(|(i, &byte)| {
564                         let required_features = 0b01_01_01_01;
565                         let unknown_features = if i < byte_count {
566                                 !T::KNOWN_FEATURE_MASK[i]
567                         } else {
568                                 0b11_11_11_11
569                         };
570                         (byte & (required_features & unknown_features)) != 0
571                 })
572         }
573
574         pub(crate) fn supports_unknown_bits(&self) -> bool {
575                 // Bitwise AND-ing with all even and odd bits set except for known features will select
576                 // both required and optional unknown features.
577                 let byte_count = T::KNOWN_FEATURE_MASK.len();
578                 self.flags.iter().enumerate().any(|(i, &byte)| {
579                         let unknown_features = if i < byte_count {
580                                 !T::KNOWN_FEATURE_MASK[i]
581                         } else {
582                                 0b11_11_11_11
583                         };
584                         (byte & unknown_features) != 0
585                 })
586         }
587
588         /// The number of bytes required to represent the feature flags present. This does not include
589         /// the length bytes which are included in the serialized form.
590         pub(crate) fn byte_count(&self) -> usize {
591                 self.flags.len()
592         }
593 }
594
595 impl<T: sealed::DataLossProtect> Features<T> {
596         #[cfg(test)]
597         pub(crate) fn requires_data_loss_protect(&self) -> bool {
598                 <T as sealed::DataLossProtect>::requires_feature(&self.flags)
599         }
600         #[cfg(test)]
601         pub(crate) fn supports_data_loss_protect(&self) -> bool {
602                 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
603         }
604 }
605
606 impl<T: sealed::UpfrontShutdownScript> Features<T> {
607         #[cfg(test)]
608         pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
609                 <T as sealed::UpfrontShutdownScript>::requires_feature(&self.flags)
610         }
611         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
612                 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
613         }
614         #[cfg(test)]
615         pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
616                 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
617                 self
618         }
619 }
620
621
622 impl<T: sealed::GossipQueries> Features<T> {
623         #[cfg(test)]
624         pub(crate) fn requires_gossip_queries(&self) -> bool {
625                 <T as sealed::GossipQueries>::requires_feature(&self.flags)
626         }
627         pub(crate) fn supports_gossip_queries(&self) -> bool {
628                 <T as sealed::GossipQueries>::supports_feature(&self.flags)
629         }
630         #[cfg(test)]
631         pub(crate) fn clear_gossip_queries(mut self) -> Self {
632                 <T as sealed::GossipQueries>::clear_bits(&mut self.flags);
633                 self
634         }
635 }
636
637 impl<T: sealed::VariableLengthOnion> Features<T> {
638         #[cfg(test)]
639         pub(crate) fn requires_variable_length_onion(&self) -> bool {
640                 <T as sealed::VariableLengthOnion>::requires_feature(&self.flags)
641         }
642         pub(crate) fn supports_variable_length_onion(&self) -> bool {
643                 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
644         }
645 }
646
647 impl<T: sealed::StaticRemoteKey> Features<T> {
648         pub(crate) fn supports_static_remote_key(&self) -> bool {
649                 <T as sealed::StaticRemoteKey>::supports_feature(&self.flags)
650         }
651         #[cfg(test)]
652         pub(crate) fn requires_static_remote_key(&self) -> bool {
653                 <T as sealed::StaticRemoteKey>::requires_feature(&self.flags)
654         }
655 }
656
657 impl<T: sealed::InitialRoutingSync> Features<T> {
658         pub(crate) fn initial_routing_sync(&self) -> bool {
659                 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
660         }
661         // We are no longer setting initial_routing_sync now that gossip_queries
662         // is enabled. This feature is ignored by a peer when gossip_queries has 
663         // been negotiated.
664         #[cfg(test)]
665         pub(crate) fn clear_initial_routing_sync(&mut self) {
666                 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
667         }
668 }
669
670 impl<T: sealed::PaymentSecret> Features<T> {
671         #[cfg(test)]
672         pub(crate) fn requires_payment_secret(&self) -> bool {
673                 <T as sealed::PaymentSecret>::requires_feature(&self.flags)
674         }
675         /// Returns whether the `payment_secret` feature is supported.
676         pub fn supports_payment_secret(&self) -> bool {
677                 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
678         }
679 }
680
681 impl<T: sealed::BasicMPP> Features<T> {
682         #[cfg(test)]
683         pub(crate) fn requires_basic_mpp(&self) -> bool {
684                 <T as sealed::BasicMPP>::requires_feature(&self.flags)
685         }
686         // We currently never test for this since we don't actually *generate* multipath routes.
687         pub(crate) fn supports_basic_mpp(&self) -> bool {
688                 <T as sealed::BasicMPP>::supports_feature(&self.flags)
689         }
690 }
691
692 impl<T: sealed::ShutdownAnySegwit> Features<T> {
693         pub(crate) fn supports_shutdown_anysegwit(&self) -> bool {
694                 <T as sealed::ShutdownAnySegwit>::supports_feature(&self.flags)
695         }
696         #[cfg(test)]
697         pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
698                 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
699                 self
700         }
701 }
702
703 impl<T: sealed::Context> Writeable for Features<T> {
704         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
705                 w.size_hint(self.flags.len() + 2);
706                 (self.flags.len() as u16).write(w)?;
707                 for f in self.flags.iter().rev() { // Swap back to big-endian
708                         f.write(w)?;
709                 }
710                 Ok(())
711         }
712 }
713
714 impl<T: sealed::Context> Readable for Features<T> {
715         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
716                 let mut flags: Vec<u8> = Readable::read(r)?;
717                 flags.reverse(); // Swap to little-endian
718                 Ok(Self {
719                         flags,
720                         mark: PhantomData,
721                 })
722         }
723 }
724
725 #[cfg(test)]
726 mod tests {
727         use super::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
728         use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5};
729
730         #[test]
731         fn sanity_test_known_features() {
732                 assert!(!ChannelFeatures::known().requires_unknown_bits());
733                 assert!(!ChannelFeatures::known().supports_unknown_bits());
734                 assert!(!InitFeatures::known().requires_unknown_bits());
735                 assert!(!InitFeatures::known().supports_unknown_bits());
736                 assert!(!NodeFeatures::known().requires_unknown_bits());
737                 assert!(!NodeFeatures::known().supports_unknown_bits());
738
739                 assert!(InitFeatures::known().supports_upfront_shutdown_script());
740                 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
741                 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
742                 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
743
744                 assert!(InitFeatures::known().supports_gossip_queries());
745                 assert!(NodeFeatures::known().supports_gossip_queries());
746                 assert!(!InitFeatures::known().requires_gossip_queries());
747                 assert!(!NodeFeatures::known().requires_gossip_queries());
748
749                 assert!(InitFeatures::known().supports_data_loss_protect());
750                 assert!(NodeFeatures::known().supports_data_loss_protect());
751                 assert!(!InitFeatures::known().requires_data_loss_protect());
752                 assert!(!NodeFeatures::known().requires_data_loss_protect());
753
754                 assert!(InitFeatures::known().supports_variable_length_onion());
755                 assert!(NodeFeatures::known().supports_variable_length_onion());
756                 assert!(InvoiceFeatures::known().supports_variable_length_onion());
757                 assert!(InitFeatures::known().requires_variable_length_onion());
758                 assert!(NodeFeatures::known().requires_variable_length_onion());
759                 assert!(InvoiceFeatures::known().requires_variable_length_onion());
760
761                 assert!(InitFeatures::known().supports_static_remote_key());
762                 assert!(NodeFeatures::known().supports_static_remote_key());
763                 assert!(InitFeatures::known().requires_static_remote_key());
764                 assert!(NodeFeatures::known().requires_static_remote_key());
765
766                 assert!(InitFeatures::known().supports_payment_secret());
767                 assert!(NodeFeatures::known().supports_payment_secret());
768                 assert!(InvoiceFeatures::known().supports_payment_secret());
769                 assert!(InitFeatures::known().requires_payment_secret());
770                 assert!(NodeFeatures::known().requires_payment_secret());
771                 assert!(InvoiceFeatures::known().requires_payment_secret());
772
773                 assert!(InitFeatures::known().supports_basic_mpp());
774                 assert!(NodeFeatures::known().supports_basic_mpp());
775                 assert!(InvoiceFeatures::known().supports_basic_mpp());
776                 assert!(!InitFeatures::known().requires_basic_mpp());
777                 assert!(!NodeFeatures::known().requires_basic_mpp());
778                 assert!(!InvoiceFeatures::known().requires_basic_mpp());
779
780                 assert!(InitFeatures::known().supports_shutdown_anysegwit());
781                 assert!(NodeFeatures::known().supports_shutdown_anysegwit());
782
783                 let mut init_features = InitFeatures::known();
784                 assert!(init_features.initial_routing_sync());
785                 init_features.clear_initial_routing_sync();
786                 assert!(!init_features.initial_routing_sync());
787         }
788
789         #[test]
790         fn sanity_test_unknown_bits() {
791                 let features = ChannelFeatures::empty();
792                 assert!(!features.requires_unknown_bits());
793                 assert!(!features.supports_unknown_bits());
794
795                 let features = ChannelFeatures::empty().set_unknown_feature_required();
796                 assert!(features.requires_unknown_bits());
797                 assert!(features.supports_unknown_bits());
798
799                 let features = ChannelFeatures::empty().set_unknown_feature_optional();
800                 assert!(!features.requires_unknown_bits());
801                 assert!(features.supports_unknown_bits());
802         }
803
804         #[test]
805         fn convert_to_context_with_relevant_flags() {
806                 let init_features = InitFeatures::known().clear_upfront_shutdown_script().clear_gossip_queries();
807                 assert!(init_features.initial_routing_sync());
808                 assert!(!init_features.supports_upfront_shutdown_script());
809                 assert!(!init_features.supports_gossip_queries());
810
811                 let node_features: NodeFeatures = init_features.to_context();
812                 {
813                         // Check that the flags are as expected:
814                         // - option_data_loss_protect
815                         // - var_onion_optin (req) | static_remote_key (req) | payment_secret(req)
816                         // - basic_mpp
817                         // - opt_shutdown_anysegwit
818                         assert_eq!(node_features.flags.len(), 4);
819                         assert_eq!(node_features.flags[0], 0b00000010);
820                         assert_eq!(node_features.flags[1], 0b01010001);
821                         assert_eq!(node_features.flags[2], 0b00000010);
822                         assert_eq!(node_features.flags[3], 0b00001000);
823                 }
824
825                 // Check that cleared flags are kept blank when converting back:
826                 // - initial_routing_sync was not applicable to NodeContext
827                 // - upfront_shutdown_script was cleared before converting
828                 // - gossip_queries was cleared before converting
829                 let features: InitFeatures = node_features.to_context_internal();
830                 assert!(!features.initial_routing_sync());
831                 assert!(!features.supports_upfront_shutdown_script());
832                 assert!(!init_features.supports_gossip_queries());
833         }
834
835         #[test]
836         fn convert_to_context_with_unknown_flags() {
837                 // Ensure the `from` context has fewer known feature bytes than the `to` context.
838                 assert!(InvoiceFeatures::known().byte_count() < NodeFeatures::known().byte_count());
839                 let invoice_features = InvoiceFeatures::known().set_unknown_feature_optional();
840                 assert!(invoice_features.supports_unknown_bits());
841                 let node_features: NodeFeatures = invoice_features.to_context();
842                 assert!(!node_features.supports_unknown_bits());
843         }
844
845         #[test]
846         fn set_feature_bits() {
847                 let features = InvoiceFeatures::empty()
848                         .set_basic_mpp_optional()
849                         .set_payment_secret_required();
850                 assert!(features.supports_basic_mpp());
851                 assert!(!features.requires_basic_mpp());
852                 assert!(features.requires_payment_secret());
853                 assert!(features.supports_payment_secret());
854         }
855
856         #[test]
857         fn invoice_features_encoding() {
858                 let features_as_u5s = vec![
859                         u5::try_from_u8(6).unwrap(),
860                         u5::try_from_u8(10).unwrap(),
861                         u5::try_from_u8(25).unwrap(),
862                         u5::try_from_u8(1).unwrap(),
863                         u5::try_from_u8(10).unwrap(),
864                         u5::try_from_u8(0).unwrap(),
865                         u5::try_from_u8(20).unwrap(),
866                         u5::try_from_u8(2).unwrap(),
867                         u5::try_from_u8(0).unwrap(),
868                         u5::try_from_u8(6).unwrap(),
869                         u5::try_from_u8(0).unwrap(),
870                         u5::try_from_u8(16).unwrap(),
871                         u5::try_from_u8(1).unwrap(),
872                 ];
873                 let features = InvoiceFeatures::from_le_bytes(vec![1, 2, 3, 4, 5, 42, 100, 101]);
874
875                 // Test length calculation.
876                 assert_eq!(features.base32_len(), 13);
877
878                 // Test serialization.
879                 let features_serialized = features.to_base32();
880                 assert_eq!(features_as_u5s, features_serialized);
881
882                 // Test deserialization.
883                 let features_deserialized = InvoiceFeatures::from_base32(&features_as_u5s).unwrap();
884                 assert_eq!(features, features_deserialized);
885         }
886 }