Make Writeable::write typed instead of Writeable
[rust-lightning] / src / util / ser.rs
1 use std::result::Result;
2 use std::io::Read;
3 use std::collections::HashMap;
4 use std::hash::Hash;
5
6 use secp256k1::{Secp256k1, Signature};
7 use secp256k1::key::PublicKey;
8 use bitcoin::util::hash::Sha256dHash;
9 use bitcoin::blockdata::script::Script;
10 use std::marker::Sized;
11 use ln::msgs::DecodeError;
12
13 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
14
15 const MAX_BUF_SIZE: usize = 64 * 1024;
16
17 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
18 /// buffers being written into.
19 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
20 /// hints.
21 pub trait Writer {
22         /// Writes the given buf out. See std::io::Write::write_all for more
23         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
24         /// Hints that data of the given size is about the be written. This may not always be called
25         /// prior to data being written and may be safely ignored.
26         fn size_hint(&mut self, size: usize);
27 }
28
29 impl<W: ::std::io::Write> Writer for W {
30         #[inline]
31         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
32                 <Self as ::std::io::Write>::write_all(self, buf)
33         }
34         #[inline]
35         fn size_hint(&mut self, _size: usize) { }
36 }
37
38 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
39 pub trait Writeable {
40         /// Writes self out to the given Writer
41         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
42 }
43
44 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
45 pub trait Readable<R>
46         where Self: Sized,
47               R: Read
48 {
49         /// Reads a Self in from the given Read
50         fn read(reader: &mut R) -> Result<Self, DecodeError>;
51 }
52
53 macro_rules! impl_writeable_primitive {
54         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
55                 impl Writeable for $val_type {
56                         #[inline]
57                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
58                                 writer.write_all(&$meth_write(*self))
59                         }
60                 }
61                 impl<R: Read> Readable<R> for $val_type {
62                         #[inline]
63                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
64                                 let mut buf = [0; $len];
65                                 reader.read_exact(&mut buf)?;
66                                 Ok($meth_read(&buf))
67                         }
68                 }
69         }
70 }
71
72 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
73 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
74 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
75
76 impl Writeable for u8 {
77         #[inline]
78         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79                 writer.write_all(&[*self])
80         }
81 }
82 impl<R: Read> Readable<R> for u8 {
83         #[inline]
84         fn read(reader: &mut R) -> Result<u8, DecodeError> {
85                 let mut buf = [0; 1];
86                 reader.read_exact(&mut buf)?;
87                 Ok(buf[0])
88         }
89 }
90
91 impl Writeable for bool {
92         #[inline]
93         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
94                 writer.write_all(&[if *self {1} else {0}])
95         }
96 }
97 impl<R: Read> Readable<R> for bool {
98         #[inline]
99         fn read(reader: &mut R) -> Result<bool, DecodeError> {
100                 let mut buf = [0; 1];
101                 reader.read_exact(&mut buf)?;
102                 if buf[0] != 0 && buf[0] != 1 {
103                         return Err(DecodeError::InvalidValue);
104                 }
105                 Ok(buf[0] == 1)
106         }
107 }
108
109 // u8 arrays
110 macro_rules! impl_array {
111         ( $size:expr ) => (
112                 impl Writeable for [u8; $size]
113                 {
114                         #[inline]
115                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
116                                 w.write_all(self)
117                         }
118                 }
119
120                 impl<R: Read> Readable<R> for [u8; $size]
121                 {
122                         #[inline]
123                         fn read(r: &mut R) -> Result<Self, DecodeError> {
124                                 let mut buf = [0u8; $size];
125                                 r.read_exact(&mut buf)?;
126                                 Ok(buf)
127                         }
128                 }
129         );
130 }
131
132 //TODO: performance issue with [u8; size] with impl_array!()
133 impl_array!(32); // for channel id & hmac
134 impl_array!(33); // for PublicKey
135 impl_array!(64); // for Signature
136 impl_array!(1300); // for OnionPacket.hop_data
137
138 // HashMap
139 impl<K, V> Writeable for HashMap<K, V>
140         where K: Writeable + Eq + Hash,
141               V: Writeable
142 {
143         #[inline]
144         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
145         (self.len() as u16).write(w)?;
146                 for (key, value) in self.iter() {
147                         key.write(w)?;
148                         value.write(w)?;
149                 }
150                 Ok(())
151         }
152 }
153
154 impl<R, K, V> Readable<R> for HashMap<K, V>
155         where R: Read,
156               K: Readable<R> + Eq + Hash,
157               V: Readable<R>
158 {
159         #[inline]
160         fn read(r: &mut R) -> Result<Self, DecodeError> {
161                 let len: u16 = Readable::read(r)?;
162                 let mut ret = HashMap::with_capacity(len as usize);
163                 for _ in 0..len {
164                         ret.insert(K::read(r)?, V::read(r)?);
165                 }
166                 Ok(ret)
167         }
168 }
169
170 // Vectors
171 impl Writeable for Vec<u8> {
172         #[inline]
173         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
174                 (self.len() as u16).write(w)?;
175                 w.write_all(&self)
176         }
177 }
178
179 impl<R: Read> Readable<R> for Vec<u8> {
180         #[inline]
181         fn read(r: &mut R) -> Result<Self, DecodeError> {
182                 let len: u16 = Readable::read(r)?;
183                 let mut ret = Vec::with_capacity(len as usize);
184                 ret.resize(len as usize, 0);
185                 r.read_exact(&mut ret)?;
186                 Ok(ret)
187         }
188 }
189 impl Writeable for Vec<Signature> {
190         #[inline]
191         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
192                 (self.len() as u16).write(w)?;
193                 for e in self.iter() {
194                         e.write(w)?;
195                 }
196                 Ok(())
197         }
198 }
199
200 impl<R: Read> Readable<R> for Vec<Signature> {
201         #[inline]
202         fn read(r: &mut R) -> Result<Self, DecodeError> {
203                 let len: u16 = Readable::read(r)?;
204                 let byte_size = (len as usize)
205                                 .checked_mul(33)
206                                 .ok_or(DecodeError::BadLengthDescriptor)?;
207                 if byte_size > MAX_BUF_SIZE {
208                         return Err(DecodeError::BadLengthDescriptor);
209                 }
210                 let mut ret = Vec::with_capacity(len as usize);
211                 for _ in 0..len { ret.push(Signature::read(r)?); }
212                 Ok(ret)
213         }
214 }
215
216 impl Writeable for Script {
217         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
218                 (self.len() as u16).write(w)?;
219                 w.write_all(self.as_bytes())
220         }
221 }
222
223 impl<R: Read> Readable<R> for Script {
224         fn read(r: &mut R) -> Result<Self, DecodeError> {
225                 let len = <u16 as Readable<R>>::read(r)? as usize;
226                 let mut buf = vec![0; len];
227                 r.read_exact(&mut buf)?;
228                 Ok(Script::from(buf))
229         }
230 }
231
232 impl Writeable for Option<Script> {
233         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
234                 if let &Some(ref script) = self {
235                         script.write(w)?;
236                 }
237                 Ok(())
238         }
239 }
240
241 impl<R: Read> Readable<R> for Option<Script> {
242         fn read(r: &mut R) -> Result<Self, DecodeError> {
243                 match <u16 as Readable<R>>::read(r) {
244                         Ok(len) => {
245                                 let mut buf = vec![0; len as usize];
246                                 r.read_exact(&mut buf)?;
247                                 Ok(Some(Script::from(buf)))
248                         },
249                         Err(DecodeError::ShortRead) => Ok(None),
250                         Err(e) => Err(e)
251                 }
252         }
253 }
254
255 impl Writeable for PublicKey {
256         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
257                 self.serialize().write(w)
258         }
259 }
260
261 impl<R: Read> Readable<R> for PublicKey {
262         fn read(r: &mut R) -> Result<Self, DecodeError> {
263                 let buf: [u8; 33] = Readable::read(r)?;
264                 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
265                         Ok(key) => Ok(key),
266                         Err(_) => return Err(DecodeError::BadPublicKey),
267                 }
268         }
269 }
270
271 impl Writeable for Sha256dHash {
272         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
273                 self.as_bytes().write(w)
274         }
275 }
276
277 impl<R: Read> Readable<R> for Sha256dHash {
278         fn read(r: &mut R) -> Result<Self, DecodeError> {
279                 let buf: [u8; 32] = Readable::read(r)?;
280                 Ok(From::from(&buf[..]))
281         }
282 }
283
284 impl Writeable for Signature {
285         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
286                 self.serialize_compact(&Secp256k1::without_caps()).write(w)
287         }
288 }
289
290 impl<R: Read> Readable<R> for Signature {
291         fn read(r: &mut R) -> Result<Self, DecodeError> {
292                 let buf: [u8; 64] = Readable::read(r)?;
293                 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
294                         Ok(sig) => Ok(sig),
295                         Err(_) => return Err(DecodeError::BadSignature),
296                 }
297         }
298 }