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