Encapsulate feature flag checking and manipulation
[rust-lightning] / lightning / src / ln / features.rs
1 //! Lightning exposes sets of supported operations through "feature flags". This module includes
2 //! types to store those feature flags and query for specific flags.
3
4 use std::{cmp, fmt};
5 use std::result::Result;
6 use std::marker::PhantomData;
7
8 use ln::msgs::DecodeError;
9 use util::ser::{Readable, Writeable, Writer};
10
11 #[macro_use]
12 mod sealed { // You should just use the type aliases instead.
13         pub struct InitContext {}
14         pub struct NodeContext {}
15         pub struct ChannelContext {}
16
17         /// An internal trait capturing the various feature context types
18         pub trait Context {}
19         impl Context for InitContext {}
20         impl Context for NodeContext {}
21         impl Context for ChannelContext {}
22
23         /// Defines a feature with the given bits for the specified [`Context`]s. The generated trait is
24         /// useful for manipulating feature flags.
25         ///
26         /// [`Context`]: trait.Context.html
27         macro_rules! define_feature {
28                 ($odd_bit: expr, $feature: ident, [$($context: ty),+], $doc: expr) => {
29                         #[doc = $doc]
30                         ///
31                         /// See [BOLT #9] for details.
32                         ///
33                         /// [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md
34                         pub trait $feature: Context {
35                                 /// The bit used to signify that the feature is required.
36                                 const EVEN_BIT: usize = $odd_bit - 1;
37
38                                 /// The bit used to signify that the feature is optional.
39                                 const ODD_BIT: usize = $odd_bit;
40
41                                 /// Assertion that [`EVEN_BIT`] is actually even.
42                                 ///
43                                 /// [`EVEN_BIT`]: #associatedconstant.EVEN_BIT
44                                 const ASSERT_EVEN_BIT_PARITY: usize;
45
46                                 /// Assertion that [`ODD_BIT`] is actually odd.
47                                 ///
48                                 /// [`ODD_BIT`]: #associatedconstant.ODD_BIT
49                                 const ASSERT_ODD_BIT_PARITY: usize;
50
51                                 /// The byte where the feature is set.
52                                 const BYTE_OFFSET: usize = Self::EVEN_BIT / 8;
53
54                                 /// The bitmask for the feature's required flag relative to the [`BYTE_OFFSET`].
55                                 ///
56                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
57                                 const REQUIRED_MASK: u8 = 1 << (Self::EVEN_BIT - 8 * Self::BYTE_OFFSET);
58
59                                 /// The bitmask for the feature's optional flag relative to the [`BYTE_OFFSET`].
60                                 ///
61                                 /// [`BYTE_OFFSET`]: #associatedconstant.BYTE_OFFSET
62                                 const OPTIONAL_MASK: u8 = 1 << (Self::ODD_BIT - 8 * Self::BYTE_OFFSET);
63
64                                 /// Returns whether the feature is supported by the given flags.
65                                 #[inline]
66                                 fn supports_feature(flags: &Vec<u8>) -> bool {
67                                         flags.len() > Self::BYTE_OFFSET &&
68                                                 (flags[Self::BYTE_OFFSET] & (Self::REQUIRED_MASK | Self::OPTIONAL_MASK)) != 0
69                                 }
70
71                                 /// Sets the feature's optional (odd) bit in the given flags.
72                                 #[inline]
73                                 fn set_optional_bit(flags: &mut Vec<u8>) {
74                                         if flags.len() <= Self::BYTE_OFFSET {
75                                                 flags.resize(Self::BYTE_OFFSET + 1, 0u8);
76                                         }
77
78                                         flags[Self::BYTE_OFFSET] |= Self::OPTIONAL_MASK;
79                                 }
80
81                                 /// Clears the feature's optional (odd) bit from the given flags.
82                                 #[inline]
83                                 fn clear_optional_bit(flags: &mut Vec<u8>) {
84                                         if flags.len() > Self::BYTE_OFFSET {
85                                                 flags[Self::BYTE_OFFSET] &= !Self::OPTIONAL_MASK;
86                                         }
87                                 }
88                         }
89
90                         $(
91                                 impl $feature for $context {
92                                         // EVEN_BIT % 2 == 0
93                                         const ASSERT_EVEN_BIT_PARITY: usize = 0 - (<Self as $feature>::EVEN_BIT % 2);
94
95                                         // ODD_BIT % 2 == 1
96                                         const ASSERT_ODD_BIT_PARITY: usize = (<Self as $feature>::ODD_BIT % 2) - 1;
97                                 }
98                         )*
99                 }
100         }
101
102         define_feature!(1, DataLossProtect, [InitContext, NodeContext],
103                 "Feature flags for `option_data_loss_protect`.");
104         // NOTE: Per Bolt #9, initial_routing_sync has no even bit.
105         define_feature!(3, InitialRoutingSync, [InitContext],
106                 "Feature flags for `initial_routing_sync`.");
107         define_feature!(5, UpfrontShutdownScript, [InitContext, NodeContext],
108                 "Feature flags for `option_upfront_shutdown_script`.");
109         define_feature!(9, VariableLengthOnion, [InitContext, NodeContext],
110                 "Feature flags for `var_onion_optin`.");
111         define_feature!(15, PaymentSecret, [InitContext, NodeContext],
112                 "Feature flags for `payment_secret`.");
113         define_feature!(17, BasicMPP, [InitContext, NodeContext],
114                 "Feature flags for `basic_mpp`.");
115
116         /// Generates a feature flag byte with the given features set as optional. Useful for initializing
117         /// the flags within [`Features`].
118         ///
119         /// [`Features`]: struct.Features.html
120         macro_rules! feature_flags {
121                 ($context: ty; $($feature: ident)|*) => {
122                         (0b00_00_00_00
123                                 $(
124                                         | <$context as sealed::$feature>::OPTIONAL_MASK
125                                 )*
126                         )
127                 }
128         }
129 }
130
131 /// Tracks the set of features which a node implements, templated by the context in which it
132 /// appears.
133 pub struct Features<T: sealed::Context> {
134         /// Note that, for convinience, flags is LITTLE endian (despite being big-endian on the wire)
135         flags: Vec<u8>,
136         mark: PhantomData<T>,
137 }
138
139 impl<T: sealed::Context> Clone for Features<T> {
140         fn clone(&self) -> Self {
141                 Self {
142                         flags: self.flags.clone(),
143                         mark: PhantomData,
144                 }
145         }
146 }
147 impl<T: sealed::Context> PartialEq for Features<T> {
148         fn eq(&self, o: &Self) -> bool {
149                 self.flags.eq(&o.flags)
150         }
151 }
152 impl<T: sealed::Context> fmt::Debug for Features<T> {
153         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
154                 self.flags.fmt(fmt)
155         }
156 }
157
158 /// A feature message as it appears in an init message
159 pub type InitFeatures = Features<sealed::InitContext>;
160 /// A feature message as it appears in a node_announcement message
161 pub type NodeFeatures = Features<sealed::NodeContext>;
162 /// A feature message as it appears in a channel_announcement message
163 pub type ChannelFeatures = Features<sealed::ChannelContext>;
164
165 impl InitFeatures {
166         /// Create a Features with the features we support
167         pub fn supported() -> InitFeatures {
168                 InitFeatures {
169                         flags: vec![
170                                 feature_flags![sealed::InitContext; DataLossProtect | InitialRoutingSync | UpfrontShutdownScript],
171                                 feature_flags![sealed::InitContext; VariableLengthOnion | PaymentSecret],
172                                 feature_flags![sealed::InitContext; BasicMPP],
173                         ],
174                         mark: PhantomData,
175                 }
176         }
177
178         /// Writes all features present up to, and including, 13.
179         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
180                 let len = cmp::min(2, self.flags.len());
181                 w.size_hint(len + 2);
182                 (len as u16).write(w)?;
183                 for i in (0..len).rev() {
184                         if i == 0 {
185                                 self.flags[i].write(w)?;
186                         } else {
187                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
188                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
189                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
190                         }
191                 }
192                 Ok(())
193         }
194
195         /// or's another InitFeatures into this one.
196         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
197                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
198                 self.flags.resize(total_feature_len, 0u8);
199                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
200                         *byte |= *o_byte;
201                 }
202                 self
203         }
204 }
205
206 impl ChannelFeatures {
207         /// Create a Features with the features we support
208         #[cfg(not(feature = "fuzztarget"))]
209         pub(crate) fn supported() -> ChannelFeatures {
210                 ChannelFeatures {
211                         flags: Vec::new(),
212                         mark: PhantomData,
213                 }
214         }
215         #[cfg(feature = "fuzztarget")]
216         pub fn supported() -> ChannelFeatures {
217                 ChannelFeatures {
218                         flags: Vec::new(),
219                         mark: PhantomData,
220                 }
221         }
222
223         /// Takes the flags that we know how to interpret in an init-context features that are also
224         /// relevant in a channel-context features and creates a channel-context features from them.
225         pub(crate) fn with_known_relevant_init_flags(_init_ctx: &InitFeatures) -> Self {
226                 // There are currently no channel flags defined that we understand.
227                 Self { flags: Vec::new(), mark: PhantomData, }
228         }
229 }
230
231 impl NodeFeatures {
232         /// Create a Features with the features we support
233         #[cfg(not(feature = "fuzztarget"))]
234         pub(crate) fn supported() -> NodeFeatures {
235                 NodeFeatures {
236                         flags: vec![
237                                 feature_flags![sealed::NodeContext; DataLossProtect | UpfrontShutdownScript],
238                                 feature_flags![sealed::NodeContext; VariableLengthOnion | PaymentSecret],
239                                 feature_flags![sealed::NodeContext; BasicMPP],
240                         ],
241                         mark: PhantomData,
242                 }
243         }
244         #[cfg(feature = "fuzztarget")]
245         pub fn supported() -> NodeFeatures {
246                 NodeFeatures {
247                         flags: vec![
248                                 feature_flags![sealed::NodeContext; DataLossProtect | UpfrontShutdownScript],
249                                 feature_flags![sealed::NodeContext; VariableLengthOnion | PaymentSecret],
250                                 feature_flags![sealed::NodeContext; BasicMPP],
251                         ],
252                         mark: PhantomData,
253                 }
254         }
255
256         /// Takes the flags that we know how to interpret in an init-context features that are also
257         /// relevant in a node-context features and creates a node-context features from them.
258         /// Be sure to blank out features that are unknown to us.
259         pub(crate) fn with_known_relevant_init_flags(init_ctx: &InitFeatures) -> Self {
260                 // Generates a bitmask with both even and odd bits set for the given features. Bitwise
261                 // AND-ing it with a byte will select only common features.
262                 macro_rules! features_including {
263                         ($($feature: ident)|*) => {
264                                 (0b00_00_00_00
265                                         $(
266                                                 | <sealed::NodeContext as sealed::$feature>::REQUIRED_MASK
267                                                 | <sealed::NodeContext as sealed::$feature>::OPTIONAL_MASK
268                                         )*
269                                 )
270                         }
271                 }
272
273                 let mut flags = Vec::new();
274                 for (i, feature_byte)in init_ctx.flags.iter().enumerate() {
275                         match i {
276                                 0 => flags.push(feature_byte & features_including![DataLossProtect | UpfrontShutdownScript]),
277                                 1 => flags.push(feature_byte & features_including![VariableLengthOnion | PaymentSecret]),
278                                 2 => flags.push(feature_byte & features_including![BasicMPP]),
279                                 _ => (),
280                         }
281                 }
282                 Self { flags, mark: PhantomData, }
283         }
284 }
285
286 impl<T: sealed::Context> Features<T> {
287         /// Create a blank Features with no features set
288         pub fn empty() -> Features<T> {
289                 Features {
290                         flags: Vec::new(),
291                         mark: PhantomData,
292                 }
293         }
294
295         #[cfg(test)]
296         /// Create a Features given a set of flags, in LE.
297         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
298                 Features {
299                         flags,
300                         mark: PhantomData,
301                 }
302         }
303
304         #[cfg(test)]
305         /// Gets the underlying flags set, in LE.
306         pub fn le_flags(&self) -> &Vec<u8> {
307                 &self.flags
308         }
309
310         pub(crate) fn requires_unknown_bits(&self) -> bool {
311                 // Generates a bitmask with all even bits set except for the given features. Bitwise
312                 // AND-ing it with a byte will select unknown required features.
313                 macro_rules! features_excluding {
314                         ($($feature: ident)|*) => {
315                                 (0b01_01_01_01
316                                         $(
317                                                 & !(<sealed::InitContext as sealed::$feature>::REQUIRED_MASK)
318                                         )*
319                                 )
320                         }
321                 }
322
323                 self.flags.iter().enumerate().any(|(idx, &byte)| {
324                         (match idx {
325                                 0 => (byte & features_excluding![DataLossProtect | InitialRoutingSync | UpfrontShutdownScript]),
326                                 1 => (byte & features_excluding![VariableLengthOnion | PaymentSecret]),
327                                 2 => (byte & features_excluding![BasicMPP]),
328                                 _ => (byte & features_excluding![]),
329                         }) != 0
330                 })
331         }
332
333         pub(crate) fn supports_unknown_bits(&self) -> bool {
334                 // Generates a bitmask with all even and odd bits set except for the given features. Bitwise
335                 // AND-ing it with a byte will select unknown supported features.
336                 macro_rules! features_excluding {
337                         ($($feature: ident)|*) => {
338                                 (0b11_11_11_11
339                                         $(
340                                                 & !(<sealed::InitContext as sealed::$feature>::REQUIRED_MASK)
341                                                 & !(<sealed::InitContext as sealed::$feature>::OPTIONAL_MASK)
342                                         )*
343                                 )
344                         }
345                 }
346
347                 self.flags.iter().enumerate().any(|(idx, &byte)| {
348                         (match idx {
349                                 0 => (byte & features_excluding![DataLossProtect | InitialRoutingSync | UpfrontShutdownScript]),
350                                 1 => (byte & features_excluding![VariableLengthOnion | PaymentSecret]),
351                                 2 => (byte & features_excluding![BasicMPP]),
352                                 _ => byte,
353                         }) != 0
354                 })
355         }
356
357         /// The number of bytes required to represent the feature flags present. This does not include
358         /// the length bytes which are included in the serialized form.
359         pub(crate) fn byte_count(&self) -> usize {
360                 self.flags.len()
361         }
362
363         #[cfg(test)]
364         pub(crate) fn set_require_unknown_bits(&mut self) {
365                 let newlen = cmp::max(3, self.flags.len());
366                 self.flags.resize(newlen, 0u8);
367                 self.flags[2] |= 0x40;
368         }
369
370         #[cfg(test)]
371         pub(crate) fn clear_require_unknown_bits(&mut self) {
372                 let newlen = cmp::max(3, self.flags.len());
373                 self.flags.resize(newlen, 0u8);
374                 self.flags[2] &= !0x40;
375                 if self.flags.len() == 3 && self.flags[2] == 0 {
376                         self.flags.resize(2, 0u8);
377                 }
378                 if self.flags.len() == 2 && self.flags[1] == 0 {
379                         self.flags.resize(1, 0u8);
380                 }
381         }
382 }
383
384 impl<T: sealed::DataLossProtect> Features<T> {
385         pub(crate) fn supports_data_loss_protect(&self) -> bool {
386                 <T as sealed::DataLossProtect>::supports_feature(&self.flags)
387         }
388 }
389
390 impl<T: sealed::UpfrontShutdownScript> Features<T> {
391         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
392                 <T as sealed::UpfrontShutdownScript>::supports_feature(&self.flags)
393         }
394         #[cfg(test)]
395         pub(crate) fn unset_upfront_shutdown_script(&mut self) {
396                 <T as sealed::UpfrontShutdownScript>::clear_optional_bit(&mut self.flags)
397         }
398 }
399
400 impl<T: sealed::VariableLengthOnion> Features<T> {
401         pub(crate) fn supports_variable_length_onion(&self) -> bool {
402                 <T as sealed::VariableLengthOnion>::supports_feature(&self.flags)
403         }
404 }
405
406 impl<T: sealed::InitialRoutingSync> Features<T> {
407         pub(crate) fn initial_routing_sync(&self) -> bool {
408                 <T as sealed::InitialRoutingSync>::supports_feature(&self.flags)
409         }
410         pub(crate) fn clear_initial_routing_sync(&mut self) {
411                 <T as sealed::InitialRoutingSync>::clear_optional_bit(&mut self.flags)
412         }
413 }
414
415 impl<T: sealed::PaymentSecret> Features<T> {
416         #[allow(dead_code)]
417         // Note that we never need to test this since what really matters is the invoice - iff the
418         // invoice provides a payment_secret, we assume that we can use it (ie that the recipient
419         // supports payment_secret).
420         pub(crate) fn supports_payment_secret(&self) -> bool {
421                 <T as sealed::PaymentSecret>::supports_feature(&self.flags)
422         }
423 }
424
425 impl<T: sealed::BasicMPP> Features<T> {
426         // We currently never test for this since we don't actually *generate* multipath routes.
427         #[allow(dead_code)]
428         pub(crate) fn supports_basic_mpp(&self) -> bool {
429                 <T as sealed::BasicMPP>::supports_feature(&self.flags)
430         }
431 }
432
433 impl<T: sealed::Context> Writeable for Features<T> {
434         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
435                 w.size_hint(self.flags.len() + 2);
436                 (self.flags.len() as u16).write(w)?;
437                 for f in self.flags.iter().rev() { // Swap back to big-endian
438                         f.write(w)?;
439                 }
440                 Ok(())
441         }
442 }
443
444 impl<T: sealed::Context> Readable for Features<T> {
445         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
446                 let mut flags: Vec<u8> = Readable::read(r)?;
447                 flags.reverse(); // Swap to little-endian
448                 Ok(Self {
449                         flags,
450                         mark: PhantomData,
451                 })
452         }
453 }
454
455 #[cfg(test)]
456 mod tests {
457         use super::{ChannelFeatures, InitFeatures, NodeFeatures, Features};
458
459         #[test]
460         fn sanity_test_our_features() {
461                 assert!(!ChannelFeatures::supported().requires_unknown_bits());
462                 assert!(!ChannelFeatures::supported().supports_unknown_bits());
463                 assert!(!InitFeatures::supported().requires_unknown_bits());
464                 assert!(!InitFeatures::supported().supports_unknown_bits());
465                 assert!(!NodeFeatures::supported().requires_unknown_bits());
466                 assert!(!NodeFeatures::supported().supports_unknown_bits());
467
468                 assert!(InitFeatures::supported().supports_upfront_shutdown_script());
469                 assert!(NodeFeatures::supported().supports_upfront_shutdown_script());
470
471                 assert!(InitFeatures::supported().supports_data_loss_protect());
472                 assert!(NodeFeatures::supported().supports_data_loss_protect());
473
474                 assert!(InitFeatures::supported().supports_variable_length_onion());
475                 assert!(NodeFeatures::supported().supports_variable_length_onion());
476
477                 assert!(InitFeatures::supported().supports_payment_secret());
478                 assert!(NodeFeatures::supported().supports_payment_secret());
479
480                 assert!(InitFeatures::supported().supports_basic_mpp());
481                 assert!(NodeFeatures::supported().supports_basic_mpp());
482
483                 let mut init_features = InitFeatures::supported();
484                 assert!(init_features.initial_routing_sync());
485                 init_features.clear_initial_routing_sync();
486                 assert!(!init_features.initial_routing_sync());
487         }
488
489         #[test]
490         fn sanity_test_unkown_bits_testing() {
491                 let mut features = ChannelFeatures::supported();
492                 features.set_require_unknown_bits();
493                 assert!(features.requires_unknown_bits());
494                 features.clear_require_unknown_bits();
495                 assert!(!features.requires_unknown_bits());
496         }
497
498         #[test]
499         fn test_node_with_known_relevant_init_flags() {
500                 // Create an InitFeatures with initial_routing_sync supported.
501                 let init_features = InitFeatures::supported();
502                 assert!(init_features.initial_routing_sync());
503
504                 // Attempt to pull out non-node-context feature flags from these InitFeatures.
505                 let res = NodeFeatures::with_known_relevant_init_flags(&init_features);
506
507                 {
508                         // Check that the flags are as expected: optional_data_loss_protect,
509                         // option_upfront_shutdown_script, var_onion_optin, payment_secret, and
510                         // basic_mpp.
511                         assert_eq!(res.flags.len(), 3);
512                         assert_eq!(res.flags[0], 0b00100010);
513                         assert_eq!(res.flags[1], 0b10000010);
514                         assert_eq!(res.flags[2], 0b00000010);
515                 }
516
517                 // Check that the initial_routing_sync feature was correctly blanked out.
518                 let new_features: InitFeatures = Features::from_le_bytes(res.flags);
519                 assert!(!new_features.initial_routing_sync());
520         }
521 }