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, Transaction, TxOut};
15 use bitcoin::consensus;
16 use bitcoin::consensus::Encodable;
17 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
18 use std::marker::Sized;
19 use ln::msgs::DecodeError;
20 use ln::channelmanager::{PaymentPreimage, PaymentHash};
23 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};
25 const MAX_BUF_SIZE: usize = 64 * 1024;
27 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
28 /// buffers being written into.
29 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
32 /// Writes the given buf out. See std::io::Write::write_all for more
33 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
34 /// Hints that data of the given size is about the be written. This may not always be called
35 /// prior to data being written and may be safely ignored.
36 fn size_hint(&mut self, size: usize);
39 impl<W: Write> Writer for W {
41 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
42 <Self as ::std::io::Write>::write_all(self, buf)
45 fn size_hint(&mut self, _size: usize) { }
48 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
49 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
50 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
53 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
54 self.0.write_all(buf)?;
57 fn flush(&mut self) -> Result<(), ::std::io::Error> {
62 pub(crate) struct VecWriter(pub Vec<u8>);
63 impl Writer for VecWriter {
64 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
65 self.0.extend_from_slice(buf);
68 fn size_hint(&mut self, size: usize) {
69 self.0.reserve_exact(size);
73 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
74 /// of some data when serialized but don't yet need the full data.
75 pub(crate) struct LengthCalculatingWriter(pub usize);
76 impl Writer for LengthCalculatingWriter {
78 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
83 fn size_hint(&mut self, _size: usize) {}
86 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
87 /// forward to ensure we always consume exactly the fixed length specified.
88 pub(crate) struct FixedLengthReader<R: Read> {
93 impl<R: Read> FixedLengthReader<R> {
94 pub fn new(read: R, total_bytes: u64) -> Self {
95 Self { read, bytes_read: 0, total_bytes }
98 pub fn bytes_remain(&mut self) -> bool {
99 self.bytes_read != self.total_bytes
102 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
103 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
104 if self.bytes_read != self.total_bytes {
105 Err(DecodeError::ShortRead)
111 impl<R: Read> Read for FixedLengthReader<R> {
112 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
113 if self.total_bytes == self.bytes_read {
116 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
117 match self.read.read(&mut dest[0..(read_len as usize)]) {
119 self.bytes_read += v as u64;
128 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
129 /// between "EOF reached before we started" and "EOF reached mid-read".
130 pub(crate) struct ReadTrackingReader<R: Read> {
134 impl<R: Read> ReadTrackingReader<R> {
135 pub fn new(read: R) -> Self {
136 Self { read, have_read: false }
139 impl<R: Read> Read for ReadTrackingReader<R> {
140 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
141 match self.read.read(dest) {
144 self.have_read = true;
152 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
153 pub trait Writeable {
154 /// Writes self out to the given Writer
155 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
157 /// Writes self out to a Vec<u8>
158 fn encode(&self) -> Vec<u8> {
159 let mut msg = VecWriter(Vec::new());
160 self.write(&mut msg).unwrap();
164 /// Writes self out to a Vec<u8>
165 fn encode_with_len(&self) -> Vec<u8> {
166 let mut msg = VecWriter(Vec::new());
167 0u16.write(&mut msg).unwrap();
168 self.write(&mut msg).unwrap();
169 let len = msg.0.len();
170 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
175 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
176 pub trait Readable<R>
180 /// Reads a Self in from the given Read
181 fn read(reader: &mut R) -> Result<Self, DecodeError>;
184 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
185 /// from a Read given some additional set of arguments which is required to deserialize.
186 pub trait ReadableArgs<R, P>
190 /// Reads a Self in from the given Read
191 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
194 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
195 pub trait MaybeReadable<R>
199 /// Reads a Self in from the given Read
200 fn read(reader: &mut R) -> Result<Option<Self>, DecodeError>;
203 pub(crate) struct U48(pub u64);
204 impl Writeable for U48 {
206 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
207 writer.write_all(&be48_to_array(self.0))
210 impl<R: Read> Readable<R> for U48 {
212 fn read(reader: &mut R) -> Result<U48, DecodeError> {
213 let mut buf = [0; 6];
214 reader.read_exact(&mut buf)?;
215 Ok(U48(slice_to_be48(&buf)))
219 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
220 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
222 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
223 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
224 /// you're looking for an example of a variable-length integer to use for your own project, move
225 /// along, this is a rather poor design.
226 pub(crate) struct BigSize(pub u64);
227 impl Writeable for BigSize {
229 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
232 (self.0 as u8).write(writer)
235 0xFDu8.write(writer)?;
236 (self.0 as u16).write(writer)
238 0x10000...0xFFFFFFFF => {
239 0xFEu8.write(writer)?;
240 (self.0 as u32).write(writer)
243 0xFFu8.write(writer)?;
244 (self.0 as u64).write(writer)
249 impl<R: Read> Readable<R> for BigSize {
251 fn read(reader: &mut R) -> Result<BigSize, DecodeError> {
252 let n: u8 = Readable::read(reader)?;
255 let x: u64 = Readable::read(reader)?;
257 Err(DecodeError::InvalidValue)
263 let x: u32 = Readable::read(reader)?;
265 Err(DecodeError::InvalidValue)
267 Ok(BigSize(x as u64))
271 let x: u16 = Readable::read(reader)?;
273 Err(DecodeError::InvalidValue)
275 Ok(BigSize(x as u64))
278 n => Ok(BigSize(n as u64))
283 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
284 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
285 /// encapsulates such integers implementing Readable/Writeable for them.
286 #[cfg_attr(test, derive(PartialEq, Debug))]
287 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
289 macro_rules! impl_writeable_primitive {
290 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
291 impl Writeable for $val_type {
293 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
294 writer.write_all(&$meth_write(*self))
297 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
299 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
300 // Skip any full leading 0 bytes when writing (in BE):
301 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
304 impl<R: Read> Readable<R> for $val_type {
306 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
307 let mut buf = [0; $len];
308 reader.read_exact(&mut buf)?;
312 impl<R: Read> Readable<R> for HighZeroBytesDroppedVarInt<$val_type> {
314 fn read(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
315 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
316 // the high bytes being dropped. To do so, we start reading into the middle of buf
317 // and then convert the appropriate number of bytes with extra high bytes out of
319 let mut buf = [0; $len*2];
320 let mut read_len = reader.read(&mut buf[$len..])?;
321 let mut total_read_len = read_len;
322 while read_len != 0 && total_read_len != $len {
323 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
324 total_read_len += read_len;
326 if total_read_len == 0 || buf[$len] != 0 {
327 let first_byte = $len - ($len - total_read_len);
328 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
330 // If the encoding had extra zero bytes, return a failure even though we know
331 // what they meant (as the TLV test vectors require this)
332 Err(DecodeError::InvalidValue)
339 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
340 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
341 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
343 impl Writeable for u8 {
345 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
346 writer.write_all(&[*self])
349 impl<R: Read> Readable<R> for u8 {
351 fn read(reader: &mut R) -> Result<u8, DecodeError> {
352 let mut buf = [0; 1];
353 reader.read_exact(&mut buf)?;
358 impl Writeable for bool {
360 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
361 writer.write_all(&[if *self {1} else {0}])
364 impl<R: Read> Readable<R> for bool {
366 fn read(reader: &mut R) -> Result<bool, DecodeError> {
367 let mut buf = [0; 1];
368 reader.read_exact(&mut buf)?;
369 if buf[0] != 0 && buf[0] != 1 {
370 return Err(DecodeError::InvalidValue);
377 macro_rules! impl_array {
379 impl Writeable for [u8; $size]
382 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
387 impl<R: Read> Readable<R> for [u8; $size]
390 fn read(r: &mut R) -> Result<Self, DecodeError> {
391 let mut buf = [0u8; $size];
392 r.read_exact(&mut buf)?;
399 //TODO: performance issue with [u8; size] with impl_array!()
400 impl_array!(3); // for rgb
401 impl_array!(4); // for IPv4
402 impl_array!(10); // for OnionV2
403 impl_array!(16); // for IPv6
404 impl_array!(32); // for channel id & hmac
405 impl_array!(33); // for PublicKey
406 impl_array!(64); // for Signature
407 impl_array!(1300); // for OnionPacket.hop_data
410 impl<K, V> Writeable for HashMap<K, V>
411 where K: Writeable + Eq + Hash,
415 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
416 (self.len() as u16).write(w)?;
417 for (key, value) in self.iter() {
425 impl<R, K, V> Readable<R> for HashMap<K, V>
427 K: Readable<R> + Eq + Hash,
431 fn read(r: &mut R) -> Result<Self, DecodeError> {
432 let len: u16 = Readable::read(r)?;
433 let mut ret = HashMap::with_capacity(len as usize);
435 ret.insert(K::read(r)?, V::read(r)?);
442 impl Writeable for Vec<u8> {
444 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
445 (self.len() as u16).write(w)?;
450 impl<R: Read> Readable<R> for Vec<u8> {
452 fn read(r: &mut R) -> Result<Self, DecodeError> {
453 let len: u16 = Readable::read(r)?;
454 let mut ret = Vec::with_capacity(len as usize);
455 ret.resize(len as usize, 0);
456 r.read_exact(&mut ret)?;
460 impl Writeable for Vec<Signature> {
462 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
463 (self.len() as u16).write(w)?;
464 for e in self.iter() {
471 impl<R: Read> Readable<R> for Vec<Signature> {
473 fn read(r: &mut R) -> Result<Self, DecodeError> {
474 let len: u16 = Readable::read(r)?;
475 let byte_size = (len as usize)
477 .ok_or(DecodeError::BadLengthDescriptor)?;
478 if byte_size > MAX_BUF_SIZE {
479 return Err(DecodeError::BadLengthDescriptor);
481 let mut ret = Vec::with_capacity(len as usize);
482 for _ in 0..len { ret.push(Signature::read(r)?); }
487 impl Writeable for Script {
488 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
489 (self.len() as u16).write(w)?;
490 w.write_all(self.as_bytes())
494 impl<R: Read> Readable<R> for Script {
495 fn read(r: &mut R) -> Result<Self, DecodeError> {
496 let len = <u16 as Readable<R>>::read(r)? as usize;
497 let mut buf = vec![0; len];
498 r.read_exact(&mut buf)?;
499 Ok(Script::from(buf))
503 impl Writeable for PublicKey {
504 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
505 self.serialize().write(w)
509 impl<R: Read> Readable<R> for PublicKey {
510 fn read(r: &mut R) -> Result<Self, DecodeError> {
511 let buf: [u8; 33] = Readable::read(r)?;
512 match PublicKey::from_slice(&buf) {
514 Err(_) => return Err(DecodeError::InvalidValue),
519 impl Writeable for SecretKey {
520 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
521 let mut ser = [0; 32];
522 ser.copy_from_slice(&self[..]);
527 impl<R: Read> Readable<R> for SecretKey {
528 fn read(r: &mut R) -> Result<Self, DecodeError> {
529 let buf: [u8; 32] = Readable::read(r)?;
530 match SecretKey::from_slice(&buf) {
532 Err(_) => return Err(DecodeError::InvalidValue),
537 impl Writeable for Sha256dHash {
538 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
539 w.write_all(&self[..])
543 impl<R: Read> Readable<R> for Sha256dHash {
544 fn read(r: &mut R) -> Result<Self, DecodeError> {
545 use bitcoin_hashes::Hash;
547 let buf: [u8; 32] = Readable::read(r)?;
548 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
552 impl Writeable for Signature {
553 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
554 self.serialize_compact().write(w)
558 impl<R: Read> Readable<R> for Signature {
559 fn read(r: &mut R) -> Result<Self, DecodeError> {
560 let buf: [u8; 64] = Readable::read(r)?;
561 match Signature::from_compact(&buf) {
563 Err(_) => return Err(DecodeError::InvalidValue),
568 impl Writeable for PaymentPreimage {
569 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
574 impl<R: Read> Readable<R> for PaymentPreimage {
575 fn read(r: &mut R) -> Result<Self, DecodeError> {
576 let buf: [u8; 32] = Readable::read(r)?;
577 Ok(PaymentPreimage(buf))
581 impl Writeable for PaymentHash {
582 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
587 impl<R: Read> Readable<R> for PaymentHash {
588 fn read(r: &mut R) -> Result<Self, DecodeError> {
589 let buf: [u8; 32] = Readable::read(r)?;
594 impl<T: Writeable> Writeable for Option<T> {
595 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
597 None => 0u8.write(w)?,
607 impl<R, T> Readable<R> for Option<T>
611 fn read(r: &mut R) -> Result<Self, DecodeError> {
612 match <u8 as Readable<R>>::read(r)? {
614 1 => Ok(Some(Readable::read(r)?)),
615 _ => return Err(DecodeError::InvalidValue),
620 impl Writeable for OutPoint {
621 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
628 impl<R: Read> Readable<R> for OutPoint {
629 fn read(r: &mut R) -> Result<Self, DecodeError> {
630 let txid = Readable::read(r)?;
631 let vout = Readable::read(r)?;
639 macro_rules! impl_consensus_ser {
640 ($bitcoin_type: ty) => {
641 impl Writeable for $bitcoin_type {
642 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
643 match self.consensus_encode(WriterWriteAdaptor(writer)) {
645 Err(consensus::encode::Error::Io(e)) => Err(e),
646 Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
651 impl<R: Read> Readable<R> for $bitcoin_type {
652 fn read(r: &mut R) -> Result<Self, DecodeError> {
653 match consensus::encode::Decodable::consensus_decode(r) {
655 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
656 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
657 Err(_) => Err(DecodeError::InvalidValue),
663 impl_consensus_ser!(Transaction);
664 impl_consensus_ser!(TxOut);
666 impl<R: Read, T: Readable<R>> Readable<R> for Mutex<T> {
667 fn read(r: &mut R) -> Result<Self, DecodeError> {
668 let t: T = Readable::read(r)?;
672 impl<T: Writeable> Writeable for Mutex<T> {
673 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
674 self.lock().unwrap().write(w)
678 impl<R: Read, A: Readable<R>, B: Readable<R>> Readable<R> for (A, B) {
679 fn read(r: &mut R) -> Result<Self, DecodeError> {
680 let a: A = Readable::read(r)?;
681 let b: B = Readable::read(r)?;
685 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
686 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {