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