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