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;
13 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
15 const MAX_BUF_SIZE: usize = 64 * 1024;
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
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);
29 impl<W: ::std::io::Write> Writer for W {
31 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
32 <Self as ::std::io::Write>::write_all(self, buf)
35 fn size_hint(&mut self, _size: usize) { }
38 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
39 pub trait Writeable<W: Writer> {
40 /// Writes self out to the given Writer
41 fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
44 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
49 /// Reads a Self in from the given Read
50 fn read(reader: &mut R) -> Result<Self, DecodeError>;
53 macro_rules! impl_writeable_primitive {
54 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
55 impl<W: Writer> Writeable<W> for $val_type {
57 fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
58 writer.write_all(&$meth_write(*self))
61 impl<R: Read> Readable<R> for $val_type {
63 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
64 let mut buf = [0; $len];
65 reader.read_exact(&mut buf)?;
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);
76 impl<W: Writer> Writeable<W> for u8 {
78 fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79 writer.write_all(&[*self])
82 impl<R: Read> Readable<R> for u8 {
84 fn read(reader: &mut R) -> Result<u8, DecodeError> {
86 reader.read_exact(&mut buf)?;
91 impl<W: Writer> Writeable<W> for bool {
93 fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
94 writer.write_all(&[if *self {1} else {0}])
97 impl<R: Read> Readable<R> for bool {
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);
110 macro_rules! impl_array {
112 impl<W: Writer> Writeable<W> for [u8; $size]
115 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
120 impl<R: Read> Readable<R> for [u8; $size]
123 fn read(r: &mut R) -> Result<Self, DecodeError> {
124 let mut buf = [0u8; $size];
125 r.read_exact(&mut buf)?;
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
139 impl<W, K, V> Writeable<W> for HashMap<K, V>
141 K: Writeable<W> + Eq + Hash,
145 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
146 (self.len() as u16).write(w)?;
147 for (key, value) in self.iter() {
155 impl<R, K, V> Readable<R> for HashMap<K, V>
157 K: Readable<R> + Eq + Hash,
161 fn read(r: &mut R) -> Result<Self, DecodeError> {
162 let len: u16 = Readable::read(r)?;
163 let mut ret = HashMap::with_capacity(len as usize);
165 ret.insert(K::read(r)?, V::read(r)?);
172 impl<W: Writer> Writeable<W> for Vec<u8> {
174 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
175 (self.len() as u16).write(w)?;
180 impl<R: Read> Readable<R> for Vec<u8> {
182 fn read(r: &mut R) -> Result<Self, DecodeError> {
183 let len: u16 = Readable::read(r)?;
184 let mut ret = Vec::with_capacity(len as usize);
185 ret.resize(len as usize, 0);
186 r.read_exact(&mut ret)?;
190 impl<W: Writer> Writeable<W> for Vec<Signature> {
192 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
193 (self.len() as u16).write(w)?;
194 for e in self.iter() {
201 impl<R: Read> Readable<R> for Vec<Signature> {
203 fn read(r: &mut R) -> Result<Self, DecodeError> {
204 let len: u16 = Readable::read(r)?;
205 let byte_size = (len as usize)
207 .ok_or(DecodeError::BadLengthDescriptor)?;
208 if byte_size > MAX_BUF_SIZE {
209 return Err(DecodeError::BadLengthDescriptor);
211 let mut ret = Vec::with_capacity(len as usize);
212 for _ in 0..len { ret.push(Signature::read(r)?); }
217 impl<W: Writer> Writeable<W> for Script {
218 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
219 (self.len() as u16).write(w)?;
220 w.write_all(self.as_bytes())
224 impl<R: Read> Readable<R> for Script {
225 fn read(r: &mut R) -> Result<Self, DecodeError> {
226 let len = <u16 as Readable<R>>::read(r)? as usize;
227 let mut buf = vec![0; len];
228 r.read_exact(&mut buf)?;
229 Ok(Script::from(buf))
233 impl<W: Writer> Writeable<W> for Option<Script> {
234 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
235 if let &Some(ref script) = self {
242 impl<R: Read> Readable<R> for Option<Script> {
243 fn read(r: &mut R) -> Result<Self, DecodeError> {
244 match <u16 as Readable<R>>::read(r) {
246 let mut buf = vec![0; len as usize];
247 r.read_exact(&mut buf)?;
248 Ok(Some(Script::from(buf)))
250 Err(DecodeError::ShortRead) => Ok(None),
256 impl<W: Writer> Writeable<W> for PublicKey {
257 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
258 self.serialize().write(w)
262 impl<R: Read> Readable<R> for PublicKey {
263 fn read(r: &mut R) -> Result<Self, DecodeError> {
264 let buf: [u8; 33] = Readable::read(r)?;
265 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
267 Err(_) => return Err(DecodeError::BadPublicKey),
272 impl<W: Writer> Writeable<W> for Sha256dHash {
273 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
274 self.as_bytes().write(w)
278 impl<R: Read> Readable<R> for Sha256dHash {
279 fn read(r: &mut R) -> Result<Self, DecodeError> {
280 let buf: [u8; 32] = Readable::read(r)?;
281 Ok(From::from(&buf[..]))
285 impl<W: Writer> Writeable<W> for Signature {
286 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
287 self.serialize_compact(&Secp256k1::without_caps()).write(w)
291 impl<R: Read> Readable<R> for Signature {
292 fn read(r: &mut R) -> Result<Self, DecodeError> {
293 let buf: [u8; 64] = Readable::read(r)?;
294 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
296 Err(_) => return Err(DecodeError::BadSignature),