1 //! A very simple serialization framework which is used to serialize/deserialize messages as well
2 //! as ChannelsManagers and ChannelMonitors.
4 use std::result::Result;
5 use std::io::{Read, Write};
6 use std::collections::HashMap;
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};
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};
23 const MAX_BUF_SIZE: usize = 64 * 1024;
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
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);
37 impl<W: Write> Writer for W {
39 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
40 <Self as ::std::io::Write>::write_all(self, buf)
43 fn size_hint(&mut self, _size: usize) { }
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> {
51 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
52 self.0.write_all(buf)?;
55 fn flush(&mut self) -> Result<(), ::std::io::Error> {
60 pub(crate) struct VecWriter(pub 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);
66 fn size_hint(&mut self, size: usize) {
67 self.0.reserve_exact(size);
71 pub(crate) struct LengthCalculatingWriter(pub usize);
72 impl Writer for LengthCalculatingWriter {
74 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
79 fn size_hint(&mut self, _size: usize) {}
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> {
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 }
94 pub fn bytes_remain(&mut self) -> bool {
95 self.bytes_read != self.total_fixed_len
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)
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 {
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)]) {
115 self.bytes_read += v as u64;
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> {
130 impl<R: Read> ReadTrackingReader<R> {
131 pub fn new(read: R) -> Self {
132 Self { read, have_read: false }
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) {
140 self.have_read = true;
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>;
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();
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));
171 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
172 pub trait Readable<R>
176 /// Reads a Self in from the given Read
177 fn read(reader: &mut R) -> Result<Self, DecodeError>;
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>
186 /// Reads a Self in from the given Read
187 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
190 pub(crate) struct U48(pub u64);
191 impl Writeable for U48 {
193 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
194 writer.write_all(&be48_to_array(self.0))
197 impl<R: Read> Readable<R> for U48 {
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)))
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.
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 {
216 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
219 (self.0 as u8).write(writer)
222 0xFDu8.write(writer)?;
223 (self.0 as u16).write(writer)
225 0x10000...0xFFFFFFFF => {
226 0xFEu8.write(writer)?;
227 (self.0 as u32).write(writer)
230 0xFFu8.write(writer)?;
231 (self.0 as u64).write(writer)
236 impl<R: Read> Readable<R> for BigSize {
238 fn read(reader: &mut R) -> Result<BigSize, DecodeError> {
239 let n: u8 = Readable::read(reader)?;
242 let x: u64 = Readable::read(reader)?;
244 Err(DecodeError::InvalidValue)
250 let x: u32 = Readable::read(reader)?;
252 Err(DecodeError::InvalidValue)
254 Ok(BigSize(x as u64))
258 let x: u16 = Readable::read(reader)?;
260 Err(DecodeError::InvalidValue)
262 Ok(BigSize(x as u64))
265 n => Ok(BigSize(n as u64))
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);
276 macro_rules! impl_writeable_primitive {
277 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
278 impl Writeable for $val_type {
280 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
281 writer.write_all(&$meth_write(*self))
284 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
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])
291 impl<R: Read> Readable<R> for $val_type {
293 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
294 let mut buf = [0; $len];
295 reader.read_exact(&mut buf)?;
299 impl<R: Read> Readable<R> for HighZeroBytesDroppedVarInt<$val_type> {
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
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;
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])))
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)
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);
330 impl Writeable for u8 {
332 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
333 writer.write_all(&[*self])
336 impl<R: Read> Readable<R> for u8 {
338 fn read(reader: &mut R) -> Result<u8, DecodeError> {
339 let mut buf = [0; 1];
340 reader.read_exact(&mut buf)?;
345 impl Writeable for bool {
347 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
348 writer.write_all(&[if *self {1} else {0}])
351 impl<R: Read> Readable<R> for bool {
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);
364 macro_rules! impl_array {
366 impl Writeable for [u8; $size]
369 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
374 impl<R: Read> Readable<R> for [u8; $size]
377 fn read(r: &mut R) -> Result<Self, DecodeError> {
378 let mut buf = [0u8; $size];
379 r.read_exact(&mut buf)?;
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
397 impl<K, V> Writeable for HashMap<K, V>
398 where K: Writeable + Eq + Hash,
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() {
412 impl<R, K, V> Readable<R> for HashMap<K, V>
414 K: Readable<R> + Eq + Hash,
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);
422 ret.insert(K::read(r)?, V::read(r)?);
429 impl Writeable for Vec<u8> {
431 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
432 (self.len() as u16).write(w)?;
437 impl<R: Read> Readable<R> for Vec<u8> {
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)?;
447 impl Writeable for Vec<Signature> {
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() {
458 impl<R: Read> Readable<R> for Vec<Signature> {
460 fn read(r: &mut R) -> Result<Self, DecodeError> {
461 let len: u16 = Readable::read(r)?;
462 let byte_size = (len as usize)
464 .ok_or(DecodeError::BadLengthDescriptor)?;
465 if byte_size > MAX_BUF_SIZE {
466 return Err(DecodeError::BadLengthDescriptor);
468 let mut ret = Vec::with_capacity(len as usize);
469 for _ in 0..len { ret.push(Signature::read(r)?); }
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())
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))
490 impl Writeable for PublicKey {
491 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
492 self.serialize().write(w)
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) {
501 Err(_) => return Err(DecodeError::InvalidValue),
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[..]);
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) {
519 Err(_) => return Err(DecodeError::InvalidValue),
524 impl Writeable for Sha256dHash {
525 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
526 w.write_all(&self[..])
530 impl<R: Read> Readable<R> for Sha256dHash {
531 fn read(r: &mut R) -> Result<Self, DecodeError> {
532 use bitcoin_hashes::Hash;
534 let buf: [u8; 32] = Readable::read(r)?;
535 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
539 impl Writeable for Signature {
540 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
541 self.serialize_compact().write(w)
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) {
550 Err(_) => return Err(DecodeError::InvalidValue),
555 impl Writeable for PaymentPreimage {
556 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
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))
568 impl Writeable for PaymentHash {
569 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
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)?;
581 impl<T: Writeable> Writeable for Option<T> {
582 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
584 None => 0u8.write(w)?,
594 impl<R, T> Readable<R> for Option<T>
598 fn read(r: &mut R) -> Result<Self, DecodeError> {
599 match <u8 as Readable<R>>::read(r)? {
601 1 => Ok(Some(Readable::read(r)?)),
602 _ => return Err(DecodeError::InvalidValue),
607 impl Writeable for OutPoint {
608 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
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)?;
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)?;
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)
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)?;
645 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
646 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {