Add new streams and serialization wrappers for TLV types.
[rust-lightning] / 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 use std::sync::Mutex;
9 use std::cmp;
10
11 use secp256k1::Signature;
12 use secp256k1::key::{PublicKey, SecretKey};
13 use bitcoin::blockdata::script::Script;
14 use bitcoin::blockdata::transaction::OutPoint;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16 use std::marker::Sized;
17 use ln::msgs::DecodeError;
18 use ln::channelmanager::{PaymentPreimage, PaymentHash};
19 use util::byte_utils;
20
21 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};
22
23 const MAX_BUF_SIZE: usize = 64 * 1024;
24
25 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
26 /// buffers being written into.
27 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
28 /// hints.
29 pub trait Writer {
30         /// Writes the given buf out. See std::io::Write::write_all for more
31         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
32         /// Hints that data of the given size is about the be written. This may not always be called
33         /// prior to data being written and may be safely ignored.
34         fn size_hint(&mut self, size: usize);
35 }
36
37 impl<W: Write> Writer for W {
38         #[inline]
39         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
40                 <Self as ::std::io::Write>::write_all(self, buf)
41         }
42         #[inline]
43         fn size_hint(&mut self, _size: usize) { }
44 }
45
46 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
47 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
48         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
49                 self.0.write_all(buf)
50         }
51         fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
52                 self.0.write_all(buf)?;
53                 Ok(buf.len())
54         }
55         fn flush(&mut self) -> Result<(), ::std::io::Error> {
56                 Ok(())
57         }
58 }
59
60 struct VecWriter(Vec<u8>);
61 impl Writer for VecWriter {
62         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
63                 self.0.extend_from_slice(buf);
64                 Ok(())
65         }
66         fn size_hint(&mut self, size: usize) {
67                 self.0.reserve_exact(size);
68         }
69 }
70
71 pub(crate) struct LengthCalculatingWriter(pub usize);
72 impl Writer for LengthCalculatingWriter {
73         #[inline]
74         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
75                 self.0 += buf.len();
76                 Ok(())
77         }
78         #[inline]
79         fn size_hint(&mut self, _size: usize) {}
80 }
81
82 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
83 /// forward to ensure we always consume exactly the fixed length specified.
84 pub(crate) struct FixedLengthReader<R: Read> {
85         read: R,
86         bytes_read: u64,
87         total_fixed_len: u64,
88 }
89 impl<R: Read> FixedLengthReader<R> {
90         pub fn new(read: R, total_fixed_len: u64) -> Self {
91                 Self { read, bytes_read: 0, total_fixed_len }
92         }
93
94         pub fn bytes_remain(&mut self) -> bool {
95                 self.bytes_read != self.total_fixed_len
96         }
97
98         pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
99                 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
100                 if self.bytes_read != self.total_fixed_len {
101                         Err(DecodeError::ShortRead)
102                 } else {
103                         Ok(())
104                 }
105         }
106 }
107 impl<R: Read> Read for FixedLengthReader<R> {
108         fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
109                 if self.total_fixed_len == self.bytes_read {
110                         Ok(0)
111                 } else {
112                         let read_len = cmp::min(dest.len() as u64, self.total_fixed_len - self.bytes_read);
113                         match self.read.read(&mut dest[0..(read_len as usize)]) {
114                                 Ok(v) => {
115                                         self.bytes_read += v as u64;
116                                         Ok(v)
117                                 },
118                                 Err(e) => Err(e),
119                         }
120                 }
121         }
122 }
123
124 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
125 /// between "EOF reached before we started" and "EOF reached mid-read".
126 pub(crate) struct ReadTrackingReader<R: Read> {
127         read: R,
128         pub have_read: bool,
129 }
130 impl<R: Read> ReadTrackingReader<R> {
131         pub fn new(read: R) -> Self {
132                 Self { read, have_read: false }
133         }
134 }
135 impl<R: Read> Read for ReadTrackingReader<R> {
136         fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
137                 match self.read.read(dest) {
138                         Ok(0) => Ok(0),
139                         Ok(len) => {
140                                 self.have_read = true;
141                                 Ok(len)
142                         },
143                         Err(e) => Err(e),
144                 }
145         }
146 }
147
148 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
149 pub trait Writeable {
150         /// Writes self out to the given Writer
151         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
152
153         /// Writes self out to a Vec<u8>
154         fn encode(&self) -> Vec<u8> {
155                 let mut msg = VecWriter(Vec::new());
156                 self.write(&mut msg).unwrap();
157                 msg.0
158         }
159
160         /// Writes self out to a Vec<u8>
161         fn encode_with_len(&self) -> Vec<u8> {
162                 let mut msg = VecWriter(Vec::new());
163                 0u16.write(&mut msg).unwrap();
164                 self.write(&mut msg).unwrap();
165                 let len = msg.0.len();
166                 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
167                 msg.0
168         }
169 }
170
171 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
172 pub trait Readable<R>
173         where Self: Sized,
174               R: Read
175 {
176         /// Reads a Self in from the given Read
177         fn read(reader: &mut R) -> Result<Self, DecodeError>;
178 }
179
180 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
181 /// from a Read given some additional set of arguments which is required to deserialize.
182 pub trait ReadableArgs<R, P>
183         where Self: Sized,
184               R: Read
185 {
186         /// Reads a Self in from the given Read
187         fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
188 }
189
190 pub(crate) struct U48(pub u64);
191 impl Writeable for U48 {
192         #[inline]
193         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
194                 writer.write_all(&be48_to_array(self.0))
195         }
196 }
197 impl<R: Read> Readable<R> for U48 {
198         #[inline]
199         fn read(reader: &mut R) -> Result<U48, DecodeError> {
200                 let mut buf = [0; 6];
201                 reader.read_exact(&mut buf)?;
202                 Ok(U48(slice_to_be48(&buf)))
203         }
204 }
205
206 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
207 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
208 ///
209 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
210 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
211 /// you're looking for an example of a variable-length integer to use for your own project, move
212 /// along, this is a rather poor design.
213 pub(crate) struct BigSize(pub u64);
214 impl Writeable for BigSize {
215         #[inline]
216         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
217                 match self.0 {
218                         0...0xFC => {
219                                 (self.0 as u8).write(writer)
220                         },
221                         0xFD...0xFFFF => {
222                                 0xFDu8.write(writer)?;
223                                 (self.0 as u16).write(writer)
224                         },
225                         0x10000...0xFFFFFFFF => {
226                                 0xFEu8.write(writer)?;
227                                 (self.0 as u32).write(writer)
228                         },
229                         _ => {
230                                 0xFFu8.write(writer)?;
231                                 (self.0 as u64).write(writer)
232                         },
233                 }
234         }
235 }
236 impl<R: Read> Readable<R> for BigSize {
237         #[inline]
238         fn read(reader: &mut R) -> Result<BigSize, DecodeError> {
239                 let n: u8 = Readable::read(reader)?;
240                 match n {
241                         0xFF => {
242                                 let x: u64 = Readable::read(reader)?;
243                                 if x < 0x100000000 {
244                                         Err(DecodeError::InvalidValue)
245                                 } else {
246                                         Ok(BigSize(x))
247                                 }
248                         }
249                         0xFE => {
250                                 let x: u32 = Readable::read(reader)?;
251                                 if x < 0x10000 {
252                                         Err(DecodeError::InvalidValue)
253                                 } else {
254                                         Ok(BigSize(x as u64))
255                                 }
256                         }
257                         0xFD => {
258                                 let x: u16 = Readable::read(reader)?;
259                                 if x < 0xFD {
260                                         Err(DecodeError::InvalidValue)
261                                 } else {
262                                         Ok(BigSize(x as u64))
263                                 }
264                         }
265                         n => Ok(BigSize(n as u64))
266                 }
267         }
268 }
269
270 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
271 /// variabe-length integer which is simply truncated by skipping high zero bytes. This type
272 /// encapsulates such integers implementing Readable/Writeable for them.
273 #[cfg_attr(test, derive(PartialEq, Debug))]
274 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
275
276 macro_rules! impl_writeable_primitive {
277         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
278                 impl Writeable for $val_type {
279                         #[inline]
280                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
281                                 writer.write_all(&$meth_write(*self))
282                         }
283                 }
284                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
285                         #[inline]
286                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
287                                 // Skip any full leading 0 bytes when writing (in BE):
288                                 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
289                         }
290                 }
291                 impl<R: Read> Readable<R> for $val_type {
292                         #[inline]
293                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
294                                 let mut buf = [0; $len];
295                                 reader.read_exact(&mut buf)?;
296                                 Ok($meth_read(&buf))
297                         }
298                 }
299                 impl<R: Read> Readable<R> for HighZeroBytesDroppedVarInt<$val_type> {
300                         #[inline]
301                         fn read(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
302                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
303                                 // the high bytes being dropped. To do so, we start reading in the middle of buf
304                                 // and then convert the appropriate number of bytes with extra high bytes out of
305                                 // buf.
306                                 let mut buf = [0; $len*2];
307                                 let mut read_len = reader.read(&mut buf[$len..])?;
308                                 let mut total_read_len = read_len;
309                                 while read_len != 0 && total_read_len != $len {
310                                         read_len = reader.read(&mut buf[($len + read_len)..])?;
311                                         total_read_len += read_len;
312                                 }
313                                 if total_read_len == 0 || buf[$len] != 0 {
314                                         let first_byte = $len - ($len - total_read_len);
315                                         Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
316                                 } else {
317                                         // If the encoding had extra zero bytes, return a failure even though we know
318                                         // what they meant (as the TLV test vectors require this)
319                                         Err(DecodeError::InvalidValue)
320                                 }
321                         }
322                 }
323         }
324 }
325
326 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
327 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
328 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
329
330 impl Writeable for u8 {
331         #[inline]
332         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
333                 writer.write_all(&[*self])
334         }
335 }
336 impl<R: Read> Readable<R> for u8 {
337         #[inline]
338         fn read(reader: &mut R) -> Result<u8, DecodeError> {
339                 let mut buf = [0; 1];
340                 reader.read_exact(&mut buf)?;
341                 Ok(buf[0])
342         }
343 }
344
345 impl Writeable for bool {
346         #[inline]
347         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
348                 writer.write_all(&[if *self {1} else {0}])
349         }
350 }
351 impl<R: Read> Readable<R> for bool {
352         #[inline]
353         fn read(reader: &mut R) -> Result<bool, DecodeError> {
354                 let mut buf = [0; 1];
355                 reader.read_exact(&mut buf)?;
356                 if buf[0] != 0 && buf[0] != 1 {
357                         return Err(DecodeError::InvalidValue);
358                 }
359                 Ok(buf[0] == 1)
360         }
361 }
362
363 // u8 arrays
364 macro_rules! impl_array {
365         ( $size:expr ) => (
366                 impl Writeable for [u8; $size]
367                 {
368                         #[inline]
369                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
370                                 w.write_all(self)
371                         }
372                 }
373
374                 impl<R: Read> Readable<R> for [u8; $size]
375                 {
376                         #[inline]
377                         fn read(r: &mut R) -> Result<Self, DecodeError> {
378                                 let mut buf = [0u8; $size];
379                                 r.read_exact(&mut buf)?;
380                                 Ok(buf)
381                         }
382                 }
383         );
384 }
385
386 //TODO: performance issue with [u8; size] with impl_array!()
387 impl_array!(3); // for rgb
388 impl_array!(4); // for IPv4
389 impl_array!(10); // for OnionV2
390 impl_array!(16); // for IPv6
391 impl_array!(32); // for channel id & hmac
392 impl_array!(33); // for PublicKey
393 impl_array!(64); // for Signature
394 impl_array!(1300); // for OnionPacket.hop_data
395
396 // HashMap
397 impl<K, V> Writeable for HashMap<K, V>
398         where K: Writeable + Eq + Hash,
399               V: Writeable
400 {
401         #[inline]
402         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
403         (self.len() as u16).write(w)?;
404                 for (key, value) in self.iter() {
405                         key.write(w)?;
406                         value.write(w)?;
407                 }
408                 Ok(())
409         }
410 }
411
412 impl<R, K, V> Readable<R> for HashMap<K, V>
413         where R: Read,
414               K: Readable<R> + Eq + Hash,
415               V: Readable<R>
416 {
417         #[inline]
418         fn read(r: &mut R) -> Result<Self, DecodeError> {
419                 let len: u16 = Readable::read(r)?;
420                 let mut ret = HashMap::with_capacity(len as usize);
421                 for _ in 0..len {
422                         ret.insert(K::read(r)?, V::read(r)?);
423                 }
424                 Ok(ret)
425         }
426 }
427
428 // Vectors
429 impl Writeable for Vec<u8> {
430         #[inline]
431         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
432                 (self.len() as u16).write(w)?;
433                 w.write_all(&self)
434         }
435 }
436
437 impl<R: Read> Readable<R> for Vec<u8> {
438         #[inline]
439         fn read(r: &mut R) -> Result<Self, DecodeError> {
440                 let len: u16 = Readable::read(r)?;
441                 let mut ret = Vec::with_capacity(len as usize);
442                 ret.resize(len as usize, 0);
443                 r.read_exact(&mut ret)?;
444                 Ok(ret)
445         }
446 }
447 impl Writeable for Vec<Signature> {
448         #[inline]
449         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
450                 (self.len() as u16).write(w)?;
451                 for e in self.iter() {
452                         e.write(w)?;
453                 }
454                 Ok(())
455         }
456 }
457
458 impl<R: Read> Readable<R> for Vec<Signature> {
459         #[inline]
460         fn read(r: &mut R) -> Result<Self, DecodeError> {
461                 let len: u16 = Readable::read(r)?;
462                 let byte_size = (len as usize)
463                                 .checked_mul(33)
464                                 .ok_or(DecodeError::BadLengthDescriptor)?;
465                 if byte_size > MAX_BUF_SIZE {
466                         return Err(DecodeError::BadLengthDescriptor);
467                 }
468                 let mut ret = Vec::with_capacity(len as usize);
469                 for _ in 0..len { ret.push(Signature::read(r)?); }
470                 Ok(ret)
471         }
472 }
473
474 impl Writeable for Script {
475         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
476                 (self.len() as u16).write(w)?;
477                 w.write_all(self.as_bytes())
478         }
479 }
480
481 impl<R: Read> Readable<R> for Script {
482         fn read(r: &mut R) -> Result<Self, DecodeError> {
483                 let len = <u16 as Readable<R>>::read(r)? as usize;
484                 let mut buf = vec![0; len];
485                 r.read_exact(&mut buf)?;
486                 Ok(Script::from(buf))
487         }
488 }
489
490 impl Writeable for PublicKey {
491         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
492                 self.serialize().write(w)
493         }
494 }
495
496 impl<R: Read> Readable<R> for PublicKey {
497         fn read(r: &mut R) -> Result<Self, DecodeError> {
498                 let buf: [u8; 33] = Readable::read(r)?;
499                 match PublicKey::from_slice(&buf) {
500                         Ok(key) => Ok(key),
501                         Err(_) => return Err(DecodeError::InvalidValue),
502                 }
503         }
504 }
505
506 impl Writeable for SecretKey {
507         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
508                 let mut ser = [0; 32];
509                 ser.copy_from_slice(&self[..]);
510                 ser.write(w)
511         }
512 }
513
514 impl<R: Read> Readable<R> for SecretKey {
515         fn read(r: &mut R) -> Result<Self, DecodeError> {
516                 let buf: [u8; 32] = Readable::read(r)?;
517                 match SecretKey::from_slice(&buf) {
518                         Ok(key) => Ok(key),
519                         Err(_) => return Err(DecodeError::InvalidValue),
520                 }
521         }
522 }
523
524 impl Writeable for Sha256dHash {
525         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
526                 w.write_all(&self[..])
527         }
528 }
529
530 impl<R: Read> Readable<R> for Sha256dHash {
531         fn read(r: &mut R) -> Result<Self, DecodeError> {
532                 use bitcoin_hashes::Hash;
533
534                 let buf: [u8; 32] = Readable::read(r)?;
535                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
536         }
537 }
538
539 impl Writeable for Signature {
540         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
541                 self.serialize_compact().write(w)
542         }
543 }
544
545 impl<R: Read> Readable<R> for Signature {
546         fn read(r: &mut R) -> Result<Self, DecodeError> {
547                 let buf: [u8; 64] = Readable::read(r)?;
548                 match Signature::from_compact(&buf) {
549                         Ok(sig) => Ok(sig),
550                         Err(_) => return Err(DecodeError::InvalidValue),
551                 }
552         }
553 }
554
555 impl Writeable for PaymentPreimage {
556         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
557                 self.0.write(w)
558         }
559 }
560
561 impl<R: Read> Readable<R> for PaymentPreimage {
562         fn read(r: &mut R) -> Result<Self, DecodeError> {
563                 let buf: [u8; 32] = Readable::read(r)?;
564                 Ok(PaymentPreimage(buf))
565         }
566 }
567
568 impl Writeable for PaymentHash {
569         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
570                 self.0.write(w)
571         }
572 }
573
574 impl<R: Read> Readable<R> for PaymentHash {
575         fn read(r: &mut R) -> Result<Self, DecodeError> {
576                 let buf: [u8; 32] = Readable::read(r)?;
577                 Ok(PaymentHash(buf))
578         }
579 }
580
581 impl<T: Writeable> Writeable for Option<T> {
582         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
583                 match *self {
584                         None => 0u8.write(w)?,
585                         Some(ref data) => {
586                                 1u8.write(w)?;
587                                 data.write(w)?;
588                         }
589                 }
590                 Ok(())
591         }
592 }
593
594 impl<R, T> Readable<R> for Option<T>
595         where R: Read,
596               T: Readable<R>
597 {
598         fn read(r: &mut R) -> Result<Self, DecodeError> {
599                 match <u8 as Readable<R>>::read(r)? {
600                         0 => Ok(None),
601                         1 => Ok(Some(Readable::read(r)?)),
602                         _ => return Err(DecodeError::InvalidValue),
603                 }
604         }
605 }
606
607 impl Writeable for OutPoint {
608         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
609                 self.txid.write(w)?;
610                 self.vout.write(w)?;
611                 Ok(())
612         }
613 }
614
615 impl<R: Read> Readable<R> for OutPoint {
616         fn read(r: &mut R) -> Result<Self, DecodeError> {
617                 let txid = Readable::read(r)?;
618                 let vout = Readable::read(r)?;
619                 Ok(OutPoint {
620                         txid,
621                         vout,
622                 })
623         }
624 }
625
626 impl<R: Read, T: Readable<R>> Readable<R> for Mutex<T> {
627         fn read(r: &mut R) -> Result<Self, DecodeError> {
628                 let t: T = Readable::read(r)?;
629                 Ok(Mutex::new(t))
630         }
631 }
632 impl<T: Writeable> Writeable for Mutex<T> {
633         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
634                 self.lock().unwrap().write(w)
635         }
636 }
637
638 impl<R: Read, A: Readable<R>, B: Readable<R>> Readable<R> for (A, B) {
639         fn read(r: &mut R) -> Result<Self, DecodeError> {
640                 let a: A = Readable::read(r)?;
641                 let b: B = Readable::read(r)?;
642                 Ok((a, b))
643         }
644 }
645 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
646         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
647                 self.0.write(w)?;
648                 self.1.write(w)
649         }
650 }