549663c90d080c6eaae1111fce74909bc8d1dc18
[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). A
16 //! [`Context`] is used to parameterize [`Features`] and defines which features it can support.
17 //!
18 //! Whether a feature is considered "known" or "unknown" is relative to the implementation, whereas
19 //! the term "supports" is used in reference to a particular set of [`Features`]. That is, a node
20 //! supports a feature if it advertises the feature (as either required or optional) to its peers.
21 //! And the implementation can interpret a feature if the feature is known to it.
22 //!
23 //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
24 //! [messages]: ../msgs/index.html
25 //! [`Features`]: struct.Features.html
26 //! [`Context`]: sealed/trait.Context.html
27
28 use std::{cmp, fmt};
29 use std::marker::PhantomData;
30
31 use ln::msgs::DecodeError;
32 use util::ser::{Readable, Writeable, Writer};
33
34 mod sealed {
35         use ln::features::Features;
36
37         /// The context in which [`Features`] are applicable. Defines which features are required and
38         /// which are optional for the context.
39         ///
40         /// [`Features`]: ../struct.Features.html
41         pub trait Context {
42                 /// Features that are known to the implementation, where a required feature is indicated by
43                 /// its even bit and an optional feature is indicated by its odd bit.
44                 const KNOWN_FEATURE_FLAGS: &'static [u8];
45
46                 /// Bitmask for selecting features that are known to the implementation, regardless of
47                 /// whether each feature is required or optional.
48                 const KNOWN_FEATURE_MASK: &'static [u8];
49         }
50
51         /// Defines a [`Context`] by stating which features it requires and which are optional. Features
52         /// are specified as a comma-separated list of bytes where each byte is a pipe-delimited list of
53         /// feature identifiers.
54         ///
55         /// [`Context`]: trait.Context.html
56         macro_rules! define_context {
57                 ($context: ident {
58                         required_features: [$( $( $required_feature: ident )|*, )*],
59                         optional_features: [$( $( $optional_feature: ident )|*, )*],
60                 }) => {
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         }
96
97         define_context!(InitContext {
98                 required_features: [
99                         // Byte 0
100                         ,
101                         // Byte 1
102                         StaticRemoteKey,
103                         // Byte 2
104                         ,
105                         // Byte 3
106                         ,
107                 ],
108                 optional_features: [
109                         // Byte 0
110                         DataLossProtect | InitialRoutingSync | UpfrontShutdownScript | GossipQueries,
111                         // Byte 1
112                         VariableLengthOnion | PaymentSecret,
113                         // Byte 2
114                         BasicMPP,
115                         // Byte 3
116                         ShutdownAnySegwit,
117                 ],
118         });
119         define_context!(NodeContext {
120                 required_features: [
121                         // Byte 0
122                         ,
123                         // Byte 1
124                         StaticRemoteKey,
125                         // Byte 2
126                         ,
127                         // Byte 3
128                         ,
129                 ],
130                 optional_features: [
131                         // Byte 0
132                         DataLossProtect | UpfrontShutdownScript | GossipQueries,
133                         // Byte 1
134                         VariableLengthOnion | PaymentSecret,
135                         // Byte 2
136                         BasicMPP,
137                         // Byte 3
138                         ShutdownAnySegwit,
139                 ],
140         });
141         define_context!(ChannelContext {
142                 required_features: [],
143                 optional_features: [],
144         });
145         define_context!(InvoiceContext {
146                 required_features: [,,,],
147                 optional_features: [
148                         // Byte 0
149                         ,
150                         // Byte 1
151                         VariableLengthOnion | PaymentSecret,
152                         // Byte 2
153                         BasicMPP,
154                 ],
155         });
156
157         /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
158         /// useful for manipulating feature flags.
159         ///
160         /// [`Context`]: trait.Context.html
161         macro_rules! define_feature {
162                 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr, $optional_setter: ident,
163                  $required_setter: ident) => {
164                         #[doc = $doc]
165                         ///
166                         /// See [BOLT #9] for details.
167                         ///
168                         /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
169                         pub trait $feature: Context {
170                                 /// The bit used to signify that the feature is required.
171                                 const EVEN_BIT: usize = $odd_bit - 1;
172
173                                 /// The bit used to signify that the feature is optional.
174                                 const ODD_BIT: usize = $odd_bit;
175
176                                 /// Assertion that [`EVEN_BIT`] is actually even.
177                                 ///
178                                 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
179                                 const ASSERT_EVEN_BIT_PARITY: usize;
180
181                                 /// Assertion that [`ODD_BIT`] is actually odd.
182                                 ///
183                                 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
184                                 const ASSERT_ODD_BIT_PARITY: usize;
185
186                                 /// The byte where the feature is set.
187                                 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
188
189                                 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
190                                 ///
191                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
192                                 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
193
194                                 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
195                                 ///
196                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
197                                 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
198
199                                 /// Returns whether the feature is required by the given flags.
200                                 #[inline]
201                                 fn requires_feature(flags: &Vec<u8>) -> bool {
202                                         flags.len() > Self::BYTE_OFFSET &&
203                                                 (flags[Self::BYTE_OFFSET] & Self::REQUIRED_MASK) != 0
204                                 }
205
206                                 /// Returns whether the feature is supported by the given flags.
207                                 #[inline]
208                                 fn supports_feature(flags: &Vec<u8>) -> bool {
209                                         flags.len() > Self::BYTE_OFFSET &&
210                                                 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
211                                 }
212
213                                 /// Sets the feature's required (even) bit in the given flags.
214                                 #[inline]
215                                 fn set_required_bit(flags: &mut Vec<u8>) {
216                                         if flags.len() <= Self::BYTE_OFFSET {
217                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
218                                         }
219
220                                         flags[Self::BYTE_OFFSET] |= Self::REQUIRED_MASK;
221                                 }
222
223                                 /// Sets the feature's optional (odd) bit in the given flags.
224                                 #[inline]
225                                 fn set_optional_bit(flags: &mut Vec<u8>) {
226                                         if flags.len() <= Self::BYTE_OFFSET {
227                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
228                                         }
229
230                                         flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
231                                 }
232
233                                 /// Clears the feature's required (even) and optional (odd) bits from the given
234                                 /// flags.
235                                 #[inline]
236                                 fn clear_bits(flags: &mut Vec<u8>) {
237                                         if flags.len() > Self::BYTE_OFFSET {
238                                                 flags[Self::BYTE_OFFSET] &= !Self::REQUIRED_MASK;
239                                                 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
240                                         }
241
242                                         let last_non_zero_byte = flags.iter().rposition(|&byte| byte != 0);
243                                         let size = if let Some(offset) = last_non_zero_byte { offset + 1 } else { 0 };
244                                         flags.resize(size, 0u8);
245                                 }
246                         }
247
248                         impl <T: $feature> Features<T> {
249                                 /// Set this feature as optional.
250                                 pub fn $optional_setter(mut self) -> Self {
251                                         <T as $feature>::set_optional_bit(&mut self.flags);
252                                         self
253                                 }
254
255                                 /// Set this feature as required.
256                                 pub fn $required_setter(mut self) -> Self {
257                                         <T as $feature>::set_required_bit(&mut self.flags);
258                                         self
259                                 }
260                         }
261
262                         $(
263                                 impl $feature for $context {
264                                         // EVEN_BIT % 2 == 0
265                                         const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
266
267                                         // ODD_BIT % 2 == 1
268                                         const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
269                                 }
270                         )*
271
272                 }
273         }
274
275         define_feature!(1, DataLossProtect, [InitContext, NodeContext],
276                 "Feature flags for `option_data_loss_protect`.", set_data_loss_protect_optional,
277                 set_data_loss_protect_required);
278         // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
279         define_feature!(3, InitialRoutingSync, [InitContext], "Feature flags for `initial_routing_sync`.",
280                 set_initial_routing_sync_optional, set_initial_routing_sync_required);
281         define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
282                 "Feature flags for `option_upfront_shutdown_script`.", set_upfront_shutdown_script_optional,
283                 set_upfront_shutdown_script_required);
284         define_feature!(7, GossipQueries, [InitContext, NodeContext],
285                 "Feature flags for `gossip_queries`.", set_gossip_queries_optional, set_gossip_queries_required);
286         define_feature!(9, VariableLengthOnion, [InitContext, NodeContext, InvoiceContext],
287                 "Feature flags for `var_onion_optin`.", set_variable_length_onion_optional,
288                 set_variable_length_onion_required);
289         define_feature!(13, StaticRemoteKey, [InitContext, NodeContext],
290                 "Feature flags for `option_static_remotekey`.", set_static_remote_key_optional,
291                 set_static_remote_key_required);
292         define_feature!(15, PaymentSecret, [InitContext, NodeContext, InvoiceContext],
293                 "Feature flags for `payment_secret`.", set_payment_secret_optional, set_payment_secret_required);
294         define_feature!(17, BasicMPP, [InitContext, NodeContext, InvoiceContext],
295                 "Feature flags for `basic_mpp`.", set_basic_mpp_optional, set_basic_mpp_required);
296         define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
297                 "Feature flags for `opt_shutdown_anysegwit`.", set_shutdown_any_segwit_optional,
298                 set_shutdown_any_segwit_required);
299
300         #[cfg(test)]
301         define_context!(TestingContext {
302                 required_features: [
303                         // Byte 0
304                         ,
305                         // Byte 1
306                         ,
307                         // Byte 2
308                         UnknownFeature,
309                 ],
310                 optional_features: [
311                         // Byte 0
312                         ,
313                         // Byte 1
314                         ,
315                         // Byte 2
316                         ,
317                 ],
318         });
319
320         #[cfg(test)]
321         define_feature!(23, UnknownFeature, [TestingContext],
322                 "Feature flags for an unknown feature used in testing.", set_unknown_feature_optional,
323                 set_unknown_feature_required);
324 }
325
326 /// Tracks the set of features which a node implements, templated by the context in which it
327 /// appears.
328 ///
329 /// (C-not exported) as we map the concrete feature types below directly instead
330 pub struct Features<T: sealed::Context> {
331         /// Note that, for convenience, flags is LITTLE endian (despite being big-endian on the wire)
332         flags: Vec<u8>,
333         mark: PhantomData<T>,
334 }
335
336 impl<T: sealed::Context> Clone for Features<T> {
337         fn clone(&self) -> Self {
338                 Self {
339                         flags: self.flags.clone(),
340                         mark: PhantomData,
341                 }
342         }
343 }
344 impl<T: sealed::Context> PartialEq for Features<T> {
345         fn eq(&self, o: &Self) -> bool {
346                 self.flags.eq(&o.flags)
347         }
348 }
349 impl<T: sealed::Context> fmt::Debug for Features<T> {
350         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
351                 self.flags.fmt(fmt)
352         }
353 }
354
355 /// Features used within an `init` message.
356 pub type InitFeatures = Features<sealed::InitContext>;
357 /// Features used within a `node_announcement` message.
358 pub type NodeFeatures = Features<sealed::NodeContext>;
359 /// Features used within a `channel_announcement` message.
360 pub type ChannelFeatures = Features<sealed::ChannelContext>;
361 /// Features used within an invoice.
362 pub type InvoiceFeatures = Features<sealed::InvoiceContext>;
363
364 impl InitFeatures {
365         /// Writes all features present up to, and including, 13.
366         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
367                 let len = cmp::min(2, self.flags.len());
368                 w.size_hint(len + 2);
369                 (len as u16).write(w)?;
370                 for i in (0..len).rev() {
371                         if i == 0 {
372                                 self.flags[i].write(w)?;
373                         } else {
374                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
375                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
376                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
377                         }
378                 }
379                 Ok(())
380         }
381
382         /// or's another InitFeatures into this one.
383         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
384                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
385                 self.flags.resize(total_feature_len, 0u8);
386                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
387                         *byte |= *o_byte;
388                 }
389                 self
390         }
391
392         /// Converts `InitFeatures` to `Features<C>`. Only known `InitFeatures` relevant to context `C`
393         /// are included in the result.
394         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
395                 self.to_context_internal()
396         }
397 }
398
399 impl InvoiceFeatures {
400         /// Converts `InvoiceFeatures` to `Features<C>`. Only known `InvoiceFeatures` relevant to
401         /// context `C` are included in the result.
402         pub(crate) fn to_context<C: sealed::Context>(&self) -> Features<C> {
403                 self.to_context_internal()
404         }
405 }
406
407 impl<T: sealed::Context> Features<T> {
408         /// Create a blank Features with no features set
409         pub fn empty() -> Self {
410                 Features {
411                         flags: Vec::new(),
412                         mark: PhantomData,
413                 }
414         }
415
416         /// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
417         ///
418         /// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
419         pub fn known() -> Self {
420                 Self {
421                         flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
422                         mark: PhantomData,
423                 }
424         }
425
426         /// Converts `Features<T>` to `Features<C>`. Only known `T` features relevant to context `C` are
427         /// included in the result.
428         fn to_context_internal<C: sealed::Context>(&self) -> Features<C> {
429                 let byte_count = C::KNOWN_FEATURE_MASK.len();
430                 let mut flags = Vec::new();
431                 for (i, byte) in self.flags.iter().enumerate() {
432                         if i < byte_count {
433                                 let known_source_features = T::KNOWN_FEATURE_MASK[i];
434                                 let known_target_features = C::KNOWN_FEATURE_MASK[i];
435                                 flags.push(byte & known_source_features & known_target_features);
436                         }
437                 }
438                 Features::<C> { flags, mark: PhantomData, }
439         }
440
441         #[cfg(test)]
442         /// Create a Features given a set of flags, in LE.
443         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
444                 Features {
445                         flags,
446                         mark: PhantomData,
447                 }
448         }
449
450         #[cfg(test)]
451         /// Gets the underlying flags set, in LE.
452         pub fn le_flags(&self) -> &Vec<u8> {
453                 &self.flags
454         }
455
456         pub(crate) fn requires_unknown_bits(&self) -> bool {
457                 // Bitwise AND-ing with all even bits set except for known features will select required
458                 // unknown features.
459                 let byte_count = T::KNOWN_FEATURE_MASK.len();
460                 self.flags.iter().enumerate().any(|(i, &byte)| {
461                         let required_features = 0b01_01_01_01;
462                         let unknown_features = if i < byte_count {
463                                 !T::KNOWN_FEATURE_MASK[i]
464                         } else {
465                                 0b11_11_11_11
466                         };
467                         (byte & (required_features & unknown_features)) != 0
468                 })
469         }
470
471         pub(crate) fn supports_unknown_bits(&self) -> bool {
472                 // Bitwise AND-ing with all even and odd bits set except for known features will select
473                 // both required and optional unknown features.
474                 let byte_count = T::KNOWN_FEATURE_MASK.len();
475                 self.flags.iter().enumerate().any(|(i, &byte)| {
476                         let unknown_features = if i < byte_count {
477                                 !T::KNOWN_FEATURE_MASK[i]
478                         } else {
479                                 0b11_11_11_11
480                         };
481                         (byte & unknown_features) != 0
482                 })
483         }
484
485         /// The number of bytes required to represent the feature flags present. This does not include
486         /// the length bytes which are included in the serialized form.
487         pub(crate) fn byte_count(&self) -> usize {
488                 self.flags.len()
489         }
490
491         #[cfg(test)]
492         pub(crate) fn set_required_unknown_bits(&mut self) {
493                 <sealed::TestingContext as sealed::UnknownFeature>::set_required_bit(&mut self.flags);
494         }
495
496         #[cfg(test)]
497         pub(crate) fn set_optional_unknown_bits(&mut self) {
498                 <sealed::TestingContext as sealed::UnknownFeature>::set_optional_bit(&mut self.flags);
499         }
500
501         #[cfg(test)]
502         pub(crate) fn clear_unknown_bits(&mut self) {
503                 <sealed::TestingContext as sealed::UnknownFeature>::clear_bits(&mut self.flags);
504         }
505 }
506
507 impl<T: sealed::DataLossProtect> Features<T> {
508         #[cfg(test)]
509         pub(crate) fn requires_data_loss_protect(&self) -> bool {
510                 <T as sealed::DataLossProtect>::requires_feature(&self.flags)
511         }
512         pub(crate) fn supports_data_loss_protect(&self) -> bool {
513                 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
514         }
515 }
516
517 impl<T: sealed::UpfrontShutdownScript> Features<T> {
518         #[cfg(test)]
519         pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
520                 <T as sealed::UpfrontShutdownScript>::requires_feature(&self.flags)
521         }
522         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
523                 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
524         }
525         #[cfg(test)]
526         pub(crate) fn clear_upfront_shutdown_script(mut self) -> Self {
527                 <T as sealed::UpfrontShutdownScript>::clear_bits(&mut self.flags);
528                 self
529         }
530 }
531
532
533 impl<T: sealed::GossipQueries> Features<T> {
534         #[cfg(test)]
535         pub(crate) fn requires_gossip_queries(&self) -> bool {
536                 <T as sealed::GossipQueries>::requires_feature(&self.flags)
537         }
538         pub(crate) fn supports_gossip_queries(&self) -> bool {
539                 <T as sealed::GossipQueries>::supports_feature(&self.flags)
540         }
541         #[cfg(test)]
542         pub(crate) fn clear_gossip_queries(mut self) -> Self {
543                 <T as sealed::GossipQueries>::clear_bits(&mut self.flags);
544                 self
545         }
546 }
547
548 impl<T: sealed::VariableLengthOnion> Features<T> {
549         #[cfg(test)]
550         pub(crate) fn requires_variable_length_onion(&self) -> bool {
551                 <T as sealed::VariableLengthOnion>::requires_feature(&self.flags)
552         }
553         pub(crate) fn supports_variable_length_onion(&self) -> bool {
554                 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
555         }
556 }
557
558 impl<T: sealed::StaticRemoteKey> Features<T> {
559         pub(crate) fn supports_static_remote_key(&self) -> bool {
560                 <T as sealed::StaticRemoteKey>::supports_feature(&self.flags)
561         }
562         #[cfg(test)]
563         pub(crate) fn requires_static_remote_key(&self) -> bool {
564                 <T as sealed::StaticRemoteKey>::requires_feature(&self.flags)
565         }
566 }
567
568 impl<T: sealed::InitialRoutingSync> Features<T> {
569         pub(crate) fn initial_routing_sync(&self) -> bool {
570                 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
571         }
572         // We are no longer setting initial_routing_sync now that gossip_queries
573         // is enabled. This feature is ignored by a peer when gossip_queries has 
574         // been negotiated.
575         #[cfg(test)]
576         pub(crate) fn clear_initial_routing_sync(&mut self) {
577                 <T as sealed::InitialRoutingSync>::clear_bits(&mut self.flags)
578         }
579 }
580
581 impl<T: sealed::PaymentSecret> Features<T> {
582         #[cfg(test)]
583         pub(crate) fn requires_payment_secret(&self) -> bool {
584                 <T as sealed::PaymentSecret>::requires_feature(&self.flags)
585         }
586         // Note that we never need to test this since what really matters is the invoice - iff the
587         // invoice provides a payment_secret, we assume that we can use it (ie that the recipient
588         // supports payment_secret).
589         #[allow(dead_code)]
590         pub(crate) fn supports_payment_secret(&self) -> bool {
591                 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
592         }
593 }
594
595 impl<T: sealed::BasicMPP> Features<T> {
596         #[cfg(test)]
597         pub(crate) fn requires_basic_mpp(&self) -> bool {
598                 <T as sealed::BasicMPP>::requires_feature(&self.flags)
599         }
600         // We currently never test for this since we don't actually *generate* multipath routes.
601         pub(crate) fn supports_basic_mpp(&self) -> bool {
602                 <T as sealed::BasicMPP>::supports_feature(&self.flags)
603         }
604 }
605
606 impl<T: sealed::ShutdownAnySegwit> Features<T> {
607         pub(crate) fn supports_shutdown_anysegwit(&self) -> bool {
608                 <T as sealed::ShutdownAnySegwit>::supports_feature(&self.flags)
609         }
610         #[cfg(test)]
611         pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
612                 <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
613                 self
614         }
615 }
616
617 impl<T: sealed::Context> Writeable for Features<T> {
618         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
619                 w.size_hint(self.flags.len() + 2);
620                 (self.flags.len() as u16).write(w)?;
621                 for f in self.flags.iter().rev() { // Swap back to big-endian
622                         f.write(w)?;
623                 }
624                 Ok(())
625         }
626 }
627
628 impl<T: sealed::Context> Readable for Features<T> {
629         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
630                 let mut flags: Vec<u8> = Readable::read(r)?;
631                 flags.reverse(); // Swap to little-endian
632                 Ok(Self {
633                         flags,
634                         mark: PhantomData,
635                 })
636         }
637 }
638
639 #[cfg(test)]
640 mod tests {
641         use super::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
642
643         #[test]
644         fn sanity_test_known_features() {
645                 assert!(!ChannelFeatures::known().requires_unknown_bits());
646                 assert!(!ChannelFeatures::known().supports_unknown_bits());
647                 assert!(!InitFeatures::known().requires_unknown_bits());
648                 assert!(!InitFeatures::known().supports_unknown_bits());
649                 assert!(!NodeFeatures::known().requires_unknown_bits());
650                 assert!(!NodeFeatures::known().supports_unknown_bits());
651
652                 assert!(InitFeatures::known().supports_upfront_shutdown_script());
653                 assert!(NodeFeatures::known().supports_upfront_shutdown_script());
654                 assert!(!InitFeatures::known().requires_upfront_shutdown_script());
655                 assert!(!NodeFeatures::known().requires_upfront_shutdown_script());
656
657                 assert!(InitFeatures::known().supports_gossip_queries());
658                 assert!(NodeFeatures::known().supports_gossip_queries());
659                 assert!(!InitFeatures::known().requires_gossip_queries());
660                 assert!(!NodeFeatures::known().requires_gossip_queries());
661
662                 assert!(InitFeatures::known().supports_data_loss_protect());
663                 assert!(NodeFeatures::known().supports_data_loss_protect());
664                 assert!(!InitFeatures::known().requires_data_loss_protect());
665                 assert!(!NodeFeatures::known().requires_data_loss_protect());
666
667                 assert!(InitFeatures::known().supports_variable_length_onion());
668                 assert!(NodeFeatures::known().supports_variable_length_onion());
669                 assert!(!InitFeatures::known().requires_variable_length_onion());
670                 assert!(!NodeFeatures::known().requires_variable_length_onion());
671
672                 assert!(InitFeatures::known().supports_static_remote_key());
673                 assert!(NodeFeatures::known().supports_static_remote_key());
674                 assert!(InitFeatures::known().requires_static_remote_key());
675                 assert!(NodeFeatures::known().requires_static_remote_key());
676
677                 assert!(InitFeatures::known().supports_payment_secret());
678                 assert!(NodeFeatures::known().supports_payment_secret());
679                 assert!(!InitFeatures::known().requires_payment_secret());
680                 assert!(!NodeFeatures::known().requires_payment_secret());
681
682                 assert!(InitFeatures::known().supports_basic_mpp());
683                 assert!(NodeFeatures::known().supports_basic_mpp());
684                 assert!(!InitFeatures::known().requires_basic_mpp());
685                 assert!(!NodeFeatures::known().requires_basic_mpp());
686
687                 assert!(InitFeatures::known().supports_shutdown_anysegwit());
688                 assert!(NodeFeatures::known().supports_shutdown_anysegwit());
689
690                 let mut init_features = InitFeatures::known();
691                 assert!(init_features.initial_routing_sync());
692                 init_features.clear_initial_routing_sync();
693                 assert!(!init_features.initial_routing_sync());
694         }
695
696         #[test]
697         fn sanity_test_unknown_bits() {
698                 let mut features = ChannelFeatures::empty();
699                 assert!(!features.requires_unknown_bits());
700                 assert!(!features.supports_unknown_bits());
701
702                 features.set_required_unknown_bits();
703                 assert!(features.requires_unknown_bits());
704                 assert!(features.supports_unknown_bits());
705
706                 features.clear_unknown_bits();
707                 assert!(!features.requires_unknown_bits());
708                 assert!(!features.supports_unknown_bits());
709
710                 features.set_optional_unknown_bits();
711                 assert!(!features.requires_unknown_bits());
712                 assert!(features.supports_unknown_bits());
713         }
714
715         #[test]
716         fn convert_to_context_with_relevant_flags() {
717                 let init_features = InitFeatures::known().clear_upfront_shutdown_script().clear_gossip_queries();
718                 assert!(init_features.initial_routing_sync());
719                 assert!(!init_features.supports_upfront_shutdown_script());
720                 assert!(!init_features.supports_gossip_queries());
721
722                 let node_features: NodeFeatures = init_features.to_context();
723                 {
724                         // Check that the flags are as expected:
725                         // - option_data_loss_protect
726                         // - var_onion_optin | static_remote_key (req) | payment_secret
727                         // - basic_mpp
728                         // - opt_shutdown_anysegwit
729                         assert_eq!(node_features.flags.len(), 4);
730                         assert_eq!(node_features.flags[0], 0b00000010);
731                         assert_eq!(node_features.flags[1], 0b10010010);
732                         assert_eq!(node_features.flags[2], 0b00000010);
733                         assert_eq!(node_features.flags[3], 0b00001000);
734                 }
735
736                 // Check that cleared flags are kept blank when converting back:
737                 // - initial_routing_sync was not applicable to NodeContext
738                 // - upfront_shutdown_script was cleared before converting
739                 // - gossip_queries was cleared before converting
740                 let features: InitFeatures = node_features.to_context_internal();
741                 assert!(!features.initial_routing_sync());
742                 assert!(!features.supports_upfront_shutdown_script());
743                 assert!(!init_features.supports_gossip_queries());
744         }
745
746         #[test]
747         fn set_feature_bits() {
748                 let features = InvoiceFeatures::empty()
749                         .set_basic_mpp_optional()
750                         .set_payment_secret_required();
751                 assert!(features.supports_basic_mpp());
752                 assert!(!features.requires_basic_mpp());
753                 assert!(features.requires_payment_secret());
754                 assert!(features.supports_payment_secret());
755         }
756 }