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;
10 use secp256k1::Signature;
11 use secp256k1::key::{PublicKey, SecretKey};
12 use bitcoin::blockdata::script::Script;
13 use bitcoin::blockdata::transaction::OutPoint;
14 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
15 use std::marker::Sized;
16 use ln::msgs::DecodeError;
17 use ln::channelmanager::{PaymentPreimage, PaymentHash};
20 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 const MAX_BUF_SIZE: usize = 64 * 1024;
24 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
25 /// buffers being written into.
26 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
29 /// Writes the given buf out. See std::io::Write::write_all for more
30 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
31 /// Hints that data of the given size is about the be written. This may not always be called
32 /// prior to data being written and may be safely ignored.
33 fn size_hint(&mut self, size: usize);
36 impl<W: Write> Writer for W {
38 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
39 <Self as ::std::io::Write>::write_all(self, buf)
42 fn size_hint(&mut self, _size: usize) { }
45 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
46 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
47 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
50 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
51 self.0.write_all(buf)?;
54 fn flush(&mut self) -> Result<(), ::std::io::Error> {
59 struct VecWriter(Vec<u8>);
60 impl Writer for VecWriter {
61 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
62 self.0.extend_from_slice(buf);
65 fn size_hint(&mut self, size: usize) {
66 self.0.reserve_exact(size);
70 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
72 /// Writes self out to the given Writer
73 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
75 /// Writes self out to a Vec<u8>
76 fn encode(&self) -> Vec<u8> {
77 let mut msg = VecWriter(Vec::new());
78 self.write(&mut msg).unwrap();
82 /// Writes self out to a Vec<u8>
83 fn encode_with_len(&self) -> Vec<u8> {
84 let mut msg = VecWriter(Vec::new());
85 0u16.write(&mut msg).unwrap();
86 self.write(&mut msg).unwrap();
87 let len = msg.0.len();
88 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
93 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
98 /// Reads a Self in from the given Read
99 fn read(reader: &mut R) -> Result<Self, DecodeError>;
102 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
103 /// from a Read given some additional set of arguments which is required to deserialize.
104 pub trait ReadableArgs<R, P>
108 /// Reads a Self in from the given Read
109 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
112 pub(crate) struct U48(pub u64);
113 impl Writeable for U48 {
115 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
116 writer.write_all(&be48_to_array(self.0))
119 impl<R: Read> Readable<R> for U48 {
121 fn read(reader: &mut R) -> Result<U48, DecodeError> {
122 let mut buf = [0; 6];
123 reader.read_exact(&mut buf)?;
124 Ok(U48(slice_to_be48(&buf)))
128 macro_rules! impl_writeable_primitive {
129 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
130 impl Writeable for $val_type {
132 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
133 writer.write_all(&$meth_write(*self))
136 impl<R: Read> Readable<R> for $val_type {
138 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
139 let mut buf = [0; $len];
140 reader.read_exact(&mut buf)?;
147 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
148 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
149 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
151 impl Writeable for u8 {
153 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
154 writer.write_all(&[*self])
157 impl<R: Read> Readable<R> for u8 {
159 fn read(reader: &mut R) -> Result<u8, DecodeError> {
160 let mut buf = [0; 1];
161 reader.read_exact(&mut buf)?;
166 impl Writeable for bool {
168 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
169 writer.write_all(&[if *self {1} else {0}])
172 impl<R: Read> Readable<R> for bool {
174 fn read(reader: &mut R) -> Result<bool, DecodeError> {
175 let mut buf = [0; 1];
176 reader.read_exact(&mut buf)?;
177 if buf[0] != 0 && buf[0] != 1 {
178 return Err(DecodeError::InvalidValue);
185 macro_rules! impl_array {
187 impl Writeable for [u8; $size]
190 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
195 impl<R: Read> Readable<R> for [u8; $size]
198 fn read(r: &mut R) -> Result<Self, DecodeError> {
199 let mut buf = [0u8; $size];
200 r.read_exact(&mut buf)?;
207 //TODO: performance issue with [u8; size] with impl_array!()
208 impl_array!(3); // for rgb
209 impl_array!(4); // for IPv4
210 impl_array!(10); // for OnionV2
211 impl_array!(16); // for IPv6
212 impl_array!(32); // for channel id & hmac
213 impl_array!(33); // for PublicKey
214 impl_array!(64); // for Signature
215 impl_array!(1300); // for OnionPacket.hop_data
218 impl<K, V> Writeable for HashMap<K, V>
219 where K: Writeable + Eq + Hash,
223 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
224 (self.len() as u16).write(w)?;
225 for (key, value) in self.iter() {
233 impl<R, K, V> Readable<R> for HashMap<K, V>
235 K: Readable<R> + Eq + Hash,
239 fn read(r: &mut R) -> Result<Self, DecodeError> {
240 let len: u16 = Readable::read(r)?;
241 let mut ret = HashMap::with_capacity(len as usize);
243 ret.insert(K::read(r)?, V::read(r)?);
250 impl Writeable for Vec<u8> {
252 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
253 (self.len() as u16).write(w)?;
258 impl<R: Read> Readable<R> for Vec<u8> {
260 fn read(r: &mut R) -> Result<Self, DecodeError> {
261 let len: u16 = Readable::read(r)?;
262 let mut ret = Vec::with_capacity(len as usize);
263 ret.resize(len as usize, 0);
264 r.read_exact(&mut ret)?;
268 impl Writeable for Vec<Signature> {
270 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
271 (self.len() as u16).write(w)?;
272 for e in self.iter() {
279 impl<R: Read> Readable<R> for Vec<Signature> {
281 fn read(r: &mut R) -> Result<Self, DecodeError> {
282 let len: u16 = Readable::read(r)?;
283 let byte_size = (len as usize)
285 .ok_or(DecodeError::BadLengthDescriptor)?;
286 if byte_size > MAX_BUF_SIZE {
287 return Err(DecodeError::BadLengthDescriptor);
289 let mut ret = Vec::with_capacity(len as usize);
290 for _ in 0..len { ret.push(Signature::read(r)?); }
295 impl Writeable for Script {
296 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
297 (self.len() as u16).write(w)?;
298 w.write_all(self.as_bytes())
302 impl<R: Read> Readable<R> for Script {
303 fn read(r: &mut R) -> Result<Self, DecodeError> {
304 let len = <u16 as Readable<R>>::read(r)? as usize;
305 let mut buf = vec![0; len];
306 r.read_exact(&mut buf)?;
307 Ok(Script::from(buf))
311 impl Writeable for PublicKey {
312 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
313 self.serialize().write(w)
317 impl<R: Read> Readable<R> for PublicKey {
318 fn read(r: &mut R) -> Result<Self, DecodeError> {
319 let buf: [u8; 33] = Readable::read(r)?;
320 match PublicKey::from_slice(&buf) {
322 Err(_) => return Err(DecodeError::InvalidValue),
327 impl Writeable for SecretKey {
328 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
329 let mut ser = [0; 32];
330 ser.copy_from_slice(&self[..]);
335 impl<R: Read> Readable<R> for SecretKey {
336 fn read(r: &mut R) -> Result<Self, DecodeError> {
337 let buf: [u8; 32] = Readable::read(r)?;
338 match SecretKey::from_slice(&buf) {
340 Err(_) => return Err(DecodeError::InvalidValue),
345 impl Writeable for Sha256dHash {
346 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
347 w.write_all(&self[..])
351 impl<R: Read> Readable<R> for Sha256dHash {
352 fn read(r: &mut R) -> Result<Self, DecodeError> {
353 use bitcoin_hashes::Hash;
355 let buf: [u8; 32] = Readable::read(r)?;
356 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
360 impl Writeable for Signature {
361 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
362 self.serialize_compact().write(w)
366 impl<R: Read> Readable<R> for Signature {
367 fn read(r: &mut R) -> Result<Self, DecodeError> {
368 let buf: [u8; 64] = Readable::read(r)?;
369 match Signature::from_compact(&buf) {
371 Err(_) => return Err(DecodeError::InvalidValue),
376 impl Writeable for PaymentPreimage {
377 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
382 impl<R: Read> Readable<R> for PaymentPreimage {
383 fn read(r: &mut R) -> Result<Self, DecodeError> {
384 let buf: [u8; 32] = Readable::read(r)?;
385 Ok(PaymentPreimage(buf))
389 impl Writeable for PaymentHash {
390 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
395 impl<R: Read> Readable<R> for PaymentHash {
396 fn read(r: &mut R) -> Result<Self, DecodeError> {
397 let buf: [u8; 32] = Readable::read(r)?;
402 impl<T: Writeable> Writeable for Option<T> {
403 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
405 None => 0u8.write(w)?,
415 impl<R, T> Readable<R> for Option<T>
419 fn read(r: &mut R) -> Result<Self, DecodeError> {
420 match <u8 as Readable<R>>::read(r)? {
422 1 => Ok(Some(Readable::read(r)?)),
423 _ => return Err(DecodeError::InvalidValue),
428 impl Writeable for OutPoint {
429 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
436 impl<R: Read> Readable<R> for OutPoint {
437 fn read(r: &mut R) -> Result<Self, DecodeError> {
438 let txid = Readable::read(r)?;
439 let vout = Readable::read(r)?;
447 impl<R: Read, T: Readable<R>> Readable<R> for Mutex<T> {
448 fn read(r: &mut R) -> Result<Self, DecodeError> {
449 let t: T = Readable::read(r)?;
453 impl<T: Writeable> Writeable for Mutex<T> {
454 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
455 self.lock().unwrap().write(w)
459 impl<R: Read, A: Readable<R>, B: Readable<R>> Readable<R> for (A, B) {
460 fn read(r: &mut R) -> Result<Self, DecodeError> {
461 let a: A = Readable::read(r)?;
462 let b: B = Readable::read(r)?;
466 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
467 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {