Add a second Readable trait for state args, clean macros slightly
[rust-lightning] / src / util / ser.rs
1 //! A very simple serialization framework which is used to serialize/deserialize messages as well
2 //! as ChannelsManagers and ChannelMonitors.
3
4 use std::result::Result;
5 use std::io::Read;
6 use std::collections::HashMap;
7 use std::hash::Hash;
8
9 use secp256k1::{Secp256k1, Signature};
10 use secp256k1::key::PublicKey;
11 use bitcoin::util::hash::Sha256dHash;
12 use bitcoin::blockdata::script::Script;
13 use std::marker::Sized;
14 use ln::msgs::DecodeError;
15 use util::byte_utils;
16
17 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
18
19 const MAX_BUF_SIZE: usize = 64 * 1024;
20
21 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
22 /// buffers being written into.
23 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
24 /// hints.
25 pub trait Writer {
26         /// Writes the given buf out. See std::io::Write::write_all for more
27         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
28         /// Hints that data of the given size is about the be written. This may not always be called
29         /// prior to data being written and may be safely ignored.
30         fn size_hint(&mut self, size: usize);
31 }
32
33 impl<W: ::std::io::Write> Writer for W {
34         #[inline]
35         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
36                 <Self as ::std::io::Write>::write_all(self, buf)
37         }
38         #[inline]
39         fn size_hint(&mut self, _size: usize) { }
40 }
41
42 struct VecWriter(Vec<u8>);
43 impl Writer for VecWriter {
44         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
45                 self.0.extend_from_slice(buf);
46                 Ok(())
47         }
48         fn size_hint(&mut self, size: usize) {
49                 self.0.reserve_exact(size);
50         }
51 }
52
53 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
54 pub trait Writeable {
55         /// Writes self out to the given Writer
56         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
57
58         /// Writes self out to a Vec<u8>
59         fn encode(&self) -> Vec<u8> {
60                 let mut msg = VecWriter(Vec::new());
61                 self.write(&mut msg).unwrap();
62                 msg.0
63         }
64
65         /// Writes self out to a Vec<u8>
66         fn encode_with_len(&self) -> Vec<u8> {
67                 let mut msg = VecWriter(Vec::new());
68                 0u16.write(&mut msg).unwrap();
69                 self.write(&mut msg).unwrap();
70                 let len = msg.0.len();
71                 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
72                 msg.0
73         }
74 }
75
76 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
77 pub trait Readable<R>
78         where Self: Sized,
79               R: Read
80 {
81         /// Reads a Self in from the given Read
82         fn read(reader: &mut R) -> Result<Self, DecodeError>;
83 }
84
85 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
86 /// from a Read given some additional set of arguments which is required to deserialize.
87 pub trait ReadableArgs<R, P>
88         where Self: Sized,
89               R: Read
90 {
91         /// Reads a Self in from the given Read
92         fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
93 }
94
95 macro_rules! impl_writeable_primitive {
96         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
97                 impl Writeable for $val_type {
98                         #[inline]
99                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100                                 writer.write_all(&$meth_write(*self))
101                         }
102                 }
103                 impl<R: Read> Readable<R> for $val_type {
104                         #[inline]
105                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
106                                 let mut buf = [0; $len];
107                                 reader.read_exact(&mut buf)?;
108                                 Ok($meth_read(&buf))
109                         }
110                 }
111         }
112 }
113
114 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
115 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
116 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
117
118 impl Writeable for u8 {
119         #[inline]
120         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
121                 writer.write_all(&[*self])
122         }
123 }
124 impl<R: Read> Readable<R> for u8 {
125         #[inline]
126         fn read(reader: &mut R) -> Result<u8, DecodeError> {
127                 let mut buf = [0; 1];
128                 reader.read_exact(&mut buf)?;
129                 Ok(buf[0])
130         }
131 }
132
133 impl Writeable for bool {
134         #[inline]
135         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
136                 writer.write_all(&[if *self {1} else {0}])
137         }
138 }
139 impl<R: Read> Readable<R> for bool {
140         #[inline]
141         fn read(reader: &mut R) -> Result<bool, DecodeError> {
142                 let mut buf = [0; 1];
143                 reader.read_exact(&mut buf)?;
144                 if buf[0] != 0 && buf[0] != 1 {
145                         return Err(DecodeError::InvalidValue);
146                 }
147                 Ok(buf[0] == 1)
148         }
149 }
150
151 // u8 arrays
152 macro_rules! impl_array {
153         ( $size:expr ) => (
154                 impl Writeable for [u8; $size]
155                 {
156                         #[inline]
157                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
158                                 w.write_all(self)
159                         }
160                 }
161
162                 impl<R: Read> Readable<R> for [u8; $size]
163                 {
164                         #[inline]
165                         fn read(r: &mut R) -> Result<Self, DecodeError> {
166                                 let mut buf = [0u8; $size];
167                                 r.read_exact(&mut buf)?;
168                                 Ok(buf)
169                         }
170                 }
171         );
172 }
173
174 //TODO: performance issue with [u8; size] with impl_array!()
175 impl_array!(32); // for channel id & hmac
176 impl_array!(33); // for PublicKey
177 impl_array!(64); // for Signature
178 impl_array!(1300); // for OnionPacket.hop_data
179
180 // HashMap
181 impl<K, V> Writeable for HashMap<K, V>
182         where K: Writeable + Eq + Hash,
183               V: Writeable
184 {
185         #[inline]
186         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
187         (self.len() as u16).write(w)?;
188                 for (key, value) in self.iter() {
189                         key.write(w)?;
190                         value.write(w)?;
191                 }
192                 Ok(())
193         }
194 }
195
196 impl<R, K, V> Readable<R> for HashMap<K, V>
197         where R: Read,
198               K: Readable<R> + Eq + Hash,
199               V: Readable<R>
200 {
201         #[inline]
202         fn read(r: &mut R) -> Result<Self, DecodeError> {
203                 let len: u16 = Readable::read(r)?;
204                 let mut ret = HashMap::with_capacity(len as usize);
205                 for _ in 0..len {
206                         ret.insert(K::read(r)?, V::read(r)?);
207                 }
208                 Ok(ret)
209         }
210 }
211
212 // Vectors
213 impl Writeable for Vec<u8> {
214         #[inline]
215         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
216                 (self.len() as u16).write(w)?;
217                 w.write_all(&self)
218         }
219 }
220
221 impl<R: Read> Readable<R> for Vec<u8> {
222         #[inline]
223         fn read(r: &mut R) -> Result<Self, DecodeError> {
224                 let len: u16 = Readable::read(r)?;
225                 let mut ret = Vec::with_capacity(len as usize);
226                 ret.resize(len as usize, 0);
227                 r.read_exact(&mut ret)?;
228                 Ok(ret)
229         }
230 }
231 impl Writeable for Vec<Signature> {
232         #[inline]
233         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
234                 (self.len() as u16).write(w)?;
235                 for e in self.iter() {
236                         e.write(w)?;
237                 }
238                 Ok(())
239         }
240 }
241
242 impl<R: Read> Readable<R> for Vec<Signature> {
243         #[inline]
244         fn read(r: &mut R) -> Result<Self, DecodeError> {
245                 let len: u16 = Readable::read(r)?;
246                 let byte_size = (len as usize)
247                                 .checked_mul(33)
248                                 .ok_or(DecodeError::BadLengthDescriptor)?;
249                 if byte_size > MAX_BUF_SIZE {
250                         return Err(DecodeError::BadLengthDescriptor);
251                 }
252                 let mut ret = Vec::with_capacity(len as usize);
253                 for _ in 0..len { ret.push(Signature::read(r)?); }
254                 Ok(ret)
255         }
256 }
257
258 impl Writeable for Script {
259         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
260                 (self.len() as u16).write(w)?;
261                 w.write_all(self.as_bytes())
262         }
263 }
264
265 impl<R: Read> Readable<R> for Script {
266         fn read(r: &mut R) -> Result<Self, DecodeError> {
267                 let len = <u16 as Readable<R>>::read(r)? as usize;
268                 let mut buf = vec![0; len];
269                 r.read_exact(&mut buf)?;
270                 Ok(Script::from(buf))
271         }
272 }
273
274 impl Writeable for Option<Script> {
275         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
276                 if let &Some(ref script) = self {
277                         script.write(w)?;
278                 }
279                 Ok(())
280         }
281 }
282
283 impl<R: Read> Readable<R> for Option<Script> {
284         fn read(r: &mut R) -> Result<Self, DecodeError> {
285                 match <u16 as Readable<R>>::read(r) {
286                         Ok(len) => {
287                                 let mut buf = vec![0; len as usize];
288                                 r.read_exact(&mut buf)?;
289                                 Ok(Some(Script::from(buf)))
290                         },
291                         Err(DecodeError::ShortRead) => Ok(None),
292                         Err(e) => Err(e)
293                 }
294         }
295 }
296
297 impl Writeable for PublicKey {
298         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
299                 self.serialize().write(w)
300         }
301 }
302
303 impl<R: Read> Readable<R> for PublicKey {
304         fn read(r: &mut R) -> Result<Self, DecodeError> {
305                 let buf: [u8; 33] = Readable::read(r)?;
306                 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
307                         Ok(key) => Ok(key),
308                         Err(_) => return Err(DecodeError::InvalidValue),
309                 }
310         }
311 }
312
313 impl Writeable for Sha256dHash {
314         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
315                 self.as_bytes().write(w)
316         }
317 }
318
319 impl<R: Read> Readable<R> for Sha256dHash {
320         fn read(r: &mut R) -> Result<Self, DecodeError> {
321                 let buf: [u8; 32] = Readable::read(r)?;
322                 Ok(From::from(&buf[..]))
323         }
324 }
325
326 impl Writeable for Signature {
327         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
328                 self.serialize_compact(&Secp256k1::without_caps()).write(w)
329         }
330 }
331
332 impl<R: Read> Readable<R> for Signature {
333         fn read(r: &mut R) -> Result<Self, DecodeError> {
334                 let buf: [u8; 64] = Readable::read(r)?;
335                 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
336                         Ok(sig) => Ok(sig),
337                         Err(_) => return Err(DecodeError::InvalidValue),
338                 }
339         }
340 }