X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Fser.rs;h=484d603404297d6aaf4e6c59f8f46af2a86fb4dc;hb=c558ccd6a92fa9034929769f55e65bf9c1336abd;hp=7971f35fc97ce6ef0c8ec9c5dba4348cfdce697b;hpb=c86cacd29d72c0af62cfd29d78dcf17a6d8f8c71;p=rust-lightning diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index 7971f35f..484d6034 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -29,7 +29,7 @@ use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SI use bitcoin::secp256k1::ecdsa; use bitcoin::secp256k1::schnorr; use bitcoin::blockdata::constants::ChainHash; -use bitcoin::blockdata::script::{self, Script}; +use bitcoin::blockdata::script::{self, ScriptBuf}; use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut}; use bitcoin::{consensus, Witness}; use bitcoin::consensus::Encodable; @@ -199,8 +199,14 @@ pub trait Writeable { /// Writes `self` out to a `Vec`. fn encode(&self) -> Vec { - let mut msg = VecWriter(Vec::new()); + let len = self.serialized_length(); + let mut msg = VecWriter(Vec::with_capacity(len)); self.write(&mut msg).unwrap(); + // Note that objects with interior mutability may change size between when we called + // serialized_length and when we called write. That's okay, but shouldn't happen during + // testing as most of our tests are not threaded. + #[cfg(test)] + debug_assert_eq!(len, msg.0.len()); msg.0 } @@ -211,6 +217,7 @@ pub trait Writeable { 0u16.write(&mut msg).unwrap(); self.write(&mut msg).unwrap(); let len = msg.0.len(); + debug_assert_eq!(len - 2, self.serialized_length()); msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes()); msg.0 } @@ -364,14 +371,14 @@ impl Writeable for BigSize { #[inline] fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self.0 { - 0...0xFC => { + 0..=0xFC => { (self.0 as u8).write(writer) }, - 0xFD...0xFFFF => { + 0xFD..=0xFFFF => { 0xFDu8.write(writer)?; (self.0 as u16).write(writer) }, - 0x10000...0xFFFFFFFF => { + 0x10000..=0xFFFFFFFF => { 0xFEu8.write(writer)?; (self.0 as u32).write(writer) }, @@ -668,14 +675,14 @@ impl<'a, T> From<&'a Vec> for WithoutLength<&'a Vec> { fn from(v: &'a Vec) -> Self { Self(v) } } -impl Writeable for WithoutLength<&Script> { +impl Writeable for WithoutLength<&ScriptBuf> { #[inline] fn write(&self, writer: &mut W) -> Result<(), io::Error> { writer.write_all(self.0.as_bytes()) } } -impl Readable for WithoutLength