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