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