Merge pull request #428 from TheBlueMatt/2019-12-flat-features
[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
34 /// Tracks the set of features which a node implements, templated by the context in which it
35 /// appears.
36 pub struct Features<T: sealed::Context> {
37         /// Note that, for convinience, flags is LITTLE endian (despite being big-endian on the wire)
38         flags: Vec<u8>,
39         mark: PhantomData<T>,
40 }
41
42 impl<T: sealed::Context> Clone for Features<T> {
43         fn clone(&self) -> Self {
44                 Self {
45                         flags: self.flags.clone(),
46                         mark: PhantomData,
47                 }
48         }
49 }
50 impl<T: sealed::Context> PartialEq for Features<T> {
51         fn eq(&self, o: &Self) -> bool {
52                 self.flags.eq(&o.flags)
53         }
54 }
55 impl<T: sealed::Context> fmt::Debug for Features<T> {
56         fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
57                 self.flags.fmt(fmt)
58         }
59 }
60
61 /// A feature message as it appears in an init message
62 pub type InitFeatures = Features<sealed::InitContext>;
63 /// A feature message as it appears in a node_announcement message
64 pub type NodeFeatures = Features<sealed::NodeContext>;
65 /// A feature message as it appears in a channel_announcement message
66 pub type ChannelFeatures = Features<sealed::ChannelContext>;
67
68 impl InitFeatures {
69         /// Create a Features with the features we support
70         #[cfg(not(feature = "fuzztarget"))]
71         pub(crate) fn supported() -> InitFeatures {
72                 InitFeatures {
73                         flags: vec![2 | 1 << 5],
74                         mark: PhantomData,
75                 }
76         }
77         #[cfg(feature = "fuzztarget")]
78         pub fn supported() -> InitFeatures {
79                 InitFeatures {
80                         flags: vec![2 | 1 << 5],
81                         mark: PhantomData,
82                 }
83         }
84
85         /// Writes all features present up to, and including, 13.
86         pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
87                 let len = cmp::min(2, self.flags.len());
88                 w.size_hint(len + 2);
89                 (len as u16).write(w)?;
90                 for i in (0..len).rev() {
91                         if i == 0 {
92                                 self.flags[i].write(w)?;
93                         } else {
94                                 // On byte 1, we want up-to-and-including-bit-13, 0-indexed, which is
95                                 // up-to-and-including-bit-5, 0-indexed, on this byte:
96                                 (self.flags[i] & 0b00_11_11_11).write(w)?;
97                         }
98                 }
99                 Ok(())
100         }
101
102         /// or's another InitFeatures into this one.
103         pub(crate) fn or(mut self, o: InitFeatures) -> InitFeatures {
104                 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
105                 self.flags.resize(total_feature_len, 0u8);
106                 for (byte, o_byte) in self.flags.iter_mut().zip(o.flags.iter()) {
107                         *byte |= *o_byte;
108                 }
109                 self
110         }
111 }
112
113 impl ChannelFeatures {
114         /// Create a Features with the features we support
115         #[cfg(not(feature = "fuzztarget"))]
116         pub(crate) fn supported() -> ChannelFeatures {
117                 ChannelFeatures {
118                         flags: Vec::new(),
119                         mark: PhantomData,
120                 }
121         }
122         #[cfg(feature = "fuzztarget")]
123         pub fn supported() -> ChannelFeatures {
124                 ChannelFeatures {
125                         flags: Vec::new(),
126                         mark: PhantomData,
127                 }
128         }
129 }
130
131 impl NodeFeatures {
132         /// Create a Features with the features we support
133         #[cfg(not(feature = "fuzztarget"))]
134         pub(crate) fn supported() -> NodeFeatures {
135                 NodeFeatures {
136                         flags: vec![2 | 1 << 5],
137                         mark: PhantomData,
138                 }
139         }
140         #[cfg(feature = "fuzztarget")]
141         pub fn supported() -> NodeFeatures {
142                 NodeFeatures {
143                         flags: vec![2 | 1 << 5],
144                         mark: PhantomData,
145                 }
146         }
147 }
148
149 impl<T: sealed::Context> Features<T> {
150         /// Create a blank Features with no features set
151         pub fn empty() -> Features<T> {
152                 Features {
153                         flags: Vec::new(),
154                         mark: PhantomData,
155                 }
156         }
157
158         #[cfg(test)]
159         /// Create a Features given a set of flags, in LE.
160         pub fn from_le_bytes(flags: Vec<u8>) -> Features<T> {
161                 Features {
162                         flags,
163                         mark: PhantomData,
164                 }
165         }
166
167         #[cfg(test)]
168         /// Gets the underlying flags set, in LE.
169         pub fn le_flags(&self) -> &Vec<u8> {
170                 &self.flags
171         }
172
173         pub(crate) fn requires_unknown_bits(&self) -> bool {
174                 self.flags.iter().enumerate().any(|(idx, &byte)| {
175                         ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
176                 })
177         }
178
179         pub(crate) fn supports_unknown_bits(&self) -> bool {
180                 self.flags.iter().enumerate().any(|(idx, &byte)| {
181                         ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
182                 })
183         }
184
185         /// The number of bytes required to represent the feature flags present. This does not include
186         /// the length bytes which are included in the serialized form.
187         pub(crate) fn byte_count(&self) -> usize {
188                 self.flags.len()
189         }
190
191         #[cfg(test)]
192         pub(crate) fn set_require_unknown_bits(&mut self) {
193                 let newlen = cmp::max(2, self.flags.len());
194                 self.flags.resize(newlen, 0u8);
195                 self.flags[1] |= 0x40;
196         }
197
198         #[cfg(test)]
199         pub(crate) fn clear_require_unknown_bits(&mut self) {
200                 let newlen = cmp::max(2, self.flags.len());
201                 self.flags.resize(newlen, 0u8);
202                 self.flags[1] &= !0x40;
203                 if self.flags.len() == 2 && self.flags[1] == 0 {
204                         self.flags.resize(1, 0u8);
205                 }
206         }
207 }
208
209 impl<T: sealed::DataLossProtect> Features<T> {
210         pub(crate) fn supports_data_loss_protect(&self) -> bool {
211                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
212         }
213 }
214
215 impl<T: sealed::UpfrontShutdownScript> Features<T> {
216         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
217                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
218         }
219         #[cfg(test)]
220         pub(crate) fn unset_upfront_shutdown_script(&mut self) {
221                 self.flags[0] ^= 1 << 5;
222         }
223 }
224
225 impl<T: sealed::InitialRoutingSync> Features<T> {
226         pub(crate) fn initial_routing_sync(&self) -> bool {
227                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
228         }
229         pub(crate) fn set_initial_routing_sync(&mut self) {
230                 if self.flags.len() == 0 {
231                         self.flags.resize(1, 1 << 3);
232                 } else {
233                         self.flags[0] |= 1 << 3;
234                 }
235         }
236 }
237
238 impl<T: sealed::Context> Writeable for Features<T> {
239         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
240                 w.size_hint(self.flags.len() + 2);
241                 (self.flags.len() as u16).write(w)?;
242                 for f in self.flags.iter().rev() { // Swap back to big-endian
243                         f.write(w)?;
244                 }
245                 Ok(())
246         }
247 }
248
249 impl<R: ::std::io::Read, T: sealed::Context> Readable<R> for Features<T> {
250         fn read(r: &mut R) -> Result<Self, DecodeError> {
251                 let mut flags: Vec<u8> = Readable::read(r)?;
252                 flags.reverse(); // Swap to little-endian
253                 Ok(Self {
254                         flags,
255                         mark: PhantomData,
256                 })
257         }
258 }