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 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
72 /// of some data when serialized but don't yet need the full data.
73 pub(crate) struct LengthCalculatingWriter(pub usize);
74 impl Writer for LengthCalculatingWriter {
76 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
81 fn size_hint(&mut self, _size: usize) {}
84 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
85 /// forward to ensure we always consume exactly the fixed length specified.
86 pub(crate) struct FixedLengthReader<R: Read> {
91 impl<R: Read> FixedLengthReader<R> {
92 pub fn new(read: R, total_bytes: u64) -> Self {
93 Self { read, bytes_read: 0, total_bytes }
96 pub fn bytes_remain(&mut self) -> bool {
97 self.bytes_read != self.total_bytes
100 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
101 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
102 if self.bytes_read != self.total_bytes {
103 Err(DecodeError::ShortRead)
109 impl<R: Read> Read for FixedLengthReader<R> {
110 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
111 if self.total_bytes == self.bytes_read {
114 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
115 match self.read.read(&mut dest[0..(read_len as usize)]) {
117 self.bytes_read += v as u64;
126 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
127 /// between "EOF reached before we started" and "EOF reached mid-read".
128 pub(crate) struct ReadTrackingReader<R: Read> {
132 impl<R: Read> ReadTrackingReader<R> {
133 pub fn new(read: R) -> Self {
134 Self { read, have_read: false }
137 impl<R: Read> Read for ReadTrackingReader<R> {
138 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
139 match self.read.read(dest) {
142 self.have_read = true;
150 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
151 pub trait Writeable {
152 /// Writes self out to the given Writer
153 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
155 /// Writes self out to a Vec<u8>
156 fn encode(&self) -> Vec<u8> {
157 let mut msg = VecWriter(Vec::new());
158 self.write(&mut msg).unwrap();
162 /// Writes self out to a Vec<u8>
163 fn encode_with_len(&self) -> Vec<u8> {
164 let mut msg = VecWriter(Vec::new());
165 0u16.write(&mut msg).unwrap();
166 self.write(&mut msg).unwrap();
167 let len = msg.0.len();
168 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
173 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
174 pub trait Readable<R>
178 /// Reads a Self in from the given Read
179 fn read(reader: &mut R) -> Result<Self, DecodeError>;
182 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
183 /// from a Read given some additional set of arguments which is required to deserialize.
184 pub trait ReadableArgs<R, P>
188 /// Reads a Self in from the given Read
189 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
192 pub(crate) struct U48(pub u64);
193 impl Writeable for U48 {
195 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
196 writer.write_all(&be48_to_array(self.0))
199 impl<R: Read> Readable<R> for U48 {
201 fn read(reader: &mut R) -> Result<U48, DecodeError> {
202 let mut buf = [0; 6];
203 reader.read_exact(&mut buf)?;
204 Ok(U48(slice_to_be48(&buf)))
208 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
209 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
211 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
212 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
213 /// you're looking for an example of a variable-length integer to use for your own project, move
214 /// along, this is a rather poor design.
215 pub(crate) struct BigSize(pub u64);
216 impl Writeable for BigSize {
218 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
221 (self.0 as u8).write(writer)
224 0xFDu8.write(writer)?;
225 (self.0 as u16).write(writer)
227 0x10000...0xFFFFFFFF => {
228 0xFEu8.write(writer)?;
229 (self.0 as u32).write(writer)
232 0xFFu8.write(writer)?;
233 (self.0 as u64).write(writer)
238 impl<R: Read> Readable<R> for BigSize {
240 fn read(reader: &mut R) -> Result<BigSize, DecodeError> {
241 let n: u8 = Readable::read(reader)?;
244 let x: u64 = Readable::read(reader)?;
246 Err(DecodeError::InvalidValue)
252 let x: u32 = Readable::read(reader)?;
254 Err(DecodeError::InvalidValue)
256 Ok(BigSize(x as u64))
260 let x: u16 = Readable::read(reader)?;
262 Err(DecodeError::InvalidValue)
264 Ok(BigSize(x as u64))
267 n => Ok(BigSize(n as u64))
272 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
273 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
274 /// encapsulates such integers implementing Readable/Writeable for them.
275 #[cfg_attr(test, derive(PartialEq, Debug))]
276 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
278 macro_rules! impl_writeable_primitive {
279 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
280 impl Writeable for $val_type {
282 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
283 writer.write_all(&$meth_write(*self))
286 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
288 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
289 // Skip any full leading 0 bytes when writing (in BE):
290 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
293 impl<R: Read> Readable<R> for $val_type {
295 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
296 let mut buf = [0; $len];
297 reader.read_exact(&mut buf)?;
301 impl<R: Read> Readable<R> for HighZeroBytesDroppedVarInt<$val_type> {
303 fn read(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
304 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
305 // the high bytes being dropped. To do so, we start reading into the middle of buf
306 // and then convert the appropriate number of bytes with extra high bytes out of
308 let mut buf = [0; $len*2];
309 let mut read_len = reader.read(&mut buf[$len..])?;
310 let mut total_read_len = read_len;
311 while read_len != 0 && total_read_len != $len {
312 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
313 total_read_len += read_len;
315 if total_read_len == 0 || buf[$len] != 0 {
316 let first_byte = $len - ($len - total_read_len);
317 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
319 // If the encoding had extra zero bytes, return a failure even though we know
320 // what they meant (as the TLV test vectors require this)
321 Err(DecodeError::InvalidValue)
328 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
329 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
330 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
332 impl Writeable for u8 {
334 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
335 writer.write_all(&[*self])
338 impl<R: Read> Readable<R> for u8 {
340 fn read(reader: &mut R) -> Result<u8, DecodeError> {
341 let mut buf = [0; 1];
342 reader.read_exact(&mut buf)?;
347 impl Writeable for bool {
349 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
350 writer.write_all(&[if *self {1} else {0}])
353 impl<R: Read> Readable<R> for bool {
355 fn read(reader: &mut R) -> Result<bool, DecodeError> {
356 let mut buf = [0; 1];
357 reader.read_exact(&mut buf)?;
358 if buf[0] != 0 && buf[0] != 1 {
359 return Err(DecodeError::InvalidValue);
366 macro_rules! impl_array {
368 impl Writeable for [u8; $size]
371 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
376 impl<R: Read> Readable<R> for [u8; $size]
379 fn read(r: &mut R) -> Result<Self, DecodeError> {
380 let mut buf = [0u8; $size];
381 r.read_exact(&mut buf)?;
388 //TODO: performance issue with [u8; size] with impl_array!()
389 impl_array!(3); // for rgb
390 impl_array!(4); // for IPv4
391 impl_array!(10); // for OnionV2
392 impl_array!(16); // for IPv6
393 impl_array!(32); // for channel id & hmac
394 impl_array!(33); // for PublicKey
395 impl_array!(64); // for Signature
396 impl_array!(1300); // for OnionPacket.hop_data
399 impl<K, V> Writeable for HashMap<K, V>
400 where K: Writeable + Eq + Hash,
404 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
405 (self.len() as u16).write(w)?;
406 for (key, value) in self.iter() {
414 impl<R, K, V> Readable<R> for HashMap<K, V>
416 K: Readable<R> + Eq + Hash,
420 fn read(r: &mut R) -> Result<Self, DecodeError> {
421 let len: u16 = Readable::read(r)?;
422 let mut ret = HashMap::with_capacity(len as usize);
424 ret.insert(K::read(r)?, V::read(r)?);
431 impl Writeable for Vec<u8> {
433 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
434 (self.len() as u16).write(w)?;
439 impl<R: Read> Readable<R> for Vec<u8> {
441 fn read(r: &mut R) -> Result<Self, DecodeError> {
442 let len: u16 = Readable::read(r)?;
443 let mut ret = Vec::with_capacity(len as usize);
444 ret.resize(len as usize, 0);
445 r.read_exact(&mut ret)?;
449 impl Writeable for Vec<Signature> {
451 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
452 (self.len() as u16).write(w)?;
453 for e in self.iter() {
460 impl<R: Read> Readable<R> for Vec<Signature> {
462 fn read(r: &mut R) -> Result<Self, DecodeError> {
463 let len: u16 = Readable::read(r)?;
464 let byte_size = (len as usize)
466 .ok_or(DecodeError::BadLengthDescriptor)?;
467 if byte_size > MAX_BUF_SIZE {
468 return Err(DecodeError::BadLengthDescriptor);
470 let mut ret = Vec::with_capacity(len as usize);
471 for _ in 0..len { ret.push(Signature::read(r)?); }
476 impl Writeable for Script {
477 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
478 (self.len() as u16).write(w)?;
479 w.write_all(self.as_bytes())
483 impl<R: Read> Readable<R> for Script {
484 fn read(r: &mut R) -> Result<Self, DecodeError> {
485 let len = <u16 as Readable<R>>::read(r)? as usize;
486 let mut buf = vec![0; len];
487 r.read_exact(&mut buf)?;
488 Ok(Script::from(buf))
492 impl Writeable for PublicKey {
493 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
494 self.serialize().write(w)
498 impl<R: Read> Readable<R> for PublicKey {
499 fn read(r: &mut R) -> Result<Self, DecodeError> {
500 let buf: [u8; 33] = Readable::read(r)?;
501 match PublicKey::from_slice(&buf) {
503 Err(_) => return Err(DecodeError::InvalidValue),
508 impl Writeable for SecretKey {
509 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
510 let mut ser = [0; 32];
511 ser.copy_from_slice(&self[..]);
516 impl<R: Read> Readable<R> for SecretKey {
517 fn read(r: &mut R) -> Result<Self, DecodeError> {
518 let buf: [u8; 32] = Readable::read(r)?;
519 match SecretKey::from_slice(&buf) {
521 Err(_) => return Err(DecodeError::InvalidValue),
526 impl Writeable for Sha256dHash {
527 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
528 w.write_all(&self[..])
532 impl<R: Read> Readable<R> for Sha256dHash {
533 fn read(r: &mut R) -> Result<Self, DecodeError> {
534 use bitcoin_hashes::Hash;
536 let buf: [u8; 32] = Readable::read(r)?;
537 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
541 impl Writeable for Signature {
542 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
543 self.serialize_compact().write(w)
547 impl<R: Read> Readable<R> for Signature {
548 fn read(r: &mut R) -> Result<Self, DecodeError> {
549 let buf: [u8; 64] = Readable::read(r)?;
550 match Signature::from_compact(&buf) {
552 Err(_) => return Err(DecodeError::InvalidValue),
557 impl Writeable for PaymentPreimage {
558 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
563 impl<R: Read> Readable<R> for PaymentPreimage {
564 fn read(r: &mut R) -> Result<Self, DecodeError> {
565 let buf: [u8; 32] = Readable::read(r)?;
566 Ok(PaymentPreimage(buf))
570 impl Writeable for PaymentHash {
571 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
576 impl<R: Read> Readable<R> for PaymentHash {
577 fn read(r: &mut R) -> Result<Self, DecodeError> {
578 let buf: [u8; 32] = Readable::read(r)?;
583 impl<T: Writeable> Writeable for Option<T> {
584 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
586 None => 0u8.write(w)?,
596 impl<R, T> Readable<R> for Option<T>
600 fn read(r: &mut R) -> Result<Self, DecodeError> {
601 match <u8 as Readable<R>>::read(r)? {
603 1 => Ok(Some(Readable::read(r)?)),
604 _ => return Err(DecodeError::InvalidValue),
609 impl Writeable for OutPoint {
610 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
617 impl<R: Read> Readable<R> for OutPoint {
618 fn read(r: &mut R) -> Result<Self, DecodeError> {
619 let txid = Readable::read(r)?;
620 let vout = Readable::read(r)?;
628 impl<R: Read, T: Readable<R>> Readable<R> for Mutex<T> {
629 fn read(r: &mut R) -> Result<Self, DecodeError> {
630 let t: T = Readable::read(r)?;
634 impl<T: Writeable> Writeable for Mutex<T> {
635 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
636 self.lock().unwrap().write(w)
640 impl<R: Read, A: Readable<R>, B: Readable<R>> Readable<R> for (A, B) {
641 fn read(r: &mut R) -> Result<Self, DecodeError> {
642 let a: A = Readable::read(r)?;
643 let b: B = Readable::read(r)?;
647 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
648 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {