84cfa8d1633f98e78a996792d53c146d981be61a
[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, Write};
6 use std::collections::HashMap;
7 use std::hash::Hash;
8
9 use secp256k1::{Secp256k1, Signature};
10 use secp256k1::key::{PublicKey, SecretKey};
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, be48_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be48, 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: 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 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
43 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
44         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
45                 self.0.write_all(buf)
46         }
47         fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
48                 self.0.write_all(buf)?;
49                 Ok(buf.len())
50         }
51         fn flush(&mut self) -> Result<(), ::std::io::Error> {
52                 Ok(())
53         }
54 }
55
56 struct VecWriter(Vec<u8>);
57 impl Writer for VecWriter {
58         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
59                 self.0.extend_from_slice(buf);
60                 Ok(())
61         }
62         fn size_hint(&mut self, size: usize) {
63                 self.0.reserve_exact(size);
64         }
65 }
66
67 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
68 pub trait Writeable {
69         /// Writes self out to the given Writer
70         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
71
72         /// Writes self out to a Vec<u8>
73         fn encode(&self) -> Vec<u8> {
74                 let mut msg = VecWriter(Vec::new());
75                 self.write(&mut msg).unwrap();
76                 msg.0
77         }
78
79         /// Writes self out to a Vec<u8>
80         fn encode_with_len(&self) -> Vec<u8> {
81                 let mut msg = VecWriter(Vec::new());
82                 0u16.write(&mut msg).unwrap();
83                 self.write(&mut msg).unwrap();
84                 let len = msg.0.len();
85                 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
86                 msg.0
87         }
88 }
89
90 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
91 pub trait Readable<R>
92         where Self: Sized,
93               R: Read
94 {
95         /// Reads a Self in from the given Read
96         fn read(reader: &mut R) -> Result<Self, DecodeError>;
97 }
98
99 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
100 /// from a Read given some additional set of arguments which is required to deserialize.
101 pub trait ReadableArgs<R, P>
102         where Self: Sized,
103               R: Read
104 {
105         /// Reads a Self in from the given Read
106         fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
107 }
108
109 pub(crate) struct U48(pub u64);
110 impl Writeable for U48 {
111         #[inline]
112         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
113                 writer.write_all(&be48_to_array(self.0))
114         }
115 }
116 impl<R: Read> Readable<R> for U48 {
117         #[inline]
118         fn read(reader: &mut R) -> Result<U48, DecodeError> {
119                 let mut buf = [0; 6];
120                 reader.read_exact(&mut buf)?;
121                 Ok(U48(slice_to_be48(&buf)))
122         }
123 }
124
125 macro_rules! impl_writeable_primitive {
126         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
127                 impl Writeable for $val_type {
128                         #[inline]
129                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
130                                 writer.write_all(&$meth_write(*self))
131                         }
132                 }
133                 impl<R: Read> Readable<R> for $val_type {
134                         #[inline]
135                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
136                                 let mut buf = [0; $len];
137                                 reader.read_exact(&mut buf)?;
138                                 Ok($meth_read(&buf))
139                         }
140                 }
141         }
142 }
143
144 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
145 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
146 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
147
148 impl Writeable for u8 {
149         #[inline]
150         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
151                 writer.write_all(&[*self])
152         }
153 }
154 impl<R: Read> Readable<R> for u8 {
155         #[inline]
156         fn read(reader: &mut R) -> Result<u8, DecodeError> {
157                 let mut buf = [0; 1];
158                 reader.read_exact(&mut buf)?;
159                 Ok(buf[0])
160         }
161 }
162
163 impl Writeable for bool {
164         #[inline]
165         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
166                 writer.write_all(&[if *self {1} else {0}])
167         }
168 }
169 impl<R: Read> Readable<R> for bool {
170         #[inline]
171         fn read(reader: &mut R) -> Result<bool, DecodeError> {
172                 let mut buf = [0; 1];
173                 reader.read_exact(&mut buf)?;
174                 if buf[0] != 0 && buf[0] != 1 {
175                         return Err(DecodeError::InvalidValue);
176                 }
177                 Ok(buf[0] == 1)
178         }
179 }
180
181 // u8 arrays
182 macro_rules! impl_array {
183         ( $size:expr ) => (
184                 impl Writeable for [u8; $size]
185                 {
186                         #[inline]
187                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
188                                 w.write_all(self)
189                         }
190                 }
191
192                 impl<R: Read> Readable<R> for [u8; $size]
193                 {
194                         #[inline]
195                         fn read(r: &mut R) -> Result<Self, DecodeError> {
196                                 let mut buf = [0u8; $size];
197                                 r.read_exact(&mut buf)?;
198                                 Ok(buf)
199                         }
200                 }
201         );
202 }
203
204 //TODO: performance issue with [u8; size] with impl_array!()
205 impl_array!(32); // for channel id & hmac
206 impl_array!(33); // for PublicKey
207 impl_array!(64); // for Signature
208 impl_array!(1300); // for OnionPacket.hop_data
209
210 // HashMap
211 impl<K, V> Writeable for HashMap<K, V>
212         where K: Writeable + Eq + Hash,
213               V: Writeable
214 {
215         #[inline]
216         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
217         (self.len() as u16).write(w)?;
218                 for (key, value) in self.iter() {
219                         key.write(w)?;
220                         value.write(w)?;
221                 }
222                 Ok(())
223         }
224 }
225
226 impl<R, K, V> Readable<R> for HashMap<K, V>
227         where R: Read,
228               K: Readable<R> + Eq + Hash,
229               V: Readable<R>
230 {
231         #[inline]
232         fn read(r: &mut R) -> Result<Self, DecodeError> {
233                 let len: u16 = Readable::read(r)?;
234                 let mut ret = HashMap::with_capacity(len as usize);
235                 for _ in 0..len {
236                         ret.insert(K::read(r)?, V::read(r)?);
237                 }
238                 Ok(ret)
239         }
240 }
241
242 // Vectors
243 impl Writeable for Vec<u8> {
244         #[inline]
245         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
246                 (self.len() as u16).write(w)?;
247                 w.write_all(&self)
248         }
249 }
250
251 impl<R: Read> Readable<R> for Vec<u8> {
252         #[inline]
253         fn read(r: &mut R) -> Result<Self, DecodeError> {
254                 let len: u16 = Readable::read(r)?;
255                 let mut ret = Vec::with_capacity(len as usize);
256                 ret.resize(len as usize, 0);
257                 r.read_exact(&mut ret)?;
258                 Ok(ret)
259         }
260 }
261 impl Writeable for Vec<Signature> {
262         #[inline]
263         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
264                 (self.len() as u16).write(w)?;
265                 for e in self.iter() {
266                         e.write(w)?;
267                 }
268                 Ok(())
269         }
270 }
271
272 impl<R: Read> Readable<R> for Vec<Signature> {
273         #[inline]
274         fn read(r: &mut R) -> Result<Self, DecodeError> {
275                 let len: u16 = Readable::read(r)?;
276                 let byte_size = (len as usize)
277                                 .checked_mul(33)
278                                 .ok_or(DecodeError::BadLengthDescriptor)?;
279                 if byte_size > MAX_BUF_SIZE {
280                         return Err(DecodeError::BadLengthDescriptor);
281                 }
282                 let mut ret = Vec::with_capacity(len as usize);
283                 for _ in 0..len { ret.push(Signature::read(r)?); }
284                 Ok(ret)
285         }
286 }
287
288 impl Writeable for Script {
289         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
290                 (self.len() as u16).write(w)?;
291                 w.write_all(self.as_bytes())
292         }
293 }
294
295 impl<R: Read> Readable<R> for Script {
296         fn read(r: &mut R) -> Result<Self, DecodeError> {
297                 let len = <u16 as Readable<R>>::read(r)? as usize;
298                 let mut buf = vec![0; len];
299                 r.read_exact(&mut buf)?;
300                 Ok(Script::from(buf))
301         }
302 }
303
304 impl Writeable for Option<Script> {
305         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
306                 if let &Some(ref script) = self {
307                         script.write(w)?;
308                 }
309                 Ok(())
310         }
311 }
312
313 impl<R: Read> Readable<R> for Option<Script> {
314         fn read(r: &mut R) -> Result<Self, DecodeError> {
315                 match <u16 as Readable<R>>::read(r) {
316                         Ok(len) => {
317                                 let mut buf = vec![0; len as usize];
318                                 r.read_exact(&mut buf)?;
319                                 Ok(Some(Script::from(buf)))
320                         },
321                         Err(DecodeError::ShortRead) => Ok(None),
322                         Err(e) => Err(e)
323                 }
324         }
325 }
326
327 impl Writeable for PublicKey {
328         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
329                 self.serialize().write(w)
330         }
331 }
332
333 impl<R: Read> Readable<R> for PublicKey {
334         fn read(r: &mut R) -> Result<Self, DecodeError> {
335                 let buf: [u8; 33] = Readable::read(r)?;
336                 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
337                         Ok(key) => Ok(key),
338                         Err(_) => return Err(DecodeError::InvalidValue),
339                 }
340         }
341 }
342
343 impl Writeable for SecretKey {
344         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
345                 let mut ser = [0; 32];
346                 ser.copy_from_slice(&self[..]);
347                 ser.write(w)
348         }
349 }
350
351 impl<R: Read> Readable<R> for SecretKey {
352         fn read(r: &mut R) -> Result<Self, DecodeError> {
353                 let buf: [u8; 32] = Readable::read(r)?;
354                 match SecretKey::from_slice(&Secp256k1::without_caps(), &buf) {
355                         Ok(key) => Ok(key),
356                         Err(_) => return Err(DecodeError::InvalidValue),
357                 }
358         }
359 }
360
361 impl Writeable for Sha256dHash {
362         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
363                 self.as_bytes().write(w)
364         }
365 }
366
367 impl<R: Read> Readable<R> for Sha256dHash {
368         fn read(r: &mut R) -> Result<Self, DecodeError> {
369                 let buf: [u8; 32] = Readable::read(r)?;
370                 Ok(From::from(&buf[..]))
371         }
372 }
373
374 impl Writeable for Signature {
375         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
376                 self.serialize_compact(&Secp256k1::without_caps()).write(w)
377         }
378 }
379
380 impl<R: Read> Readable<R> for Signature {
381         fn read(r: &mut R) -> Result<Self, DecodeError> {
382                 let buf: [u8; 64] = Readable::read(r)?;
383                 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
384                         Ok(sig) => Ok(sig),
385                         Err(_) => return Err(DecodeError::InvalidValue),
386                 }
387         }
388 }