Merge pull request #502 from rloomba/rloomba/add_unregister_listener
[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 mod sealed { // You should just use the type aliases instead.
12         pub struct InitContext {}
13         pub struct NodeContext {}
14         pub struct ChannelContext {}
15
16         /// An internal trait capturing the various feature context types
17         pub trait Context {}
18         impl Context for InitContext {}
19         impl Context for NodeContext {}
20         impl Context for ChannelContext {}
21
22         pub trait DataLossProtect: Context {}
23         impl DataLossProtect for InitContext {}
24         impl DataLossProtect for NodeContext {}
25
26         pub trait InitialRoutingSync: Context {}
27         impl InitialRoutingSync for InitContext {}
28
29         pub trait UpfrontShutdownScript: Context {}
30         impl UpfrontShutdownScript for InitContext {}
31         impl UpfrontShutdownScript for NodeContext {}
32
33         pub trait VariableLengthOnion: Context {}
34         impl VariableLengthOnion for InitContext {}
35         impl VariableLengthOnion for NodeContext {}
36 }
37
38 /// Tracks the set of features which a node implements, templated by the context in which it
39 /// appears.
40 pub struct Features<T: sealed::Context> {
41         /// Note that, for convinience, flags is LITTLE endian (despite being big-endian on the wire)
42         flags: Vec<u8>,
43         mark: PhantomData<T>,
44 }
45
46 impl<T: sealed::Context> Clone for Features<T> {
47         fn clone(&self) -> Self {
48                 Self {
49                         flags: self.flags.clone(),
50                         mark: PhantomData,
51                 }
52         }
53 }
54 impl<T: sealed::Context> PartialEq for Features<T> {
55         fn eq(&self, o: &Self) -> bool {
56                 self.flags.eq(&o.flags)
57         }
58 }
59 impl<T: sealed::Context> fmt::Debug for Features<T> {
60         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
61                 self.flags.fmt(fmt)
62         }
63 }
64
65 /// A feature message as it appears in an init message
66 pub type InitFeatures = Features<sealed::InitContext>;
67 /// A feature message as it appears in a node_announcement message
68 pub type NodeFeatures = Features<sealed::NodeContext>;
69 /// A feature message as it appears in a channel_announcement message
70 pub type ChannelFeatures = Features<sealed::ChannelContext>;
71
72 impl InitFeatures {
73         /// Create a Features with the features we support
74         pub fn supported() -> InitFeatures {
75                 InitFeatures {
76                         flags: vec![2 | 1 << 5, 1 << (9-8)],
77                         mark: PhantomData,
78                 }
79         }
80
81         /// Writes all features present up to, and including, 13.
82         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
83                 let len = cmp::min(2, self.flags.len());
84                 w.size_hint(len + 2);
85                 (len as u16).write(w)?;
86                 for i in (0..len).rev() {
87                         if i == 0 {
88                                 self.flags[i].write(w)?;
89                         } else {
90                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
91                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
92                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
93                         }
94                 }
95                 Ok(())
96         }
97
98         /// or's another InitFeatures into this one.
99         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
100                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
101                 self.flags.resize(total_feature_len, 0u8);
102                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
103                         *byte |= *o_byte;
104                 }
105                 self
106         }
107 }
108
109 impl ChannelFeatures {
110         /// Create a Features with the features we support
111         #[cfg(not(feature = "fuzztarget"))]
112         pub(crate) fn supported() -> ChannelFeatures {
113                 ChannelFeatures {
114                         flags: Vec::new(),
115                         mark: PhantomData,
116                 }
117         }
118         #[cfg(feature = "fuzztarget")]
119         pub fn supported() -> ChannelFeatures {
120                 ChannelFeatures {
121                         flags: Vec::new(),
122                         mark: PhantomData,
123                 }
124         }
125
126         /// Takes the flags that we know how to interpret in an init-context features that are also
127         /// relevant in a channel-context features and creates a channel-context features from them.
128         pub(crate) fn with_known_relevant_init_flags(_init_ctx: &InitFeatures) -> Self {
129                 // There are currently no channel flags defined that we understand.
130                 Self { flags: Vec::new(), mark: PhantomData, }
131         }
132 }
133
134 impl NodeFeatures {
135         /// Create a Features with the features we support
136         #[cfg(not(feature = "fuzztarget"))]
137         pub(crate) fn supported() -> NodeFeatures {
138                 NodeFeatures {
139                         flags: vec![2 | 1 << 5, 1 << (9-8)],
140                         mark: PhantomData,
141                 }
142         }
143         #[cfg(feature = "fuzztarget")]
144         pub fn supported() -> NodeFeatures {
145                 NodeFeatures {
146                         flags: vec![2 | 1 << 5, 1 << (9-8)],
147                         mark: PhantomData,
148                 }
149         }
150
151         /// Takes the flags that we know how to interpret in an init-context features that are also
152         /// relevant in a node-context features and creates a node-context features from them.
153         pub(crate) fn with_known_relevant_init_flags(init_ctx: &InitFeatures) -> Self {
154                 let mut flags = Vec::new();
155                 if init_ctx.flags.len() > 0 {
156                         // Pull out data_loss_protect and upfront_shutdown_script (bits 0, 1, 4, and 5)
157                         flags.push(init_ctx.flags.last().unwrap() & 0b00110011);
158                 }
159                 Self { flags, mark: PhantomData, }
160         }
161 }
162
163 impl<T: sealed::Context> Features<T> {
164         /// Create a blank Features with no features set
165         pub fn empty() -> Features<T> {
166                 Features {
167                         flags: Vec::new(),
168                         mark: PhantomData,
169                 }
170         }
171
172         #[cfg(test)]
173         /// Create a Features given a set of flags, in LE.
174         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
175                 Features {
176                         flags,
177                         mark: PhantomData,
178                 }
179         }
180
181         #[cfg(test)]
182         /// Gets the underlying flags set, in LE.
183         pub fn le_flags(&self) -> &Vec<u8> {
184                 &self.flags
185         }
186
187         pub(crate) fn requires_unknown_bits(&self) -> bool {
188                 self.flags.iter().enumerate().any(|(idx, &byte)| {
189                         (match idx {
190                                 // Unknown bits are even bits which we don't understand, we list ones which we do
191                                 // here:
192                                 // unknown, upfront_shutdown_script, unknown (actually initial_routing_sync, but it
193                                 // is only valid as an optional feature), and data_loss_protect:
194                                 0 => (byte & 0b01000100),
195                                 // unknown, unknown, unknown, var_onion_optin:
196                                 1 => (byte & 0b01010100),
197                                 // fallback, all even bits set:
198                                 _ => (byte & 0b01010101),
199                         }) != 0
200                 })
201         }
202
203         pub(crate) fn supports_unknown_bits(&self) -> bool {
204                 self.flags.iter().enumerate().any(|(idx, &byte)| {
205                         (match idx {
206                                 // unknown, upfront_shutdown_script, initial_routing_sync (is only valid as an
207                                 // optional feature), and data_loss_protect:
208                                 0 => (byte & 0b11000100),
209                                 // unknown, unknown, unknown, var_onion_optin:
210                                 1 => (byte & 0b11111100),
211                                 _ => byte,
212                         }) != 0
213                 })
214         }
215
216         /// The number of bytes required to represent the feature flags present. This does not include
217         /// the length bytes which are included in the serialized form.
218         pub(crate) fn byte_count(&self) -> usize {
219                 self.flags.len()
220         }
221
222         #[cfg(test)]
223         pub(crate) fn set_require_unknown_bits(&mut self) {
224                 let newlen = cmp::max(2, self.flags.len());
225                 self.flags.resize(newlen, 0u8);
226                 self.flags[1] |= 0x40;
227         }
228
229         #[cfg(test)]
230         pub(crate) fn clear_require_unknown_bits(&mut self) {
231                 let newlen = cmp::max(2, self.flags.len());
232                 self.flags.resize(newlen, 0u8);
233                 self.flags[1] &= !0x40;
234                 if self.flags.len() == 2 && self.flags[1] == 0 {
235                         self.flags.resize(1, 0u8);
236                 }
237         }
238 }
239
240 impl<T: sealed::DataLossProtect> Features<T> {
241         pub(crate) fn supports_data_loss_protect(&self) -> bool {
242                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
243         }
244 }
245
246 impl<T: sealed::UpfrontShutdownScript> Features<T> {
247         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
248                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
249         }
250         #[cfg(test)]
251         pub(crate) fn unset_upfront_shutdown_script(&mut self) {
252                 self.flags[0] ^= 1 << 5;
253         }
254 }
255
256 impl<T: sealed::VariableLengthOnion> Features<T> {
257         pub(crate) fn supports_variable_length_onion(&self) -> bool {
258                 self.flags.len() > 1 && (self.flags[1] & 3) != 0
259         }
260 }
261
262 impl<T: sealed::InitialRoutingSync> Features<T> {
263         pub(crate) fn initial_routing_sync(&self) -> bool {
264                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
265         }
266         pub(crate) fn set_initial_routing_sync(&mut self) {
267                 if self.flags.len() == 0 {
268                         self.flags.resize(1, 1 << 3);
269                 } else {
270                         self.flags[0] |= 1 << 3;
271                 }
272         }
273 }
274
275 impl<T: sealed::Context> Writeable for Features<T> {
276         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
277                 w.size_hint(self.flags.len() + 2);
278                 (self.flags.len() as u16).write(w)?;
279                 for f in self.flags.iter().rev() { // Swap back to big-endian
280                         f.write(w)?;
281                 }
282                 Ok(())
283         }
284 }
285
286 impl<R: ::std::io::Read, T: sealed::Context> Readable<R> for Features<T> {
287         fn read(r: &mut R) -> Result<Self, DecodeError> {
288                 let mut flags: Vec<u8> = Readable::read(r)?;
289                 flags.reverse(); // Swap to little-endian
290                 Ok(Self {
291                         flags,
292                         mark: PhantomData,
293                 })
294         }
295 }
296
297 #[cfg(test)]
298 mod tests {
299         use super::{ChannelFeatures, InitFeatures, NodeFeatures};
300
301         #[test]
302         fn sanity_test_our_features() {
303                 assert!(!ChannelFeatures::supported().requires_unknown_bits());
304                 assert!(!ChannelFeatures::supported().supports_unknown_bits());
305                 assert!(!InitFeatures::supported().requires_unknown_bits());
306                 assert!(!InitFeatures::supported().supports_unknown_bits());
307                 assert!(!NodeFeatures::supported().requires_unknown_bits());
308                 assert!(!NodeFeatures::supported().supports_unknown_bits());
309
310                 assert!(InitFeatures::supported().supports_upfront_shutdown_script());
311                 assert!(NodeFeatures::supported().supports_upfront_shutdown_script());
312
313                 assert!(InitFeatures::supported().supports_data_loss_protect());
314                 assert!(NodeFeatures::supported().supports_data_loss_protect());
315
316                 assert!(InitFeatures::supported().supports_variable_length_onion());
317                 assert!(NodeFeatures::supported().supports_variable_length_onion());
318
319                 let mut init_features = InitFeatures::supported();
320                 init_features.set_initial_routing_sync();
321                 assert!(!init_features.requires_unknown_bits());
322                 assert!(!init_features.supports_unknown_bits());
323         }
324
325         #[test]
326         fn sanity_test_unkown_bits_testing() {
327                 let mut features = ChannelFeatures::supported();
328                 features.set_require_unknown_bits();
329                 assert!(features.requires_unknown_bits());
330                 features.clear_require_unknown_bits();
331                 assert!(!features.requires_unknown_bits());
332         }
333 }