Merge pull request #461 from ariard/2020-remove-duplicata
[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                                 0 => (byte & 0b00010100),
191                                 1 => (byte & 0b01010100),
192                                 _ => (byte & 0b01010101),
193                         }) != 0
194                 })
195         }
196
197         pub(crate) fn supports_unknown_bits(&self) -> bool {
198                 self.flags.iter().enumerate().any(|(idx, &byte)| {
199                         (match idx {
200                                 0 => (byte & 0b11000100),
201                                 1 => (byte & 0b11111100),
202                                 _ => byte,
203                         }) != 0
204                 })
205         }
206
207         /// The number of bytes required to represent the feature flags present. This does not include
208         /// the length bytes which are included in the serialized form.
209         pub(crate) fn byte_count(&self) -> usize {
210                 self.flags.len()
211         }
212
213         #[cfg(test)]
214         pub(crate) fn set_require_unknown_bits(&mut self) {
215                 let newlen = cmp::max(2, self.flags.len());
216                 self.flags.resize(newlen, 0u8);
217                 self.flags[1] |= 0x40;
218         }
219
220         #[cfg(test)]
221         pub(crate) fn clear_require_unknown_bits(&mut self) {
222                 let newlen = cmp::max(2, self.flags.len());
223                 self.flags.resize(newlen, 0u8);
224                 self.flags[1] &= !0x40;
225                 if self.flags.len() == 2 && self.flags[1] == 0 {
226                         self.flags.resize(1, 0u8);
227                 }
228         }
229 }
230
231 impl<T: sealed::DataLossProtect> Features<T> {
232         pub(crate) fn supports_data_loss_protect(&self) -> bool {
233                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
234         }
235 }
236
237 impl<T: sealed::UpfrontShutdownScript> Features<T> {
238         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
239                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
240         }
241         #[cfg(test)]
242         pub(crate) fn unset_upfront_shutdown_script(&mut self) {
243                 self.flags[0] ^= 1 << 5;
244         }
245 }
246
247 impl<T: sealed::VariableLengthOnion> Features<T> {
248         pub(crate) fn supports_variable_length_onion(&self) -> bool {
249                 self.flags.len() > 1 && (self.flags[1] & 3) != 0
250         }
251 }
252
253 impl<T: sealed::InitialRoutingSync> Features<T> {
254         pub(crate) fn initial_routing_sync(&self) -> bool {
255                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
256         }
257         pub(crate) fn set_initial_routing_sync(&mut self) {
258                 if self.flags.len() == 0 {
259                         self.flags.resize(1, 1 << 3);
260                 } else {
261                         self.flags[0] |= 1 << 3;
262                 }
263         }
264 }
265
266 impl<T: sealed::Context> Writeable for Features<T> {
267         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
268                 w.size_hint(self.flags.len() + 2);
269                 (self.flags.len() as u16).write(w)?;
270                 for f in self.flags.iter().rev() { // Swap back to big-endian
271                         f.write(w)?;
272                 }
273                 Ok(())
274         }
275 }
276
277 impl<R: ::std::io::Read, T: sealed::Context> Readable<R> for Features<T> {
278         fn read(r: &mut R) -> Result<Self, DecodeError> {
279                 let mut flags: Vec<u8> = Readable::read(r)?;
280                 flags.reverse(); // Swap to little-endian
281                 Ok(Self {
282                         flags,
283                         mark: PhantomData,
284                 })
285         }
286 }