Make commitment transaction signing a part of ChannelKeys.
[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
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};
18 use util::byte_utils;
19
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};
21
22 const MAX_BUF_SIZE: usize = 64 * 1024;
23
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
27 /// hints.
28 pub trait Writer {
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);
34 }
35
36 impl<W: Write> Writer for W {
37         #[inline]
38         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
39                 <Self as ::std::io::Write>::write_all(self, buf)
40         }
41         #[inline]
42         fn size_hint(&mut self, _size: usize) { }
43 }
44
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> {
48                 self.0.write_all(buf)
49         }
50         fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
51                 self.0.write_all(buf)?;
52                 Ok(buf.len())
53         }
54         fn flush(&mut self) -> Result<(), ::std::io::Error> {
55                 Ok(())
56         }
57 }
58
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);
63                 Ok(())
64         }
65         fn size_hint(&mut self, size: usize) {
66                 self.0.reserve_exact(size);
67         }
68 }
69
70 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
71 pub trait Writeable {
72         /// Writes self out to the given Writer
73         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
74
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();
79                 msg.0
80         }
81
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));
89                 msg.0
90         }
91 }
92
93 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
94 pub trait Readable<R>
95         where Self: Sized,
96               R: Read
97 {
98         /// Reads a Self in from the given Read
99         fn read(reader: &mut R) -> Result<Self, DecodeError>;
100 }
101
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>
105         where Self: Sized,
106               R: Read
107 {
108         /// Reads a Self in from the given Read
109         fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
110 }
111
112 pub(crate) struct U48(pub u64);
113 impl Writeable for U48 {
114         #[inline]
115         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
116                 writer.write_all(&be48_to_array(self.0))
117         }
118 }
119 impl<R: Read> Readable<R> for U48 {
120         #[inline]
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)))
125         }
126 }
127
128 macro_rules! impl_writeable_primitive {
129         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
130                 impl Writeable for $val_type {
131                         #[inline]
132                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
133                                 writer.write_all(&$meth_write(*self))
134                         }
135                 }
136                 impl<R: Read> Readable<R> for $val_type {
137                         #[inline]
138                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
139                                 let mut buf = [0; $len];
140                                 reader.read_exact(&mut buf)?;
141                                 Ok($meth_read(&buf))
142                         }
143                 }
144         }
145 }
146
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);
150
151 impl Writeable for u8 {
152         #[inline]
153         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
154                 writer.write_all(&[*self])
155         }
156 }
157 impl<R: Read> Readable<R> for u8 {
158         #[inline]
159         fn read(reader: &mut R) -> Result<u8, DecodeError> {
160                 let mut buf = [0; 1];
161                 reader.read_exact(&mut buf)?;
162                 Ok(buf[0])
163         }
164 }
165
166 impl Writeable for bool {
167         #[inline]
168         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
169                 writer.write_all(&[if *self {1} else {0}])
170         }
171 }
172 impl<R: Read> Readable<R> for bool {
173         #[inline]
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);
179                 }
180                 Ok(buf[0] == 1)
181         }
182 }
183
184 // u8 arrays
185 macro_rules! impl_array {
186         ( $size:expr ) => (
187                 impl Writeable for [u8; $size]
188                 {
189                         #[inline]
190                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
191                                 w.write_all(self)
192                         }
193                 }
194
195                 impl<R: Read> Readable<R> for [u8; $size]
196                 {
197                         #[inline]
198                         fn read(r: &mut R) -> Result<Self, DecodeError> {
199                                 let mut buf = [0u8; $size];
200                                 r.read_exact(&mut buf)?;
201                                 Ok(buf)
202                         }
203                 }
204         );
205 }
206
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
216
217 // HashMap
218 impl<K, V> Writeable for HashMap<K, V>
219         where K: Writeable + Eq + Hash,
220               V: Writeable
221 {
222         #[inline]
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() {
226                         key.write(w)?;
227                         value.write(w)?;
228                 }
229                 Ok(())
230         }
231 }
232
233 impl<R, K, V> Readable<R> for HashMap<K, V>
234         where R: Read,
235               K: Readable<R> + Eq + Hash,
236               V: Readable<R>
237 {
238         #[inline]
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);
242                 for _ in 0..len {
243                         ret.insert(K::read(r)?, V::read(r)?);
244                 }
245                 Ok(ret)
246         }
247 }
248
249 // Vectors
250 impl Writeable for Vec<u8> {
251         #[inline]
252         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
253                 (self.len() as u16).write(w)?;
254                 w.write_all(&self)
255         }
256 }
257
258 impl<R: Read> Readable<R> for Vec<u8> {
259         #[inline]
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)?;
265                 Ok(ret)
266         }
267 }
268 impl Writeable for Vec<Signature> {
269         #[inline]
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() {
273                         e.write(w)?;
274                 }
275                 Ok(())
276         }
277 }
278
279 impl<R: Read> Readable<R> for Vec<Signature> {
280         #[inline]
281         fn read(r: &mut R) -> Result<Self, DecodeError> {
282                 let len: u16 = Readable::read(r)?;
283                 let byte_size = (len as usize)
284                                 .checked_mul(33)
285                                 .ok_or(DecodeError::BadLengthDescriptor)?;
286                 if byte_size > MAX_BUF_SIZE {
287                         return Err(DecodeError::BadLengthDescriptor);
288                 }
289                 let mut ret = Vec::with_capacity(len as usize);
290                 for _ in 0..len { ret.push(Signature::read(r)?); }
291                 Ok(ret)
292         }
293 }
294
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())
299         }
300 }
301
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))
308         }
309 }
310
311 impl Writeable for PublicKey {
312         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
313                 self.serialize().write(w)
314         }
315 }
316
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) {
321                         Ok(key) => Ok(key),
322                         Err(_) => return Err(DecodeError::InvalidValue),
323                 }
324         }
325 }
326
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[..]);
331                 ser.write(w)
332         }
333 }
334
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) {
339                         Ok(key) => Ok(key),
340                         Err(_) => return Err(DecodeError::InvalidValue),
341                 }
342         }
343 }
344
345 impl Writeable for Sha256dHash {
346         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
347                 w.write_all(&self[..])
348         }
349 }
350
351 impl<R: Read> Readable<R> for Sha256dHash {
352         fn read(r: &mut R) -> Result<Self, DecodeError> {
353                 use bitcoin_hashes::Hash;
354
355                 let buf: [u8; 32] = Readable::read(r)?;
356                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
357         }
358 }
359
360 impl Writeable for Signature {
361         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
362                 self.serialize_compact().write(w)
363         }
364 }
365
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) {
370                         Ok(sig) => Ok(sig),
371                         Err(_) => return Err(DecodeError::InvalidValue),
372                 }
373         }
374 }
375
376 impl Writeable for PaymentPreimage {
377         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
378                 self.0.write(w)
379         }
380 }
381
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))
386         }
387 }
388
389 impl Writeable for PaymentHash {
390         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
391                 self.0.write(w)
392         }
393 }
394
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)?;
398                 Ok(PaymentHash(buf))
399         }
400 }
401
402 impl<T: Writeable> Writeable for Option<T> {
403         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
404                 match *self {
405                         None => 0u8.write(w)?,
406                         Some(ref data) => {
407                                 1u8.write(w)?;
408                                 data.write(w)?;
409                         }
410                 }
411                 Ok(())
412         }
413 }
414
415 impl<R, T> Readable<R> for Option<T>
416         where R: Read,
417               T: Readable<R>
418 {
419         fn read(r: &mut R) -> Result<Self, DecodeError> {
420                 match <u8 as Readable<R>>::read(r)? {
421                         0 => Ok(None),
422                         1 => Ok(Some(Readable::read(r)?)),
423                         _ => return Err(DecodeError::InvalidValue),
424                 }
425         }
426 }
427
428 impl Writeable for OutPoint {
429         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
430                 self.txid.write(w)?;
431                 self.vout.write(w)?;
432                 Ok(())
433         }
434 }
435
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)?;
440                 Ok(OutPoint {
441                         txid,
442                         vout,
443                 })
444         }
445 }
446
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)?;
450                 Ok(Mutex::new(t))
451         }
452 }
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)
456         }
457 }
458
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)?;
463                 Ok((a, b))
464         }
465 }
466 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
467         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
468                 self.0.write(w)?;
469                 self.1.write(w)
470         }
471 }