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