1 use std::result::Result;
3 use std::collections::HashMap;
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;
14 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
16 const MAX_BUF_SIZE: usize = 64 * 1024;
18 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
19 /// buffers being written into.
20 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
23 /// Writes the given buf out. See std::io::Write::write_all for more
24 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
25 /// Hints that data of the given size is about the be written. This may not always be called
26 /// prior to data being written and may be safely ignored.
27 fn size_hint(&mut self, size: usize);
30 impl<W: ::std::io::Write> Writer for W {
32 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
33 <Self as ::std::io::Write>::write_all(self, buf)
36 fn size_hint(&mut self, _size: usize) { }
39 struct VecWriter(Vec<u8>);
40 impl Writer for VecWriter {
41 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
42 self.0.extend_from_slice(buf);
45 fn size_hint(&mut self, size: usize) {
46 self.0.reserve_exact(size);
50 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
52 /// Writes self out to the given Writer
53 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
55 /// Writes self out to a Vec<u8>
56 fn encode(&self) -> Vec<u8> {
57 let mut msg = VecWriter(Vec::new());
58 self.write(&mut msg).unwrap();
62 /// Writes self out to a Vec<u8>
63 fn encode_with_len(&self) -> Vec<u8> {
64 let mut msg = VecWriter(Vec::new());
65 0u16.write(&mut msg).unwrap();
66 self.write(&mut msg).unwrap();
67 let len = msg.0.len();
68 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
73 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
78 /// Reads a Self in from the given Read
79 fn read(reader: &mut R) -> Result<Self, DecodeError>;
82 macro_rules! impl_writeable_primitive {
83 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
84 impl Writeable for $val_type {
86 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
87 writer.write_all(&$meth_write(*self))
90 impl<R: Read> Readable<R> for $val_type {
92 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
93 let mut buf = [0; $len];
94 reader.read_exact(&mut buf)?;
101 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
102 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
103 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
105 impl Writeable for u8 {
107 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
108 writer.write_all(&[*self])
111 impl<R: Read> Readable<R> for u8 {
113 fn read(reader: &mut R) -> Result<u8, DecodeError> {
114 let mut buf = [0; 1];
115 reader.read_exact(&mut buf)?;
120 impl Writeable for bool {
122 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
123 writer.write_all(&[if *self {1} else {0}])
126 impl<R: Read> Readable<R> for bool {
128 fn read(reader: &mut R) -> Result<bool, DecodeError> {
129 let mut buf = [0; 1];
130 reader.read_exact(&mut buf)?;
131 if buf[0] != 0 && buf[0] != 1 {
132 return Err(DecodeError::InvalidValue);
139 macro_rules! impl_array {
141 impl Writeable for [u8; $size]
144 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
149 impl<R: Read> Readable<R> for [u8; $size]
152 fn read(r: &mut R) -> Result<Self, DecodeError> {
153 let mut buf = [0u8; $size];
154 r.read_exact(&mut buf)?;
161 //TODO: performance issue with [u8; size] with impl_array!()
162 impl_array!(32); // for channel id & hmac
163 impl_array!(33); // for PublicKey
164 impl_array!(64); // for Signature
165 impl_array!(1300); // for OnionPacket.hop_data
168 impl<K, V> Writeable for HashMap<K, V>
169 where K: Writeable + Eq + Hash,
173 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
174 (self.len() as u16).write(w)?;
175 for (key, value) in self.iter() {
183 impl<R, K, V> Readable<R> for HashMap<K, V>
185 K: Readable<R> + Eq + Hash,
189 fn read(r: &mut R) -> Result<Self, DecodeError> {
190 let len: u16 = Readable::read(r)?;
191 let mut ret = HashMap::with_capacity(len as usize);
193 ret.insert(K::read(r)?, V::read(r)?);
200 impl Writeable for Vec<u8> {
202 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
203 (self.len() as u16).write(w)?;
208 impl<R: Read> Readable<R> for Vec<u8> {
210 fn read(r: &mut R) -> Result<Self, DecodeError> {
211 let len: u16 = Readable::read(r)?;
212 let mut ret = Vec::with_capacity(len as usize);
213 ret.resize(len as usize, 0);
214 r.read_exact(&mut ret)?;
218 impl Writeable for Vec<Signature> {
220 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
221 (self.len() as u16).write(w)?;
222 for e in self.iter() {
229 impl<R: Read> Readable<R> for Vec<Signature> {
231 fn read(r: &mut R) -> Result<Self, DecodeError> {
232 let len: u16 = Readable::read(r)?;
233 let byte_size = (len as usize)
235 .ok_or(DecodeError::BadLengthDescriptor)?;
236 if byte_size > MAX_BUF_SIZE {
237 return Err(DecodeError::BadLengthDescriptor);
239 let mut ret = Vec::with_capacity(len as usize);
240 for _ in 0..len { ret.push(Signature::read(r)?); }
245 impl Writeable for Script {
246 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
247 (self.len() as u16).write(w)?;
248 w.write_all(self.as_bytes())
252 impl<R: Read> Readable<R> for Script {
253 fn read(r: &mut R) -> Result<Self, DecodeError> {
254 let len = <u16 as Readable<R>>::read(r)? as usize;
255 let mut buf = vec![0; len];
256 r.read_exact(&mut buf)?;
257 Ok(Script::from(buf))
261 impl Writeable for Option<Script> {
262 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
263 if let &Some(ref script) = self {
270 impl<R: Read> Readable<R> for Option<Script> {
271 fn read(r: &mut R) -> Result<Self, DecodeError> {
272 match <u16 as Readable<R>>::read(r) {
274 let mut buf = vec![0; len as usize];
275 r.read_exact(&mut buf)?;
276 Ok(Some(Script::from(buf)))
278 Err(DecodeError::ShortRead) => Ok(None),
284 impl Writeable for PublicKey {
285 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
286 self.serialize().write(w)
290 impl<R: Read> Readable<R> for PublicKey {
291 fn read(r: &mut R) -> Result<Self, DecodeError> {
292 let buf: [u8; 33] = Readable::read(r)?;
293 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
295 Err(_) => return Err(DecodeError::BadPublicKey),
300 impl Writeable for Sha256dHash {
301 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
302 self.as_bytes().write(w)
306 impl<R: Read> Readable<R> for Sha256dHash {
307 fn read(r: &mut R) -> Result<Self, DecodeError> {
308 let buf: [u8; 32] = Readable::read(r)?;
309 Ok(From::from(&buf[..]))
313 impl Writeable for Signature {
314 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
315 self.serialize_compact(&Secp256k1::without_caps()).write(w)
319 impl<R: Read> Readable<R> for Signature {
320 fn read(r: &mut R) -> Result<Self, DecodeError> {
321 let buf: [u8; 64] = Readable::read(r)?;
322 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
324 Err(_) => return Err(DecodeError::BadSignature),